r/FastAPI • • Dec 07 '25

Question Depends or Middleware

20 Upvotes

Hi, I'm very new to FastAPI. My previous background is more in Express.js and Spring Boot. I just learn what ASGI is and know how to write pure ASGI middlewares for Starlette.

For FastAPI, should I write everything in Depend instead of ASGI middlewres? For example, I've written an ASGI middleware for adding x-request-id in the structlog context. Should I change it to a function and use Depends? Thanks for reading!


r/FastAPI • • Sep 18 '25

Tutorial Open source FastAPI starter project for students learning AI web apps

20 Upvotes

I’ve been working on a scaffolded FastAPI project designed to help students and new developers practice building AI-focused web applications.

One of the main ideas is that you maybe learned or are learning Python in school and don’t want to use JavaScript. With this project you don’t have to know JavaScript front-end that deeply.

The repo sets up a modern stack (FastAPI, SQLite, HTMX, Tailwind, etc.) and includes examples of how to extend it into a working AI-first app. The idea is to give beginners something more structured than tutorials but less intimidating than building from scratch.

I’d like to hear from the community:

-- What features would you want to see in a starter like this? -- Are there pitfalls for students using FastAPI in this way? -- Any recommendations for making it more educational?

If you want to look at the code, it’s here: GitHub repo


r/FastAPI • • Aug 21 '25

Hosting and deployment What is the best/verified way which you honestly can recommend to deploy simple python app?

20 Upvotes

I thought about some kind of cloud like AWS, but I don't have any experience with it, so it will probably cost me a fortune by this way. It is micro project. I had an idea also about making my own server, but I am not so sure if it is worth my effort.

Which hosting has easy configuration and rather doesn't have many problems with python packages?


r/FastAPI • • Aug 19 '25

Question FastAPI + Cloud Deployments: What if scaling was just a decorator?

20 Upvotes

I've been working with FastAPI for a while and love the developer experience, but I keep running into the same deployment challenges. I'm considering building a tool to solve this and wanted to get your thoughts.

The Problem I'm Trying to Solve:

Right now, when we deploy FastAPI apps, we typically deploy the entire application as one unit. But what if your /health-check endpoint gets 1000 requests/minute while your /heavy-ml-prediction endpoint gets 10 requests/hour? You end up over-provisioning resources or dealing with performance bottlenecks.

My Idea:

A tool that automatically deploys each FastAPI endpoint as its own scalable compute unit with:

  1. Per-endpoint scaling configs via decorators

  2. Automatic Infrastructure-as-Code generation (Terraform/CloudFormation)

  3. Built-in CI/CD pipelines for seamless deployment

  4. Shared dependency management with messaging for state sync

  5. Support for serverless AND containers (Lambda, Cloud Run, ECS, etc.)

@app.get("/light-endpoint") @scale_config(cpu="100m", memory="128Mi", max_replicas=5) async def quick_lookup(): pass

@app.post("/heavy-ml") @scale_config(cpu="2000m", memory="4Gi", gpu=True, max_replicas=2) async def ml_prediction(): pass

What I'm thinking:

  1. Keep FastAPI's amazing DX while getting enterprise-grade deployment

  2. Each endpoint gets optimal compute resources

  3. Automatic handling of shared dependencies (DB connections, caches, etc.)

  4. One command deployment to AWS/GCP/Azure

Questions for you:

  1. Does this solve a real pain point you've experienced?

  2. What deployment challenges do you face with FastAPI currently?

  3. Would you prefer this as a CLI tool, web platform, or IDE extension?

  4. Any concerns about splitting endpoints into separate deployments?

  5. What features would make this a must-have vs nice-to-have?

  6. I'm still in the early research phase, so honest feedback (even if it's "this is a terrible idea") would be super valuable!


r/FastAPI • • Aug 11 '25

feedback request I generated an architecture diagram for FastAPI

20 Upvotes

Hey all, I recently switched from using Django to FastAPI. As I am new to the framework I used my own open source tool to generate a diagram represnetation of how it works. Hope this is useful to people.


r/FastAPI • • Jul 31 '25

Question Building a Zapier-lite system with FastAPI & Celery — how to make it feel modern like Trigger.dev?

20 Upvotes

Hey folks,
I’m building a B2B SaaS using FastAPI and Celery (with Redis as broker), and I’d love to implement some internal automation/workflow logic — basically like a lightweight Zapier within my app.

Think: scheduled background tasks, chaining steps across APIs (e.g., Notion, Slack, Resend), delayed actions, retries, etc.

I really love how Trigger.dev does this — clean workflows, Git-based config, good DX, managed scheduling — but it's built for TypeScript/Node. I’d prefer to stay in Python and not spin up a separate Node service.

Right now, I’m using:

  • FastAPI

  • Celery + Redis

  • Looking into APScheduler for better cron-like scheduling

  • Flower for monitoring (though the UI feels very dated)

My question:

How do people build modern, developer-friendly automation systems in Python?
What tools/approaches do you use to make a Celery-based setup feel more like Trigger.dev? Especially:

  • Workflow observability / tracing

  • Retry logic + chaining tasks

  • Admin-facing status dashboards

  • Declarative workflow definitions?

Open to any tools, design patterns, or projects to check out. Thanks!


r/FastAPI • • Jul 16 '25

Question Modern example repos showing FastApi with SqlModel and async SqlAlchemy?

20 Upvotes

I'm trying to stand up a backend using the latest best practices for async endpoints and database calls. I'm using latest or recent SqlModel (0.0.24), pytest (8.4.1), and pytest-asyncio (0.26.2).

My endpoints are working just fine but I am banging my head against the wall trying to get pytest to work. I keep running into all manner of coroutine bugs, got Future <Future pending> attached to a different loop. I've gotten other repos (like this one ) working, but when i try to translate it to my codebase, it fails.

Are there any repos (ideally as recent as possible) out there demonstrating an app using async sqlalchemy and pytest?


r/FastAPI • • Jun 04 '25

Question Types sync for frontend

20 Upvotes

A problem we are facing in our company's tech stack is to keep fastapi request response schemas in sync with frontend. Our frontend is NextJS, but the problem is more of a general nature.

  1. We want a simple solution, protobuf while getting the job done is a beast of its own to manage.

  2. OpenAPI spec produced by the swagger part of fastAPI can be used, but an ideal solution should skip hopping to the spec.

What is the most crisp & elegant solution for a growing codebase with 100+ endpoints, while not making a team of 5 engs go mad?


r/FastAPI • • Jan 24 '25

Question Is there a Python equivalent to Trigger.dev for simple background job scheduling?

20 Upvotes

I'm using [Trigger.dev](http://Trigger.dev) for background jobs in TypeScript and appreciate how straightforward it is to set up and run background tasks. Looking for something with similar ease of use but for Python projects. Ideally want something that's beginner-friendly and doesn't require complex infrastructure setup.


r/FastAPI • • Jan 13 '25

Question Best projects for job interview?

20 Upvotes

Hey guys, I'm a beginner here. I have applied to one of the startup companies and they are expecting me to know fastapi in depth and projects related to fastapi. I have been thinking of using ai in the projects. Can anyone suggest the best projects for it?


r/FastAPI • • Jan 13 '25

Question Best practice for mocking stripe calls in a FASTAPI integration test?

20 Upvotes

I created a FASTAPI based shopping app. Most of the code is generated. I spent 2 hours organizing it into separate files and modules and getting tests to pass.

However 3 tests are failing because I don't have a stripe payment webhook setup. What is the common practice for mocking it in an integration test?

Is there another way to create the payment intent that doesn't fail and have it magically transition status for test purposes?


r/FastAPI • • Dec 31 '24

Question Real example of many-to-many with additional fields

20 Upvotes

Hello everyone,

Over the past few months, I’ve been working on an application based on FastAPI. The first and most frustrating challenge I faced was creating a many-to-many relationship between models with an additional field. I couldn’t figure out how to handle it properly, so I ended up writing a messy piece of code that included an association table and a custom validator for serialization...

Is there a clear and well-structured example of how to implement a many-to-many relationship with additional fields? Something similar to how it’s handled in the Django framework would be ideal.


r/FastAPI • • Nov 21 '24

Question Fed up with dependencies everywhere

20 Upvotes

My routers looks like this:

@router.post("/get_user")
async def user(request: DoTheWorkRequest,
                       mail: Mail = Depends(get_mail_service),
                       redis: Redis = Depends(get_redis_service),
                       db: Session = Depends(get_session_service)):
   user = await get_user(request.id, db, redis)


async def get_user(id, mail, db, redis):
   # pseudocode
   if (redis.has(id)) return redis.get(id)
   send_mail(mail)
   return db.get(User, id)

async def send_mail(mail_service)
   mail_service.send()

I want it to be like this:

@router.post("/get_user")
async def user(request: DoTheWorkRequest):
   user = await get_user(request.id)

## REDIS, MAIL, and DB can be accessed globally from anywhere
async def get_user(id):
   # pseudocode
   if (REDIS.has(id)) return REDIS.get(id)
   send_mail()
   return DB.get(User, id)

async def send_mail()
   MAIL.send()

To send emails, use Redis for caching, or make database requests, each route currently requires passing specific arguments, which is cumbersome. How can I eliminate these arguments in every function and globally access the mail, redis, and db objects throughout the app while still leveraging FastAPI’s async?


r/FastAPI • • Oct 04 '24

Tutorial FastAPI microservice tutorial?

20 Upvotes

I want to learn microservice in FastAPI, unfortunately there is not much tutorial I can see available. If there any tutorial/article on how to implement microservice with FastAPI please share :)


r/FastAPI • • Aug 06 '24

Question for a complete fast API beginer what should I do?

20 Upvotes

So I want to learn fast API by building something, Can you please suggest me some projects and resources so I can start off building and learning fast API.


r/FastAPI • • Jul 26 '24

Tutorial Validate JWTs from Auth0 in FastAPI [tutorial]

20 Upvotes

Hello everyone! Over the past weeks I've been putting together a tutorial on how to implement API authentication and authorization in FastAPI with Auth0. I just finished the last video that explains how to validate the JWTs issued from Auth0 and wanted to share it with you.

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

The code for the tutorial is available on GitHub: https://github.com/abunuwas/short-tutorials/tree/main/fastapi-auth0-authz

The whole process of issuing and validating JWTs from Auth0 is based on standards, and that's the angle in the video. I explain how to inspect a JWT, how to pull the identity provider's OIDC configuration from its well-known endpoint, where to find and how to use the JWKS (JWT signing keys, the public ones in this case), etc.

I've seen and still see many organizations getting this part of the API authorization process wrong, so hopefully this helps some!

There are two videos preceding this tutorial that explain how to configure the Auth0 tenant and how to create the login and authorization flows. I've put together a playlist (https://www.youtube.com/playlist?list=PLZGraXskpvb8JX17hMZoYQRmMr0fo97G6). I'll add a few more videos to this playlist in the future, but I'll move on to other topics in the coming weeks.

Hope you enjoy the tutorial and find it useful!


r/FastAPI • • Jun 16 '24

Question Default thread limit of 40 (by Starlette)

20 Upvotes

Hi, I tried to understand how FastAPI handles synchronous endpoints and understood that they are executed in a thread pool that is awaited. https://github.com/encode/starlette/issues/1724 says that this thread pool by default has a size of 40. Can someone explain the effect of this limit? I did not find information on if e.g. uvicorn running a single FastAPI process is then limited to max. 40 (minus the ones used internally by FastAPI) concurrent requests? Any idea or link to further read on is welcome.


r/FastAPI • • Jun 06 '24

Tutorial Create custom middleware with FastAPI [tutorial]

20 Upvotes

Hi all I created a tutorial explaining how to create custom middleware with FastAPI. Showcases the two approaches, with decorator-based and class-based middleware. It has very simple examples and is hopefully beginner-friendly, so hoping it helps some of you getting started with the framework!

Link to the tutorial: https://youtu.be/P3zdVdb-yn8

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

Feel free to ask any questions if something isn't clear!
is


r/FastAPI • • Apr 19 '24

Question Is FastAPI + HTMX a viable combination or better to use something else?

20 Upvotes

FastAPI has improved a lot!

Now I know the name says its designed for developing API's, but if all I am doing is serving Jinja2 templates and htmx would you say this is a viable combo for building a website with Alpine JS? I was thinking of using Astro js, but considering macros can do the reusable components and Jinja2 has auto escaping for protection from XSS attacks (obviously you have to sanitize no matter the framework), it seems like a simple combo to do what I need and personally had a easier time getting this set up compared to other async frameworks.


r/FastAPI • • Mar 09 '24

Question Not so much performance improvement when using async

20 Upvotes

We changed our FastAPI to async, we were tied to sync due to using an old package.

But we are not really seeing a direct performance improvement in the Request Per Second handles before the response time skyrockets.

Our postgres database info:

  • 4 cpu, 8 gb ram

DB tops at 80% cpu and 80% ram with ~300 connections. We use connection pooling with 40 connections.

Our API is just a simpel CRUD. We test it with Locust with 600 peak users and spawn rate of 4/second.

An api call would be:
get user from db -> get all organisation where user is member with a single join (this all with SQLAlchemy 2.0 Async and Pydantic serialisation)

With async we can still only handle 70 rps with reasonable response times < 600ms, and the APIs are just a few db calls, user info, event info etc.

We tested on Cloud Run with: 2 instances, CPU is only allocated during request processing, 2cpu/1ram.

I thought that FastAPI could handle at least hundreds of these simple CRUD calls on this hardware, or am I wrong, especially with async?

Edit: added api call, add database info


r/FastAPI • • Jan 23 '24

Question anyone try running via granian?

20 Upvotes

saw version 1.0 is out and i wanted to give it a shot vs gunicorn/uvicorn. of course i know virtually nothing about it. anyone try it out and have an opinion about it?


r/FastAPI • • Oct 05 '21

feedback request FastQL - A FullStack Playground ✨

20 Upvotes

FastQL - FastAPI GraphQL Playground✨

project link: https://github.com/obytes/fastql

Generate a FullStack playground using FastAPI and GraphQL and Ariadne🚀.

This Repository is based on this Article Getting started with GraphQL in Python with FastAPI and Ariadne, Read Article to know how to use it.

Features

  • Full Docker integration (Docker-based).

  • GraphQL playground based on Graphene and Ariadne.

  • Docker Compose integration and optimization for local development.

  • Production-ready Python web server using Uvicorn.

  • Secure password hashing by default.

  • JWT token authentication.

  • SQLAlchemy database integration using PostgreSQL.

  • Alembic migrations for database schema.

  • rabbitMQ (asynchronous) message broker.

  • API tests based on Pytest, integrated with Docker, so you can test the full API interaction, independent of the database.

I want your feedback here 😅


r/FastAPI • • Sep 17 '26

feedback request Introducing Chanx-Kit, a mini WebSocket framework for FastAPI (Django Channels and other ASGI apps too)

19 Upvotes

Hi guys, if you have ever built something real with @app.websocket, you probably hit the same wall I did. The decorator is lovely for one connection, and then you need a second connection to hear about the first: a room, a notification from a background task, a presence list. So you write your own connection manager, and it quietly stops working the day you run a second uvicorn worker, because your dict of connections lives in one process.

After years of this in Django Channels (and hurting a lot), I built ChanX to make WebSockets easy, maintainable and scalable, then made it framework-independent so it runs on FastAPI too, using fast-channels as the channel layer (Redis, or in-memory locally). Then a user suggested turning it into a reusable framework, and that stuck with me: the same pieces get rebuilt in every project anyway, presence, streaming, chat, notifications. So I made Chanx-Kit, a registry of best-practice WebSocket components you add to your project and then own. The inspiration is shadcn, copy it in and modify it freely, rather than a package buried in your virtualenv that you have to fight to override.

A kit is a topic you list on a consumer, so several share one connection, and the consumer mounts as a normal ASGI route:

from chanx.fast_channels.websocket import AsyncJsonWebsocketConsumer

class AppConsumer(AsyncJsonWebsocketConsumer[AppEvents]):
    channel_layer_alias = "default"
    topics = [UserNotificationTopic, RoomChatTopic, PresenceTopic]

app.router.add_websocket_route("/ws", AppConsumer.as_asgi())

Then code anywhere, a background task or a worker included, can reach connected clients with no connection manager to keep:

await UserNotificationTopic.notify_user(user.id, payload)

Handlers are typed with Pydantic messages instead of a while True if/else chain, and you get generated AsyncAPI docs for your WebSocket API the way FastAPI gives you OpenAPI for your routes.

The kits available now:

  • AG-UI: the AG-UI agent protocol over a WebSocket, bidirectional, and a client reconnecting mid-run is replayed the run instead of seeing half an answer.

  • Notification: fan out notifications to a user's live connections from anywhere in your app.

  • Presence: track who is in a room, document or tenant, and tell everyone when it changes. Pluggable store.

  • Room chat: a chat room with history replayed on connect, plus a live roster from the presence kit.

Plus a Pydantic AI kit, stores and a test harness. Next on my list is realtime audio, Deepgram voice processing and voice-to-voice agent chat, from work I did a few years back.

It is early days, so feedback is what I want most. If you already run WebSockets on FastAPI, tell me your use case and what breaks for you, and we can talk about turning it into a kit for everyone. Contributions welcome too.

One deliberate choice: it is not a PyPI package. The components are meant to be copied and edited, so shipping one big package would work against that. If you think that is the wrong call, I would like to hear why.


r/FastAPI • • Jul 12 '26

feedback request Building a "batteries-included" FastAPI starter (auth, billing, admin, email) — what would you want in it?

19 Upvotes

Working on a FastAPI + Next.js SaaS boilerplate (Python equivalent of the JS "ship fast" starters). Backend is FastAPI + Pydantic v2, Firestore for storage so far.

Before I finalize the feature list, curious what this community actually wants baked in:

  • Auth: what's your default — Supabase, Clerk, roll-your-own JWT?

  • Billing: Stripe is obvious, but subscriptions vs. usage-based matters a lot for setup

  • Background jobs: Celery, arq, or just Cloud Tasks/Cloud Run?

Landing page + waitlist if you want to follow progress: https://fastforge.pionetix.com — but honestly more interested in the discussion here than the sign-ups.