r/FastAPI • • Sep 04 '25

feedback request I built a library to handle complex SQLAlchemy queries with a clean architecture, inspired by shadcn/ui.

16 Upvotes

Hey everyone,

A while back, I shared the first version of a library I was working on. After a lot of great feedback and more development, I'm back with a much more refined version of fastapi-query-builder.

My goal was to solve a problem I'm sure many of you have faced: your FastAPI routes get cluttered with repetitive logic for filtering, sorting, pagination, and searching SQLAlchemy models, especially across relationships.

To fix this, I designed a library that not only provides powerful query features but also encourages a clean, reusable architecture. The most unique part is its installation, inspired by shadcn/ui. You run query-builder init, and it copies the source code directly into your project. You own the code, so you can customize and extend it freely.

GitHub Repo: https://github.com/Pedroffda/fastapi-query-builder

The Core Idea: A Clean Architecture for Your Endpoints

The library is built around a three-layer pattern (UseCase, Service, Mapper) that integrates perfectly with FastAPI's dependency injection.

  1. BaseService: This is your data layer. It uses the core QueryBuilder to talk to the database. It only knows about SQLAlchemy models.

  2. BaseMapper: Your presentation layer. It's a master at converting SQLAlchemy models to Pydantic schemas, handling nested relationships and dynamic field selection (select_fields) without breaking a sweat.

  3. BaseUseCase: Your business logic layer. It coordinates the service and mapper. This is what your endpoint depends on, keeping your route logic minimal and clean.

See it in Action: From Complex Logic to a Single Dependency

Here’s a quick example of setting up a Post model that has a relationship to a User.

First, the one-time setup:

# --- In your project, after running 'query-builder init' ---
# Import from your new local 'query_builder/' directory
from query_builder import BaseService, BaseMapper, BaseUseCase, get_dynamic_relations_map
from your_models import User, Post
from your_schemas import UserView, PostView

# 1. Define Mappers to convert DB models to Pydantic schemas
user_mapper = BaseMapper(model_class=User, view_class=UserView, ...)
post_mapper = BaseMapper(
    model_class=Post, view_class=PostView,
    relationship_map={'user': {'mapper': user_mapper.map_to_view, ...}}
)

# 2. Define the Service to handle all DB logic
post_service = BaseService(
    model_class=Post,
    relationship_map=get_dynamic_relations_map(Post),
    searchable_fields=["title", "user.name"] # Search across relationships!
)

# 3. Define the UseCase to orchestrate everything
post_use_case = BaseUseCase(
    service=post_service,
    map_to_view=post_mapper.map_to_view,
    map_list_to_view=post_mapper.map_list_to_view
)

Now, look how clean your FastAPI endpoint becomes:

from query_builder import QueryBuilder

query_builder = QueryBuilder()

.get("/posts", response_model=...)
async def get_posts(
    db: Session = Depends(get_db),
    query_params: QueryParams = Depends(), # Captures all filter[...][...] params
    # Your standard pagination and sorting params...
    skip: int = Query(0),
    limit: int = Query(100),
    search: Optional[str] = Query(None),
    sort_by: Optional[str] = Query(None),
    select_fields: Optional[str] = Query(None, description="Ex: id,title,user.id,user.name")
):
    filter_params = query_builder.parse_filters(query_params)
    
    # Just call the use case. That's it.
    return await post_use_case.get_all(
        db=db,
        filter_params=filter_params,
        skip=skip, limit=limit, search=search, sort_by=sort_by,
        select_fields=select_fields
    )

This single, clean endpoint now supports incredibly powerful queries out-of-the-box:

  • Filter on a nested relationship: .../posts?filter[user.name][ilike]=%pedro%

  • Sort by a related field: .../posts?sort_by=user.name

  • Dynamically select fields to prevent over-fetching and create custom views: .../posts?select_fields=id,title,user.id,user.name

Key Features for FastAPI Developers:

  • Clean, Three-Layer Architecture: A production-ready pattern for structuring your business logic.

  • shadcn/ui-style init Command: No more black-box dependencies. You get the source and full control.

  • Powerful Filtering & Sorting: Supports 13+ operators (ilike, in, gte, etc.) on nested models.

  • Dynamic Field Selection (select_fields): Easily build GraphQL-like flexibility into your REST APIs.

  • Built-in Soft Delete & Multi-Tenancy Support: Common real-world requirements are handled for you.

Looking for Your Feedback!

As FastAPI developers, what are your thoughts?

  • Is this architectural pattern something you'd find useful for your projects?

  • What do you think of the init command and owning the code vs. a traditional package?

  • What's the most critical feature I might have missed?

The library is on TestPyPI, and I'm looking to do a full release after incorporating feedback from the community that uses FastAPI every day.

TestPyPI Link: https://test.pypi.org/project/fastapi-query-builder/

Thanks for taking a look


r/FastAPI • • Jun 26 '25

Hosting and deployment Gunicon + Amazon ELB - Solving sporadic 502

16 Upvotes

TLDR: If you are using gunicorn + Amazon ELB, just make sure to set --keep-alive to be higher than 60 seconds. Otherwise your clients may get random 502

Simple issue but we solved it recently: https://dpdzero.com/blogs/the-one-502-in-20000/

The deployment docs used to recommend gunicorn back in the day and we have not yet switched away from it - thought it might be useful to share


r/FastAPI • • May 22 '25

Question Multiprocessing in async function?

16 Upvotes

My goal is to build a webservice for a calculation. while each individual row can be calculated fairly quickly, the use-case is tens of thousands or more rows per call to be calculated. So it must happen in an async function.

the actual calculation happens externally via cli calling a 3rd party tool. So the idea is to split the work over multiple subproccess calls to split the calculation over multiple cpu cores.

My question is how the async function doing this processing must look like. How can I submit multiple subprocesses in a correct async fasion (not blocking main loop)?


r/FastAPI • • Mar 03 '25

Question FastAPI threading, SqlAlchemy and parallel requests

16 Upvotes

So, is FastAPI multithreaded? Using uvicorn --reload, so only 1 worker, it doesn't seem to be.

I have a POST which needs to call a 3rd party API to register a webhook. During that call, it wants to call back to my API to validate the endpoint. Using uvicorn --reload, that times out. When it fails, the validation request gets processed, so I can tell it's in the kernel queue waiting to hit my app but the app is blocking.

If I log the thread number with %(thread), I can see it changes thread and in another FastAPI app it appears to run multiple GET requests, but I'm not sure. Am I going crazy?

Also, using SqlAlchemy, with pooling. If it doesn't multithread is there any point using a pool bigger than say 1 or 2 for performance?

Whats others experience with parallel requests?

Note, I'm not using async/await yet, as that will be a lot of work with Python... Cheers


r/FastAPI • • Feb 23 '25

Tutorial Alternative to FastAPI for serving AI workflows? No infra, just API?

16 Upvotes

I’ve been using FastAPI to serve AI models and workflows, but I’ve been wondering....is there a way to skip the whole API server setup entirely?

Like, what if I just define my AI function, and it instantly behaves like an API without writing a FastAPI app, handling requests, or deploying anything?

I developed an approach where you can run an AI pipeline inside a Jupyter Notebook, and instead of setting up FastAPI, it auto-generates an OpenAI-style API. No need to deal with CORS, async handling, or managing infra....just write your function, and it’s callable remotely.

Has anyone tried something similar? Curious if anyone has seen a different way to serve AI workflows without manually building an API layer.

https://github.com/epuerta9/whisk

Tutorial:
https://www.youtube.com/watch?v=lNa-w114Ujo


r/FastAPI • • Feb 04 '25

Question Adding records to multiple tables at the same time

16 Upvotes

Example Model:

class A(Base):
__tablename__= "a"
id = Column(BigInteger, primary_key=True, autoincrement=True)
name = Column(String(50), nullable=False)

b = relationship("B", back_populates="a")

class B(Base):
__tablename__= "b"
id = Column(BigInteger, primary_key=True, autoincrement=True)
name = Column(String(50), nullable=False)
a_id = Column(Integer, ForeignKey("a.id"))
a = relationship("A", back_populates="b")

records = []
records.append(
B(
name = "foo",
a = A(
name = "bar"
)))

db.bulk_save_objects(records)
db.commit()

I am trying to save both records in Table A and B with relationships without having to do an .add, .flush, then .refresh to grab an id. I tried the above code and only B is recorded.


r/FastAPI • • Jan 09 '25

Tutorial Courses on Udemy for someone who isn't a beginner to APIs?

16 Upvotes

I know how to make an API in dotnet, and a good one at that. I'm not a total novice. I just wish to learn fast-api specifically. Thus i don't wanna be taken into "what is a status code" and "what is a route" and whatnot. Just get the hang of fast-api specifically


r/FastAPI • • Jan 08 '25

Question What's the benefit of sqlmodel in fastapi?

16 Upvotes

I think using sqlalchamy is enough so why using sqlmodel especially when it adds another extra layer; what's the benefti?


r/FastAPI • • Dec 16 '24

Question Go-to way to import data in development environment

16 Upvotes

Hello FastAPI community,

I am implementing an app using FastAPI and alembic and I want to have an automated way to import dummy data when running the app locally. I am using the following stack:

  • FastAPI

  • Alembic for migrations

  • Postgres database

  • docker-compose and makefile to spawn and run migrations in my local environment.

Is there something similar to python manage\.py loaddata of Django in fastapi or alembic? What is your go-to way to do something like that?

Thank you in advance for your time


r/FastAPI • • Dec 03 '24

Question Decoupling Router/Service/Repository layers

16 Upvotes

Hi All, I've read a lot about the 3-layer architecture - but the one commonality I've noted with a lot of the blogs out there, they still have tight coupling between the router-service-repo layers because the DB session is often dependency injected in the router layer and passed down via the service into the repo class.

Doesn't this create coupling between the implementation of the backend repo and the higher layers?What if one repo uses one DB type and another uses a second - the router layer shouldn't have to deal with that.

Ideally, I'd want the session layer to be a static class and the repo layer handles it's own access to it's relevant backend (database, web service etc.) The only downside to this is when it comes to testing - you need to mock/monkeypatch the database used by the repo if you're testing at the service or router layers - something I'm yet to make work nicely with all async methods and pytest+pytest_asyncio.

Does anyone have any comments on how they have approached this before or any advice on the best way for me to do so?


r/FastAPI • • Oct 10 '24

Question What is the best way to structure Exception handlers in FastAPI?

16 Upvotes

Hi, I'm new to FastAPI and have been working on a project where I have many custom exceptions (around 15 or so at the moment) like DatabaseError, IdNotFound, ValueError etc., that can be raised in each controller. I found myself repeating lots of code for logging & returning a message to the client e.g. for database errors that could occur in all of my controllers/utilities, so I wanted to centralize the logic.

I have been using app.exception_handler(X) in main to handle each of these exceptions my application may raise:

@app.exception_handler(DatabaseError)
async def database_error_handler(request: Request, e: DatabaseError):
   logger.exception("Database error during %s %s", request.method, request.url)
   return JSONResponse(status_code=503, content={"error_message": "Database error"})

My main has now become quite cluttered with these handlers. Is it appropriate to utilize middleware in this way to handle the various exceptions my application can raise instead of defining each handler function separately?

class ExceptionHandlerMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        try:
            return await call_next(request)
        except DatabaseError as e:
           logger.exception("Database error during %s %s", request.method, request.url)
           return JSONResponse(status_code=503, content={"error_message": "Database error"})
        except Exception as e:
            return JSONResponse(status_code=500, content={"error_message": "Internal error"})
        ... etc

app.add_middleware(ExceptionHandlerMiddleware)

What's the best/cleanest way to scale my application in a way that keeps my code clean as I add more custom exceptions? Thank you in advance for any guidance here.


r/FastAPI • • Jul 17 '24

Tutorial Login and issuing API access tokens with Auth0 and FastAPI

16 Upvotes

Hello everyone! It's been a while and just put together a new tutorial on how to implement login and how to issue API access tokens using Auth0 and FastAPI. It also explains to how issue refresh and ID tokens.

To clarify the terminology here:

  • Access tokens are the tokens we use to authorize access to our API. They don't (or shouldn't) contain personal information, just a sub property that identifies the user, and claims about their rights to access the API.

  • Refresh tokens are tokens we use to obtain a new access token when the current access token has expired.

  • ID tokens are tokens that contain identifiable information about the user, like their email, name, address, date of birth, and so on. These tokens don't contain claims about the right of the user to access our APIs, hence we don't send them back to the backend. We use ID tokens only to populate user info in the UI.

The tutorial explains how to issue tokens using two of the most common OAuth flow:

  • The client credentials flow, used for machine-to-machine communication, like for example microservices.

  • The authorization code flow, used when we manage the process of issuing tokens from the backend.

The idea is the authorization code flow is designed for traditional web applications like those we'd create with Django or Ruby on Rails. For APIs, the PKCE flow is usually recommended, and it's all handled from the UI. However, nothing prevents us from using the auth code flow in APIs too. It allows us to remove this complexity from the fronted, and as you'll see in the video, it's very easy to implement.

Link to the tutorial: https://youtu.be/ato2S5b27o8

Code for the tutorial: https://github.com/abunuwas/short-tutorials/tree/main/fastapi-auth0

Note: there's a previous tutorial to this one that explains how to set up an Auth0 account if you need help with that.

Hope you enjoy the video and find it useful!


r/FastAPI • • Jun 30 '24

Question Dependency declaration is ugly

16 Upvotes

Is it just me who dislikes the way dependencies are declared in FastAPI? Why does dependency injection have to be tied to type definitions?

It feels ironic that the primary reason for moving external dependencies into function arguments is to decouple them, yet declaring dependencies in the function's type signature ends up coupling them again in another way.

Does anyone else find this approach awkward?


r/FastAPI • • Jun 23 '24

Hosting and deployment Confused about uvicorn processes/threads

16 Upvotes

I'm trying to understand synchronous APIs and workers and how they affect scalability. I'm confused. I have the following python code:

from fastapi import FastAPI
import time
import asyncio
app = FastAPI()

app.get("/sync")
def sync_endpoint():
  time.sleep(5);
  return {"message": "Synchronous endpoint finished"}

u/app.get("/async")
async def async_endpoint():
    await asyncio.sleep(5)
    return {"message": "Asynchronous endpoint finished"}

I then run the code like:
uvicorn main:app --host 127.0.0.1 --port 8050 --workers 1

I have the following CLI which launches 1000 requests in parallel to the async endpoint.
seq 1 1000 | xargs -n1 -P1000 -I{} sh -c 'time curl -s -o /dev/null http://127.0.0.1:8050/async; echo "Request {} finished"'

When I run this, I got all 1000 requests back after 5 seconds. Great. That's what I expected.

When I run this:
seq 1 1000 | xargs -n1 -P1000 -I{} sh -c 'time curl -s -o /dev/null http://127.0.0.1:8050/sync; echo "Request {} finished"'

I expected that the first request would return in 5 seconds, the second in 10 seconds, etc.. Instead, the first 40 requests return in 5 seconds, the next 40 in 10 seconds, etc... I don't understand this.


r/FastAPI • • May 23 '24

Question Fine grained access control?

16 Upvotes

I am designing a huge-ass API for a client. And one of the things we are scratching our heads over is how to give people different access to different nodes.

Eg. (Examples, not actual)

/api/v1/employess # only internal people
/api/v1/projects # customers GET, internal POST
/api/v1/projects/{projectid}/timeline #customers GET
/api/v1/projects/{projectid}/updates # customers GET/POST
etc...

We have also the usual login/jwt authentication stuff

I was thinking of grouping users and writing a custom decorator that matches the path to the access.

Am I on the right track or are you all going "WTF am I reading?"

Or is this something OAuth scopes should handle? (I have never used that)

Edit: It seems that OAuth scopes is designed exactly for this kind of situation. I guess I have some learning to do.

Edit2: Thanks, I definitely have something to go on now.


r/FastAPI • • Dec 31 '23

Other Leapcell: Vercel Alternative for FastAPI

16 Upvotes

We are excited to announce that Leapcell has officially launched its Beta public testing.

Leapcell: https://leapcell.io/

Leapcell is a Data & Service Hosting Community. It allows you to host Python applications as conveniently as Vercel does. Additionally, it provides a high-performance database with an Airtable-like interface, making data management more convenient. The entire platform is Fully Managed and Serverless. We aim for users to focus on specific business implementations without spending too much time on infrastructure and DevOps.

Here is a FastAPI example:

For documentation on deploying FastAPI projects, you can refer to the following link:

Here is the trigger link for the deployed FastAPI project:

The data is stored here, and if you are familiar with spreadsheets, you will find this interface very user-friendly(python client: https://github.com/leapcell/leapcell-py):

The deployment process for Flask, FastAPI, and other projects is also straightforward.

Leapcell is currently in Beta testing, and we welcome any feedback or questions you may have.


r/FastAPI • • Sep 25 '23

feedback request FastStream: the easiest way to add Kafka and RabbitMQ support to FastAPI services

16 Upvotes

FastStream (https://github.com/airtai/faststream) is a new Python framework, born from Propan and FastKafka teams' collaboration (both are deprecated now). It extremely simplifies event-driven system development, handling all the parsing, networking, and documentation generation automatically. Now FastStream supports RabbitMQ and Kafka, but supported brokers are constantly growing (wait for NATS and Redis a bit). FastStream itself is a really great tool to build event-driven services. Also, it has a native FastAPI integration. Just create a StreamRouter (very close to APIRouter) and register event handlers the same with the regular HTTP-endpoints way:

from fastapi import FastAPI
from faststream.kafka.fastapi import KafkaRouter

router = KafkaRouter()

@router.subscriber("in-topic")
@router.publisher("out-topic")
async def handle_kafka_message(username: str, user_id: int):
    return f"User ({user_id}: {username}) event processed!"

app = FastAPI(lifespan=router.lifespan_context)
app.include_router(router)

This way you can use any FastAPI features (like Depends, BackgroundTasks, etc.).

FastStream supports in-memory testing, AsyncAPI schema generation and more... If you are interested, please support our project by giving a GH start and joining our discord server.

Last but not least, we are open to new contributors as well, let's make OSS better together!


r/FastAPI • • Mar 07 '23

feedback request FastAPI Boilerplate using MongoDB, Motor, Docker

16 Upvotes

Wanted to create a boilerplate to use MongoDB with FastAPI

Uses Python 3.11.2 and the latest packages for everything else

https://github.com/alexk1919/fastapi-motor-mongo-template


r/FastAPI • • Nov 04 '22

Tutorial Using FastAPI Inside Docker Containers

Thumbnail
blog.logrocket.com
16 Upvotes

r/FastAPI • • Mar 21 '22

Tutorial Deploying a FastAPI Application to Elastic Beanstalk

Thumbnail
testdriven.io
16 Upvotes

r/FastAPI • • Mar 03 '22

Tutorial Developing my first financial app using React Native, Redux, Figma and FastAPI

Thumbnail
medium.com
16 Upvotes

r/FastAPI • • Oct 18 '21

Other Upcoming Webinar: “Smarter FastAPI Through Tooling” with Sebastián Ramírez

16 Upvotes

r/FastAPI • • Oct 16 '21

Question tiangolo/SQLModel DoA?

16 Upvotes

There was a lot of hype and excitement around the release of SQLModel, a Pydantic + SQLAlchemy hybrid Model library with native integration for FastAPI. I pulled it out just now and there hasn't been any update beyond the initial anouncment on August 25th.

Is this project dead on arrival or is there something baking behind the scenes?


r/FastAPI • • Oct 07 '21

feedback request I wrote an alternative for the official FastAPI full stack project generator (more info in comment)

Thumbnail
github.com
16 Upvotes