/fastapi-template

Template for FastAPI services.

Primary LanguagePythonMIT LicenseMIT

fastapi-template

Template for FastAPI services.

The choice of state-of-the-art libraries balance simplicity and ease of use but you can switch them out if you want.

Please find some nice workspace defaults in .vscode if you use VSCode.

Recommended Stack

Infrastructure

Additionally I provide some shell scripts in bin to get you started with your deployment with:

Libraries

Decisions

  • Against black since it's not configurable and leads to less readable code

  • Against psycopg2 which is great for synchronous code but 5x slower than asyncpg in most use cases

  • Against requests since it's not async and httpx is basically a drop-in replacement

  • Against poetry since breaks every now and then, doesn't follow standards and most features are not needed

Setup

Use asdf to switch between Python versions.

make

Guidelines

Get ruff up and running in your IDE.

Structure

  • Flat, based on features, not layers

  • Use technical suffixes

  • Don't start with Pydantic schemas or SQLAlchemy models but evolve into them

Tests

For each router, add an http file which contains at least one happy path request for each endpoint.

Responses

Don't use fastapi.responses.*, e.g. JSONResponse or Response.

The CORS middleware won't be applied and the correct headers won't be set resulting in the response not to be readable in the frontend.

Use app.response.JsonResponse.

Exceptions

There's only one type of exception you should raise, CustomError and it must look like this:

CustomError(
    code: int,
    key: str,
    message: str | None
    details: dict | None,
)

Dump everything you want in details.