Skip to main content

Simplifies class-based views for more organized and maintainable code in FastAPI.

Project description

Class

Classes and Decorators to use FastAPI with Class based routing

Continuous Integration Package version Supported Python versions Test


Source Code: https://github.com/yezz123/fastapi-class

Install the project: pip install fastapi-class


As you create more complex FastAPI applications, you may find yourself frequently repeating the same dependencies in multiple related endpoints.

A common question people have as they become more comfortable with FastAPI is how they can reduce the number of times they have to copy/paste the same dependency into related routes.

fastapi_class provides a class-based view decorator @View to help reduce the amount of boilerplate necessary when developing related routes.

Highly inspired by Fastapi-utils, Thanks to @dmontagu for the great work.

  • Example:
from fastapi import FastAPI, Query
from pydantic import BaseModel
from fastapi_class import View

app = FastAPI()

class ItemModel(BaseModel):
    id: int
    name: str
    description: str = None

@View(app)
class ItemView:
    async def post(self, item: ItemModel):
        return item

    async def get(self, item_id: int = Query(..., gt=0)):
        return {"item_id": item_id}

Response model 📦

Exception in list need to be either function that return fastapi.HTTPException itself. In case of a function it is required to have all of it's arguments to be optional.

from fastapi import FastAPI, HTTPException, status
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel

from fastapi_class import View

app = FastAPI()

NOT_AUTHORIZED = HTTPException(401, "Not authorized.")
NOT_ALLOWED = HTTPException(405, "Method not allowed.")
NOT_FOUND = lambda item_id="item_id": HTTPException(404, f"Item with {item_id} not found.")

class ItemResponse(BaseModel):
    field: str | None = None

@View(app)
class MyView:
    exceptions = {
        "__all__": [NOT_AUTHORIZED],
        "put": [NOT_ALLOWED, NOT_FOUND]
    }

    RESPONSE_MODEL = {
        "put": ItemResponse
    }

    RESPONSE_CLASS = {
        "delete": PlainTextResponse
    }

    async def get(self):
        ...

    async def put(self):
        ...

    async def delete(self):
        ...

Customized Endpoints

from fastapi import FastAPI, HTTPException
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel

from fastapi_class import View, endpoint

app = FastAPI()

NOT_AUTHORIZED = HTTPException(401, "Not authorized.")
NOT_ALLOWED = HTTPException(405, "Method not allowed.")
NOT_FOUND = lambda item_id="item_id": HTTPException(404, f"Item with {item_id} not found.")
EXCEPTION = HTTPException(400, "Example.")

class UserResponse(BaseModel):
    field: str | None = None

@View(app)
class MyView:
    exceptions = {
        "__all__": [NOT_AUTHORIZED],
        "put": [NOT_ALLOWED, NOT_FOUND],
        "edit": [EXCEPTION]
    }

    RESPONSE_MODEL = {
        "put": UserResponse,
        "edit": UserResponse
    }

    RESPONSE_CLASS = {
        "delete": PlainTextResponse
    }

    async def get(self):
        ...

    async def put(self):
        ...

    async def delete(self):
        ...

    @endpoint(("PUT"), path="edit")
    async def edit(self):
        ...

Note: The edit() endpoint is decorated with the @endpoint(("PUT",), path="edit") decorator, which specifies that this endpoint should handle PUT requests to the /edit path, using @endpoint("PUT", path="edit") has the same effect

Development 🚧

Setup environment 📦

Note: You should have uv installed, if not you can install it with:

pip install uv

Then you can install the dependencies with:

# Install dependencies
uv sync --all-extras

Run tests 🌝

You can run all the tests with:

bash scripts/test.sh

Format the code 🍂

Execute the following command to apply pre-commit formatting:

bash scripts/format.sh

Execute the following command to apply mypy type checking:

bash scripts/lint.sh

License

This project is licensed under the terms of the MIT license.

Project details


Download files

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

Source Distribution

fastapi_class-3.7.0.tar.gz (55.7 kB view details)

Uploaded Source

Built Distribution

fastapi_class-3.7.0-py3-none-any.whl (9.4 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_class-3.7.0.tar.gz.

File metadata

  • Download URL: fastapi_class-3.7.0.tar.gz
  • Upload date:
  • Size: 55.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for fastapi_class-3.7.0.tar.gz
Algorithm Hash digest
SHA256 0f36cab68c30661008ae8c210e8ba27f78d1df127591fc65c2623c16c28cb3e8
MD5 edabd8d5f6cc2779bfc3f6969bbdc140
BLAKE2b-256 9a3df3c2bc700a982a9a4cd56fda90c8cb04eabf2218478d24bae6569ff80c42

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_class-3.7.0.tar.gz:

Publisher: release.yml on yezz123/fastapi-class

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file fastapi_class-3.7.0-py3-none-any.whl.

File metadata

  • Download URL: fastapi_class-3.7.0-py3-none-any.whl
  • Upload date:
  • Size: 9.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.0.1 CPython/3.12.8

File hashes

Hashes for fastapi_class-3.7.0-py3-none-any.whl
Algorithm Hash digest
SHA256 21f28355d32cdd7de6e4790c49a3cb4c192264e3fb6518b5fe7ec0bc20591c66
MD5 4a0f2452cbeef0a4b92a115071c51ae6
BLAKE2b-256 54d75c71e17d05d3f818fa1ed2b6533bb52f825ac925b3f2941bf334a468391e

See more details on using hashes here.

Provenance

The following attestation bundles were made for fastapi_class-3.7.0-py3-none-any.whl:

Publisher: release.yml on yezz123/fastapi-class

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page