r/FastAPI • • Dec 14 '21

Tutorial A neat trick for async database session dependencies

25 Upvotes

I'm using SQLAlchemy 1.4 with async I/O to a PostgreSQL database. I want request-scoped transactions, i.e. transactions will be automatically committed at the end of any request that does database operations, or rolled back in the case of error. I don't want my path operation code to have to worry about transactions. After some experimentation this turned out to be pretty straightforward:

# dependencies.py
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

engine = create_async_engine(
    'postgresql+asyncpg://scott:[email protected]/test',
    echo=True, future=True
)

_async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

async def get_db() -> AsyncSession:
    '''
    Dependency function that yields db sessions
    '''
    async with _async_session() as session:
        yield session
        await session.commit()

Then in a path operation:

@router.post("/new")
async def widget_new(
    widget: WidgetModel,
    db: AsyncSession = Depends(get_db)
) -> dict:
    db_obj = Widget(**widget.dict())
    db.add(db_obj)
    return {}

Since the dependency on AsyncSession is going to appear in every path operation that uses the database (i.e. a lot), it would be nice if it could be simpler. FastAPI gives you a shortcut if the dependency is a class, allowing you to omit the parameters to Depends. In our example, however, the dependency is a function, and there's nothing fancy we can do in a class constructor because the dependency is an async generator function.

It turns out FastAPI is smart enough to insert dependencies for any callable, even if it's an override of the __new__ function. Simply add the following to the end of dependencies.py:

class DB(AsyncSession):
    def __new__(cls,db:AsyncSession = Depends(get_db)):
        return db

Now the path operation can look like this:

@router.post("/new")
async def widget_new(widget: WidgetModel, db: DB = Depends()) -> dict:
    db_obj = Widget(**widget.dict())
    db.add(db_obj)
    return {}

The session dependency is just about as minimal as it can be.

EDIT: while the "neat trick" part of this works fine to eliminate the need for parameters to Depends, the transaction management part of it doesn't work. You can't issue a commit inside a dependency function after the path operation has completed because the results will already have been returned to the api caller. Any exceptions at this point cannot affect execution, but the transaction will have been rolled back. I've documented a better way to do this using decorators at https://github.com/tiangolo/fastapi/issues/2662.


r/FastAPI • • Dec 10 '21

Other Template for high-performance applications. Based on MVC architectural pattern, WSGI + ASGI. Includes tests, pipelines, utilities, Helm chart, and script for bootstrapping local Minikube with HA Redis cluster.

Thumbnail
github.com
25 Upvotes

r/FastAPI • • Mar 31 '21

Tutorial Async SQLAlchemy with FastAPI

Thumbnail
stribny.name
25 Upvotes

r/FastAPI • • May 24 '26

Question Open-sourced a FastAPI recommendation system while learning backend architecture. Looking for feedback.

24 Upvotes

I’ve been building Shelftxt as a way to learn backend systems beyond CRUD APIs.

shelftxt started as one large FastAPI file handling routes, recommendation logic, and data operations. I recently refactored it into:

api → routes → services → repositories → ranking/preprocess

Current stack:

  • FastAPI

  • Python

  • Pandas

  • CSV storage (planning PostgreSQL next)

  • recommendation scoring

  • lru_cache caching

The goal isn’t really a book app. I’m more interested in learning:

  • backend architecture

  • data handling

  • repository patterns

  • recommendation systems

  • scaling APIs

Would appreciate feedback on the structure before I move toward Postgres and more persistent storage.

Repo:
https://github.com/tranguyeenn/shelftxt


r/FastAPI • • Apr 29 '26

Tutorial A Practical Guide to OpenTelemetry and FastAPI

Thumbnail
signoz.io
24 Upvotes

Hey folks, I recently revamped our article on Implementing OpenTelemetry in FastAPI Projects in a practical manner, which was originally written in 2024 and needed a fresh coat of paint.

The article covers auto-instrumentation, manual spans, visualizing metrics and how observability lets you understand how your web apps behave.
I've also included some advanced tips, such as, selective error tracking, and wrapping dependency functions to capture any operations within the `yield` scope.

If you are on the fence about observability, or have integrated it but don't really how it works, I believe this guide can help you out.

I personally would have benefitted from this writeup in my previous day job, where I worked with FastAPI microservices and learnt how OpenTelemetry worked the hard way.

Any feedback would be much appreciated, did I miss anything, is there scope for improvement? Please let me know. I'm also curious to understand what problems you face with monitoring your FastAPI web apps.


r/FastAPI • • Mar 21 '26

Question good tutorial for fast api, cant find a new good one

24 Upvotes

all the tutorials i see are 2 or 4 years old, is there a modern one i can use


r/FastAPI • • Feb 20 '26

feedback request I published FastAPI-Toolsets v1.0.0 — A set of tools to simplify and accelerate the creation of FastAPI projects

24 Upvotes

Hi everyone,

I just released v1.0.0 of fastapi-toolsets, a modular set of tools to accelerate and simplify the creation of FastAPI projects.

After a year of working on different FastAPI projects, I kept writing the same boilerplate over and over. So I extracted everything into a reusable, modular library.

A few things to know about this project:

- Async only: built entirely around async/await

- PostgreSQL + SQLAlchemy only: no plans to support other databases for now

- Modular: install only what you need, the base package stays lean and optional extras (`cli`, `metrics`, `pytest`) add features on top

Features

CRUD

- Generic async CRUD operations (`get`, `first`, `list`, `create`, `update`, `delete`, `upsert`)

- Pagination with metadata

- Full-text search with relationship traversal

- Many-to-many relationship handling

Database

- Session dependency factory for FastAPI routes

- Context managers for standalone usage (CLI, background tasks)

- Nested transactions with savepoints

- Table lock

- Row-change polling for event-driven flows

Dependencies

- `PathDependency`: auto-fetch a model from a URL path parameter

- `BodyDependency`: auto-fetch a model from a request body field

Schemas & Exceptions

- Generic API responses and errors

- Unified error response handler

- Auto-generated OpenAPI error documentation

Fixtures

- Decorator-based fixture registration

- Dependency-aware DB seeding with topological resolution

- Context-based loading and multiple load strategies

CLI (optional)

- Django-style `manager` command

- Built-in `fixtures list/load` subcommands + extensible with custom commands

Metrics (optional)

- Decorator-based metric registration

- Provider mode (registered once at startup) and collector mode (called on each scrape)

- Auto-mounted `/metrics` endpoint

- Multi-process compatible

Pytest helpers (optional)

- Pre-configured async HTTP client

- Isolated DB sessions for tests

- Per-worker test database (pytest-xdist compatible)

Links

- GitHub: https://github.com/d3vyce/fastapi-toolsets

- Docs: https://fastapi-toolsets.d3vyce.fr

- PyPI: uv add fastapi-toolsets

Feedback welcome!


r/FastAPI • • Jun 19 '25

Question What’s your go-to setup for FastAPI when prototyping something quickly?

24 Upvotes

Curious how folks here spin up FastAPI projects when you’re just testing ideas or building quick prototypes.

Do you start from a personal template? Use something like Cookiecutter?

Do you deploy manually, or use something like Railway/Vercel/etc.?

I’ve been messing around with an idea to make this faster, but before I share anything I just want to hear what setups people here actually use.


r/FastAPI • • Feb 05 '25

Question Naming SQLAlchemy models vs Pydantic models

24 Upvotes

Hi all, how do you generally deal with naming conventions between Pydantic and SQLAlchemy models? For example you have some object like Book. You can receive this from the user to create, or it might exist in your database. Do you differentiate these with e.g. BookSchema and DbBook? Some other prefix/suffix? Is there a convention that you've seen in some book or blog post that you like?


r/FastAPI • • Sep 25 '24

Question How do you handle pagination/sorting/filtering with fastAPI?

24 Upvotes

Hi, I'm new to fastAPI, and trying to implement things like pagination, sorting, and filtering via API.

First, I was a little surprised to notice there exists nothing natively for pagination, as it's a very common need for an API.

Then, I found fastapi-pagination package. While it seems great for my pagination needs, it does not handle sorting and filtering. I'd like to avoid adding a patchwork of micro-packages, especially if related to very close features.

Then, I found fastcrud package. This time it handles pagination, sorting, and filtering. But after browsing the doc, it seems pretty much complicated to use. I'm not sure if they enforce to use their "crud" features that seems to be a layer on top on the ORM. All their examples are fully async, while I'm using the examples from FastAPI doc. In short, this package seems a little overkill for what I actually need.

Now, I'm thinking that the best solution could be to implement it by myself, using inspiration from different packages and blog posts. But I'm not sure to be skilled enough to do this successfuly.

In short, I'm a little lost! Any guidance would be appreciated. Thanks.

EDIT: I did it by myself, thanks everyone, here is the code for pagination:

from typing import Annotated, Generic, TypeVar

from fastapi import Depends
from pydantic import BaseModel, Field
from sqlalchemy.sql import func
from sqlmodel import SQLModel, select
from sqlmodel.sql.expression import SelectOfScalar

from app.core.database import SessionDep

T = TypeVar("T", bound=SQLModel)

MAX_RESULTS_PER_PAGE = 50


class PaginationInput(BaseModel):
    """Model passed in the request to validate pagination input."""

    page: int = Field(default=1, ge=1, description="Requested page number")
    page_size: int = Field(
        default=10,
        ge=1,
        le=MAX_RESULTS_PER_PAGE,
        description="Requested number of items per page",
    )


class Page(BaseModel, Generic[T]):
    """Model to represent a page of results along with pagination metadata."""

    items: list[T] = Field(description="List of items on this Page")
    total_items: int = Field(ge=0, description="Number of total items")
    start_index: int = Field(ge=0, description="Starting item index")
    end_index: int = Field(ge=0, description="Ending item index")
    total_pages: int = Field(ge=0, description="Total number of pages")
    current_page: int = Field(ge=0, description="Page number (could differ from request)")
    current_page_size: int = Field(
        ge=0, description="Number of items per page (could differ from request)"
    )


def paginate(
    query: SelectOfScalar[T],  # SQLModel select query
    session: SessionDep,
    pagination_input: PaginationInput,
) -> Page[T]:
    """Paginate the given query based on the pagination input."""

    # Get the total number of items
    total_items = session.scalar(select(func.count()).select_from(query.subquery()))
    assert isinstance(
        total_items, int
    ), "A database error occurred when getting `total_items`"

    # Handle out-of-bounds page requests by going to the last page instead of displaying
    # empty data.
    total_pages = (
        total_items + pagination_input.page_size - 1
    ) // pagination_input.page_size
    # we don't want to have 0 page even if there is no item.
    total_pages = max(total_pages, 1)
    current_page = min(pagination_input.page, total_pages)

    # Calculate the offset for pagination
    offset = (current_page - 1) * pagination_input.page_size

    # Apply limit and offset to the query
    result = session.exec(query.offset(offset).limit(pagination_input.page_size))

    # Fetch the paginated items
    items = list(result.all())

    # Calculate the rest of pagination metadata
    start_index = offset + 1 if total_items > 0 else 0
    end_index = min(offset + pagination_input.page_size, total_items)

    # Return the paginated response using the Page model
    return Page[T](
        items=items,
        total_items=total_items,
        start_index=start_index,
        end_index=end_index,
        total_pages=total_pages,
        current_page_size=len(items),  # can differ from the requested page_size
        current_page=current_page,  # can differ from the requested page
    )


PaginationDep = Annotated[PaginationInput, Depends()]

Using it in a route:

from fastapi import APIRouter
from sqlmodel import select

from app.core.database import SessionDep
from app.core.pagination import Page, PaginationDep, paginate
from app.models.badge import Badge

router = APIRouter(prefix="/badges", tags=["Badges"])


@router.get("/", summary="Read all badges", response_model=Page[Badge])
def read_badges(session: SessionDep, pagination: PaginationDep):
    return paginate(select(Badge), session, pagination)

r/FastAPI • • Mar 04 '23

Tutorial Clean Architecture with FastAPI

24 Upvotes

r/FastAPI • • Jul 28 '21

Tutorial Using Redis with FastAPI (Async)

Thumbnail
developer.redislabs.com
24 Upvotes

r/FastAPI • • Jun 09 '21

Other Have to say... sometimes I miss Flask

24 Upvotes

I really like FastAPI, it's fast, the docs are great, the automatic openapi is awesome, the way you write routes and use pydantic is amazing. But... sometimes I really miss Flask.

I just miss a way to deal with settings. Flask's `current_app.config['config_var']` is great, easy, simple, intuitive, available, just great. I've spent quite a while reading and looking for different ways to implement a simple solution in FastAPI, using starlette's settings, pydantic's basesettings, but no success. Still looking for something nice.

Also don't really like the "depends" implementation. It seems that I always have to implement things with huge and lengthy function arguments, I almost always end up having to be have multi line function parameters, and I have to say I'm not the biggest fan... it's just as if the language wasn't made for that much params.

I've even considering going to Quart, but FastAPI seems more robust at the moment. Still ask myself whether FastAPI is worth for a normal web app api (vs Flask), but oh well... This is probably normal, and just because I'm not that used as I'm to Flask. We'll see.

Just some ranting, I'll probably get used it soon...

I also understand this is completely personal preference, and I'm sure the current implementation of FastAPI is perfect for a bunch of people, so not trying to diminish the framework in any way. I just miss Flask sometimes...


r/FastAPI • • Dec 01 '20

Tutorial Introducing FARM - FastAPI, React, and MongoDB (link to the repo in comments)

Thumbnail
developer.mongodb.com
24 Upvotes

r/FastAPI • • May 21 '26

Question ORMs to Pydantic models conversion

23 Upvotes

I'm developing a side project and trying to follow DDD principles as closely as possible. My current structure is router -> service -> repository. I'm using SQLAlchemy for ORM models, which are created and handled in the repository layer.

Right now, I convert those ORM objects into Pydantic models inside the service layer, and then pass those models to the router, which returns them in the response. I'm wondering whether this is the right approach or if there’s a better pattern for handling the conversion and data flow between layers.


r/FastAPI • • Jan 29 '26

Question How to handle major refactor with live users?

23 Upvotes

I shipped my first SaaS MVP a few months ago (React + FastAPI/Postgres/Redis stack) and after getting user feedback, I'm facing some major architectural decisions. Would love advice from folks who've been through this.

Current situation: Live product with paying customers User UI and admin UI (for customers, not me) are in the same React project

Backend needs significant model changes to support new features + modifications to existing ones

What I need to do:

  1. Split frontend into separate user and admin apps

  2. Major database schema changes

  3. Heavy backend refactoring for new features

My questions:

  • Should I version my API (v1 → v2) or try to migrate everything at once?

  • Frontend split: monorepo or separate repos? -How do you handle database migrations with live users? Maintenance window or incremental?

  • Is it better to build new features in parallel and switch over, or refactor incrementally?

I'm worried about breaking things for existing users while also not wanting to accumulate more tech debt. How have you handled major post-MVP refactors?

Tech stack: React, FastAPI, PostgreSQL, Redis, Pydantic

Any lessons learned would be hugely appreciated!


r/FastAPI • • Nov 25 '25

feedback request [UPDATE] AuthTuna: the simplest way to add authentication

23 Upvotes

Been a while now

The auth library now has more features

- out of the box api keys
- public sharable keys
- secret keys to which you can give specific scopes only
- master key allows all actions the user could do
you can feel out the system at https://auth.shashstorm.in/ even test out the api keys
- Theme system to change theme without making a copy of all files

Planned
- Im planning to add event hooks (if it takes too long then i may drop it for v1.0.0 release, will come later but ye)

biggest update is better docs

you can check out the library https://github.com/shashstormer/AuthTuna

and docs at https://authtuna.shashstorm.in/

repos you could check out which use authtuna

https://github.com/shashstormer/stormauth

idk why i made a todo app with authentication

https://github.com/shashstormer/Authtuna-todo

With this library integrating and prototyping anything which requires auth becomes easier

(like i was making smth and when i used my library i realized how much time i saved and how ez it was so just gon keep mentioning this forever)

Now this time im looking for feedback

I'm doing a final polish before dropping the v1.0.0 release around January.

Id love for you guys to test it out. If you find any bugs or feel like a specific feature is missing, let me know
I'll work on whatever is feasible. The goal is to get everything right now so I don't have to change the core structure later.

EDIT:

To test out api scopes (bug in ui just select test key once and then select secret key back again)

https://timeline.shashstorm.in/

you can create a timeline there then you can try doing get with different api keys and scopes etc etc

available role:scope will be shown when creating your token


r/FastAPI • • Nov 22 '25

feedback request Give me feedback on my Fast API Project! 🙏

23 Upvotes

Hello everyone,

First time posting in this sub and looking for some feedback on a FastAPI project I've been working on.

I've been working on creating a REST API for instant quotes for 3D Printing for a few months now. Core idea, is that a user can upload an .STL file and within a few seconds get details on how much the part will cost to print, how much material it uses, etc.

I've created a few FAST API projects in the past but nothing of this scale, or that is accessible to the public. For those of you that are more experienced, please feel free to give pointers or if needed roasts!

Anyways, here's the link to my Swagger docs:
https://api.cloudslicer3d.com/docs

General Docs:
https://docs.cloudslicer3d.com/introduction/overview

Website:
https://www.cloudslicer3d.com/

Note: If the Swagger Docs page takes a while to load, my cloud servers spin down after a few minutes of inactivity, so they'll take a few seconds to spin up. This is a temporary cost saving measure

Update: Source code -> https://github.com/Cloud-Slicer/cloud-slicer-api-public


r/FastAPI • • Oct 31 '25

Question __tablename__ error

Post image
23 Upvotes

Type "Literal['books']" is not assignable to declared type "declared_attr[Unknown]"
  "Literal['books']" is not assignable to "declared_attr[Unknown]" Pylance

What does it mean? And why is the error? This is how SQLAlchemy docs do things


r/FastAPI • • May 14 '25

Question Task queue and async functions

23 Upvotes

I recently ran into an interesting issue that I only managed to work around but not solve.

I have a fastapi app with async postgres and celery as my task queue. Due to how celery works, it struggles with async tasks defined in celery (ok if i/o doesn't need to join back to main thread). The problem is that a lot of my fastapi code is async. When I run DB operations, my issue is that I get corountine errors inside a task. To solve the issue I define a separate DB sync DB driver and isolated tasks as much as possible, however I wonder how others are working within async I/O dependent tasks between celery and fastapi? How do you make methods shared and reusable across fastapi and celery?

(Looking for a discussion around best practice rather than debugging my code)


r/FastAPI • • Apr 23 '25

Question Please suggest me a lightweight front-end with URL-router for my FastAPI application

23 Upvotes

I have been a python developer for more than 10 years, recently a front-end developer who I used to work with has left the company. Now it is on my shoulder to build a front-end which has URL-ROUTER and can make calls to my FastAPI application. Now my knowledge on front-end more particularly on javascript/typescript is zero. So I need something light-weight framework which would be easy for me to understand as a python developer. So do you have any suggestions?, what all do you guys use with FastAPI?


r/FastAPI • • Jan 21 '25

Hosting and deployment FastAPI in Production: Here's How It Works!

Thumbnail
blueshoe.io
23 Upvotes

r/FastAPI • • Oct 25 '24

Question CPU-Bound Tasks Endpoints in FastAPI

23 Upvotes

Hello everyone,

I've been exploring FastAPI and have become curious about blocking operations. I'd like to get feedback on my understanding and learn more about handling these situations.

If I have an endpoint that processes a large image, it will block my FastAPI server, meaning no other requests will be able to reach it. I can't effectively use async-await because the operation is tightly coupled to the CPU - we can't simply wait for it, and thus it will block the server's event loop.

We can offload this operation to another thread to keep our event loop running. However, what happens if I get two simultaneous requests for this CPU-bound endpoint? As far as I understand, the Global Interpreter Lock (GIL) allows only one thread to work at a time on the Python interpreter.

In this situation, will my server still be available for other requests while these two threads run to completion? Or will my server be blocked? I tested this on an actual FastAPI server and noticed that I could still reach the server. Why is this possible?

Additionally, I know that instead of threads we can use processes. Should we prefer processes over threads in this scenario?

All of this is purely for learning purposes, and I'm really excited about this topic. I would greatly appreciate feedback from experts.


r/FastAPI • • Sep 29 '24

Question Is FastAPI gonna benefit from no GIL python3.13?

23 Upvotes

Performance boost? More concurrency? What is your idea?