Skip to main content

fsrest

fsrest provides reusable single-resource REST CRUD orchestration with action names familiar to Django REST Framework users. It is framework-independent: request and response objects are Pydantic models, while persistence is supplied through a small repository protocol.

Designed and developed by Codex.

Install

pip install fsrest

Python 3.9+ and Pydantic 1.10/2.x are supported.

DRF-style actions

CrudViewSet follows DRF's standard action vocabulary:

  • list
  • retrieve
  • create
  • update
  • partial_update
  • destroy

It is deliberately not an HTTP view and does not depend on Django. A FastAPI, Flask, Django, or other framework adapter can call these actions after request validation.

Bind a repository to CrudViewSet. Request schemas provide the conversion methods needed to turn HTTP-facing data into repository fields.

from pydantic import BaseModel
from fsrest import CrudViewSet, PageRequest, PageResponse

class Item(BaseModel):
    id: str
    name: str

class Filters(BaseModel):
    name: str | None = None

class Ordering(BaseModel):
    field: str = "id"

class PageData(BaseModel):
    items: list[Item]
    total: int

class ListQuery(PageRequest):
    name: str | None = None

    def build_filters(self) -> Filters:
        return Filters(name=self.name)

    def build_ordering(self) -> Ordering:
        return Ordering()

    def build_response(self, *, page_data: PageData) -> PageResponse[Item]:
        return PageResponse[Item](
            items=page_data.items,
            total=page_data.total,
            page=self.page,
            page_size=self.page_size,
        )

class ItemRepository:
    @classmethod
    def list_schema_page(cls, *, filters, ordering, page, page_size) -> PageData:
        ...

    # Also implement get_schema_by_id, create_schema,
    # update_schema_by_id, and delete_by_id.

class ItemViewSet(CrudViewSet):
    repository = ItemRepository

Framework code can now use familiar action names:

page = ItemViewSet.list(query=query)
item = ItemViewSet.retrieve(query=lookup)
created = ItemViewSet.create(payload=create_payload)
updated = ItemViewSet.update(payload=update_payload)
patched = ItemViewSet.partial_update(payload=patch_payload)
result = ItemViewSet.destroy(payload=delete_payload)

Customizing behavior

Subclass a viewset and override only the smallest relevant hook. The public actions stay unchanged, so framework adapters do not need special cases.

class TenantItemViewSet(ItemViewSet):
    not_found_message = "Item {lookup_value} does not exist"

    @classmethod
    def get_repository(cls):
        # Select a repository at runtime, for example by tenant context.
        return repository_for_current_tenant()

    @classmethod
    def get_filters(cls, query):
        filters = super().get_filters(query)
        return filters.model_copy(update={"tenant_id": current_tenant_id()})

    @classmethod
    def perform_create(cls, fields):
        item = super().perform_create(fields)
        publish_item_created(item)
        return item

Available customization layers:

Concern Hook
Runtime persistence selection get_repository
URL/request lookup extraction get_lookup_value
Object loading get_object
Filters and ordering get_filters, get_ordering
Pagination execution paginate
List response construction build_list_response
Create/update field conversion get_create_fields, get_update_fields
Persistence side effects perform_create, perform_update, perform_destroy
Error construction and messages get_exception, handle_not_found, handle_destroy_failure

get_update_fields(payload, partial=...) receives whether the caller used update or partial_update, so applications can implement PUT/PATCH semantics without replacing either action.

The library raises RestApiError for missing records and failed deletes. To integrate with an application's existing exception middleware, subclass it and bind error_class:

class ApplicationApiError(RestApiError):
    error_code = 400455

class ItemViewSet(CrudViewSet):
    repository = ItemRepository
    error_class = ApplicationApiError

Migrating from 0.1

The 0.1 API remains available for compatibility. New code should prefer these names:

0.1 API 0.2 API
RestCrudLogicBase CrudViewSet
dao_rest_crud repository
list_items list
get_item retrieve
create_item create
update_item update
delete_item destroy
RestPageReqSchema PageRequest
RestPageRespSchema PageResponse
RestDeleteRespSchema DestroyResponse

Development and publishing

From the pytools repository root, use the unified release script:

python make.py fsrest test
python make.py fsrest build
python make.py fsrest publish

publish uploads the artifacts under fsrest/dist/ using the PyPI credentials configured in ~/.pypirc. Before publishing a new release, update the version in pyproject.toml, run tests, and build fresh artifacts.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fsrest-0.3.0.tar.gz (33.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fsrest-0.3.0-py3-none-any.whl (9.3 kB view details)

Uploaded Python 3

File details

Details for the file fsrest-0.3.0.tar.gz.

File metadata

  • Download URL: fsrest-0.3.0.tar.gz
  • Upload date:
  • Size: 33.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.14.2

File hashes

Hashes for fsrest-0.3.0.tar.gz
Algorithm Hash digest
SHA256 e372134a9982084650a26504fe3b6780f8b158e7f77a5c0e7757f2bef64b052f
MD5 57ed5e55984b28b8631c336db2ed1db1
BLAKE2b-256 714a99807a6192f43d5133d9e8649e4ef63f55a3b9ebaaba52dd48a3b052b35b

See more details on using hashes here.

File details

Details for the file fsrest-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: fsrest-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 9.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.14.2

File hashes

Hashes for fsrest-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5c30e331e13dbf5b339a83d17d860787de4d5307f384913b597ed96f23c3267c
MD5 3e174af659d95eef7ef1da688a686604
BLAKE2b-256 aac40aab5460dc7718f60873168aeb168383cb72a35a98c706470e97a5b7246f

See more details on using hashes here.

Release history Release notifications | RSS feed

0.4.0

2 files

This release

0.3.0 This release

2 files

0.2.0

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page