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

Test Package version Supported Python versions


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, APIRouter, Query
from pydantic import BaseModel
from fastapi_class import View

app = FastAPI()
router = APIRouter()

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

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

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

app.include_router(router)

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, APIRouter, HTTPException, status
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel

from fastapi_class import View

app = FastAPI()
router = APIRouter()

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(router)
class MyView:
    exceptions = {
        "__all__": [NOT_AUTHORIZED],
        "put": [NOT_ALLOWED, NOT_FOUND]
    }

    RESPONSE_MODEL = {
        "put": ItemResponse
    }

    RESPONSE_CLASS = {
        "delete": PlainTextResponse
    }

    def get(self):
        ...
    def put(self):
        ...
    def delete(self):
        ...

app.include_router(router)

Customized Endpoints

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

from fastapi_class import View, endpoint

app = FastAPI()
router = APIRouter()

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(router)
class MyView:
    exceptions = {
        "__all__": [NOT_AUTHORIZED],
        "put": [NOT_ALLOWED, NOT_FOUND],
        "edit": [EXCEPTION]
    }

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

    RESPONSE_CLASS = {
        "delete": PlainTextResponse
    }

    def get(self):
        ...
    def put(self):
        ...
    def delete(self):
        ...
    @endpoint(("PUT",), path="edit")
    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.

Development 🚧

Setup environment 📦

You should create a virtual environment and activate it:

python -m venv venv/
source venv/bin/activate

And then install the development dependencies:

# Install dependencies
pip install -e .[test,lint]

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.1.0.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

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

fastapi_class-3.1.0-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: fastapi_class-3.1.0.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.11.2

File hashes

Hashes for fastapi_class-3.1.0.tar.gz
Algorithm Hash digest
SHA256 632d131638621733d78d6cf76a380dbb9e30aa776583dd05fb2fb1493a14ce43
MD5 bf0a4c123f758418099a042e08edb728
BLAKE2b-256 995008727e37640f669b32331a9f2b7c2c8df9ac86ee529e45bc50baf7aea824

See more details on using hashes here.

File details

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

File metadata

  • Download URL: fastapi_class-3.1.0-py3-none-any.whl
  • Upload date:
  • Size: 9.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.11.2

File hashes

Hashes for fastapi_class-3.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d940f4184d4bd2f0100ffb5fd55357989cd1bdc466c891b64bb69af022f453e8
MD5 455f95e503fade587c4c9d78f75fca07
BLAKE2b-256 e3c8701844559e6ddd1cb4b45d25a6830aa720fcd7d579515c8cf6f46501226c

See more details on using hashes here.

Supported by

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