r/FastAPI • • Sep 02 '21

Tutorial Create and deploy a reliable data ingestion service with FastAPI, SQLModel and Dramatiq

Thumbnail
francoisvoron.com
16 Upvotes

r/FastAPI • • Aug 16 '21

Tutorial Developing a Single Page App with FastAPI and Vue.js

Thumbnail
testdriven.io
16 Upvotes

r/FastAPI • • Feb 22 '21

pip package ⚡ FastAPI Websocket RPC and Pub/Sub packages

16 Upvotes

Looking for an easy way to build over-the-web realtime comms, updates, or data distribution?

We've recently published two Python open source packages for ⚡ RPC and Pub/Sub over Websockets (on top of FastAPI)

Stars, PRs, issues, and feedback are super welcome 😇

https://github.com/authorizon/fastapi_websocket_pubsub

https://github.com/authorizon/fastapi_websocket_rpc


r/FastAPI • • Jan 25 '21

Hosting and deployment Django Async vs FastAPI vs WSGI Django: Performance Comparision of ML/DL Inference Servers

Thumbnail
aibharata.medium.com
16 Upvotes

r/FastAPI • • Oct 27 '20

Tutorial Developing an API with FastAPI and GraphQL

Thumbnail
testdriven.io
16 Upvotes

r/FastAPI • • Sep 14 '20

feedback request Decided to share with you micro service built with FastAPI.

16 Upvotes

Hello FastApi,

Long story short, I needed microservice that would manage the files, so I ended up with writing Filemanager-Fastapi (FF) and I am not even complaining. Hope you will be able to use it in concrete needs. Have fun, and of course prs are welcome.

link: https://github.com/JexPY/filemanager-fastapi


r/FastAPI • • Aug 07 '26

Other Open sourcing my typed WebSocket approach for building AI agents with Pydantic AI on FastAPI

15 Upvotes

Hey everyone, after taking a bit of a break I decided to write an in-depth tech blog to help those of you building (or about to build) an AI agent in the Python ecosystem, especially on FastAPI, so you can end up with something structured, scalable and efficient. This comes out of a lot of time working on chatbots, streaming and AI agents. There was no good guide for me when I built those, so after suffering plenty of pain and bugs I decided to write it up and open source part of my work to help you avoid the same. Hope it helps.

Full blog here in case you have time to read properly. Whether you're a team lead or senior who needs to build a scalable AI agent project, or a junior or intern who wants to build one the right way, this should be useful (it cost me a lot of time and money to learn): https://huynguyengl99.github.io/posts/pydantic-ai-typed-websockets-fastapi/

Comes with the repo: https://github.com/huynguyengl99/pydantic-ai-ws-agent

If you want to catch up first, TL;DR:

  1. A contract-based, structured protocol still beats an unstructured, code-first one. Instead of writing a pile of if/else and tests to make sure things are correct (and sometimes they still aren't), you keep one up-to-date contract that both the backend and the frontend build against, so no field is silently missing or outdated. For REST APIs that's OpenAPI. For WebSockets it's AsyncAPI. You can even design the whole protocol before writing any code. Trust me, it saves you a lot of 2am bugs.

  2. Prefer a structured, model-independent agent. There are plenty of options now (LangChain, the OpenAI SDK, the Gemini and Anthropic SDKs), but most of the time what matters is being able to switch model or provider without rewriting anything, structured and validated tool calls (without tool calls it's just a chat, not an agent), and something that fits your existing ecosystem. Tie yourself to one vendor's SDK and you'll feel it the first time you want to compare models or a provider has an outage. Pydantic AI is the one that gives you all of that. If you've used LangChain you'll remember the mess around messages and tool handling, a lot of unnecessary complexity. Pydantic AI keeps it structured, and since it comes from the Pydantic team it speaks Pydantic models natively, which is exactly why it fits FastAPI so well.

  3. Once your agent is structured, your server API should be too. Most people reach for SSE because it's simple, but it's missing a few things: bidirectional messages, a proper API schema (OpenAPI 3.2.0 has some support for streaming now, but tooling is still limited and it doesn't feel as natural as it does for REST), and any official way to offload work to a worker or push a message from outside the request, like a notification from somewhere else in your system. WebSockets don't have that schema problem, because AsyncAPI is a real spec built for exactly this: every message your server can send or receive, described in one document your frontend can generate a client from. It's the same deal OpenAPI gives you for REST, just for event-driven APIs.

  4. Bidirectional matters more than people expect, and human-in-the-loop is why. With Pydantic AI you can mark a destructive tool requires_approval=True. The run then stops before executing, hands you the pending calls, and you send an approval request to the UI. The user approves or denies (they can even edit the arguments), and you resume the run from where it paused. That round trip is awkward over SSE and completely natural over a WebSocket, it's just two more messages on a connection you already have.

  5. That's where ChanX and fast-channels come in. Based on the well-known django-channels package, I built fast-channels to bring the channels architecture to FastAPI. ChanX is the only tool I'm aware of that makes WebSocket handlers structured and easy while auto-generating AsyncAPI docs, so your frontend can generate a client straight from the schema. That's the contract you need to stop things going stale or breaking silently. It also gives you the offload story: the run happens in a background task and broadcasts to a conversation group, so a page refresh mid-run doesn't kill the answer, every tab stays in sync, and moving the work to a Celery or taskiq worker later changes nothing else.

  6. One more thing that surprised me: the whole flow becomes testable without an LLM. Because the protocol is typed and the agent is built from a factory, Pydantic AI's FunctionModel can script exactly what the model does. Streaming, tool execution, approve, deny and reconnect all become deterministic tests. Mine run in about a second with no API key, which is the difference between having tests and pretending to.

That's the core and the summary for a quick catch up. When you have time, reading the blog and looking at the repo will give you more insight into building a structured, scalable, production-ready AI agent.

Related repos:

If ChanX or fast-channels turn out to be useful for you, a star or any contribution to improve them would be appreciated 😄

I'm open to any discussion in the comments, feel free to bring up any problem you're hitting when building an AI agent. I'll try my best to help, since I've been through most of the pain already.


r/FastAPI • • Jun 12 '26

pip package Fastvia: an open-source backend toolkit for FastAPI projects

15 Upvotes

Hi everyone,

I recently built and published Fastvia, an open-source backend toolkit for FastAPI.

When building FastAPI projects, there are many setup pieces that come up again and again: middleware, security headers, structured logging, consistent API errors, pagination, rate limiting, Redis utilities, background jobs, database helpers, authentication helpers, and Alembic migration setup.

Fastvia brings these common parts together as reusable building blocks, so developers can start projects with a cleaner foundation while still keeping the flexibility of FastAPI.

It is especially useful for developers who want a ready foundation for new FastAPI backends without spending time wiring the same setup manually in every project.

PyPI: https://pypi.org/project/fastvia-kit/
GitLab: https://gitlab.com/abdulfatahbabakrkhail/fastvia


r/FastAPI • • Apr 30 '26

Tutorial What “production-ready FastAPI” actually means beyond making the route work

15 Upvotes

A lot of beginner FastAPI projects stop at:

u/app.post("/login")
def login():
    ...

But in real apps, “it works” is not the same as “it’s safe to ship.”

Some things I think every FastAPI route should be checked for:

  • Does the route verify the current user owns the resource?

  • Does it return only safe response fields?

  • Are expired / invalid tokens tested?

  • Are duplicate emails handled properly?

  • Are async DB sessions used correctly?

  • Are errors consistent and not leaking internals?

  • Are tests covering failure cases, not only happy paths?

The biggest jump for me was realizing that backend quality is mostly about edge cases.

Curious what other FastAPI devs here check before shipping a route?


r/FastAPI • • Apr 09 '26

Hosting and deployment FastAPI Cloud vs Modal

15 Upvotes

I’m currently using AWS lambda / APIGateway to host my FastAPI server. There’s a ton of code to make this work and other stuff that I’m the only person in my team understands. Had to switch from Mangin back to using uvicorn to serve because I wanted streamed responses, and to make things start fast we use Snapstart, which is also a whole thing.

I was considering switching over to using Modal, but found out about FastAPI Cloud. Cloud sounds awesome, but I’m pretty sure I can replace my job system with function calls on Modal. I don’t see an equivalent out of the box job system managed by Cloud.

Has anyone tried both? Any reason to use Cloud over Modal? Still too early to tell with Cloud?


r/FastAPI • • Apr 07 '26

Question Is there a way for auto reloading web pages when working with fastapi + jinja2 templates

15 Upvotes

Is there a way to have Auto Reloading of the Browser Page. It would have been nice to have auto reloading feature (of browser on .html file changes) like in vite / nextjs.


r/FastAPI • • Mar 15 '26

Question Built a Production-Ready AI Backend: FastAPI + Neo4j + LangChain in an isolated Docker environment. Need advice on connection pooling!

15 Upvotes

Hey everyone,

I recently built a full stack GraphRAG application to extract complex legal contract relationships into a Knowledge Graph. Since I wanted this to be a production ready SaaS MVP rather than just a local script, I chose FastAPI as the core engine.

The Architecture choices:

  • Used FastAPI's async endpoints to handle heavy LLM inference (Llama-3 via Groq) without blocking the server.

  • Neo4j Python driver integrated for complex graph traversals.

  • Everything is fully isolated using Docker Compose (FastAPI backend, Next.js frontend, Postgres) and deployed on a DigitalOcean VPS.

My Question for the backend veterans: Managing the Neo4j driver lifecycle in FastAPI was a bit tricky. Right now, I initialize the driver on app startup and close it on shutdown. Is this the absolute best practice for a production environment, or should I be doing connection pooling differently to handle concurrent LLM requests?

(If you want to inspect the docker-compose setup and the async routing, the full source code is here: github.com/leventtcaan/graphrag-contract-ai*)*

(Also, Reddit doesn't allow video uploads in text posts, but if you want to see the 50-second UI demo and how fast it traverses the graph, you can check out my launch post on LinkedIn here: https://www.linkedin.com/feed/update/urn:li:activity:7438463942340952064/ | Would love to connect!)


r/FastAPI • • Jan 23 '26

pip package Update: I built TimeTracer (v1.6), record/replay API calls locally + dashboard (Starlette/FastAPI/Django)

15 Upvotes

After working with microservices, I kept running into the same annoying problem: reproducing production issues locally is hard (external APIs, DB state, caches, auth, env differences).

So I built TimeTracer.

What My Project Does Records an API request into a JSON “cassette” (timings + inputs/outputs + dependencies) and lets you replay it locally with dependencies mocked (or hybrid replay).

Target Audience Backend developers (FastAPI, Django, Flask, Starlette) who want to debug production issues locally without setting up complex environments.

Comparison It’s similar to VCR.py but captures the entire incoming request context (not just outgoing calls) and includes a dashboard. It sits between observability tools and testing mocks.

What’s new/cool (v1.6):

  • Starlette Support: Native support for Starlette apps.

  • Cassette Compression: Now supports GZIP/ZSTD compression to keep storage light (great for big responses).

  • New Dashboard: Enhanced UI to visualize deep dependency chains (e.g. API → DB → External API).

  • Tutorial: I wrote a full guide on debugging 404s with this workflow (link in comments).

  • Pytest integration: Zero-config fixtures (ex: timetracer_replay ) to use cassettes in tests.

  • Broad Support: Works with httpx, requests, aiohttp, SQLAlchemy, and Redis.

Security:

  • Automatic redaction for tokens/headers.

  • PII detection (emails/phones) so cassettes are safer to share.

Install: 

pip install timetracer

GitHub: https://github.com/usv240/timetracer

Contributions are welcome! If anyone is interested in helping (features, tests, docs), I’d love the support.

Full tutorial is mentioned in the comments.

Looking for feedback: Does this fit your workflow? What would make you actually use something like this next, better CI integration, more database support, or something else?


r/FastAPI • • Jan 13 '26

pip package Rabbit Manager – Python Utility for RabbitMQ Queues

15 Upvotes

Rabbit Manager – Python Utility for RabbitMQ Queues

Rabbit Manager is a simple, Python-based utility for managing RabbitMQ message queues. It provides an easy-to-use interface for sending, receiving, and processing messages with built-in support for automatic reconnections and error handling. This open-source, MIT-licensed project is ideal for Python developers and DevOps engineers looking to integrate RabbitMQ into FastAPI apps or other Python microservices with minimal overhead.

Key Features

  • Reliable Messaging: Send messages to RabbitMQ queues and receive them with automatic acknowledgements, even over connection losses.

  • Auto-Reconnect & Batch Processing: Automatically reconnects on errors and easily handles multiple messages or batch operations.

  • Intuitive Interface: Iterable consumption and context-manager support let you consume messages with Pythonic for loops or with blocks.

  • Queue Management: Inspect queue size and set message TTL per queue, simplifying monitoring and maintenance tasks.

  • Easy Setup: Available on PyPI as rabbit-manager (install with pip install rabbit-manager). Requires Python 3.10+ and the Pika library.

Why Use Rabbit Manager?

RabbitMQ is a popular message broker for building scalable backend systems and microservices. Rabbit Manager removes boilerplate by handling low-level queue tasks, so developers can focus on business logic. It’s especially useful in FastAPI or other async frameworks where seamless background processing is needed. The library includes clear documentation and examples (see the GitHub repo) and even provides a built-in test suite.

Get Involved & Contribute

Join the community! Check out the GitHub repo and the PyPI page for rabbit-manager. Star the project, submit issues, or send pull requests. Whether you’re a Python enthusiast, DevOps engineer, or open-source contributor, your help can make Rabbit Manager even better.

Install Now: pip install rabbit-manager (requires Python 3.10+ and Pika). License: MIT. Get started today and take your Python RabbitMQ integration to the next level!

Github https://github.com/ViktorViskov/rabbit-manager PyPI https://pypi.org/project/rabbit-manager/


r/FastAPI • • Dec 27 '25

Question Supabase templates

15 Upvotes

I have been setting up fastapi manually for every projects since each have a different requirements and everything but I am wondering is there a fastapi template somewhere? I usually off load the auth layer to supabase (i send jwt from the frontend to the backend for jwt verify with signature) and use either sqlalchemy or just use the supabase client to do queries and mutations (let me know if there is a better orm). I also use redis for cache and rate limiting. But setting all of this takes time and I am not even sure if I am setting it up correctly. How do you guys set up fastapi backend and is there a template somewhere?


r/FastAPI • • Sep 01 '25

pip package Looking for a specific FastAPI filtering/sorting library that uses fastapi-pagination

15 Upvotes

Hi guys!
Recently during research I came across a library which provides filtering , sorting and search functionality for fastapi application.
Unfortunately I did not save it and now I am not able to find out which library was it.

As far as I remember it used `fastapi-pagniation` lib to provide pagination support.
It was not definitelyfastapi-filter lib.

Does anyone know which library this might be? I've looked at fastapi-sa-orm-filter, fastapi-listing, and sqlalchemy-filters but none of them seem to match exactly what I remember.

Any help would be greatly appreciated!


r/FastAPI • • Aug 08 '25

feedback request Starting Freelance while learning Fastapi

15 Upvotes

Hello everyone 👋

I’m getting seriously into FastAPI and I’d like to start freelancing soon to work on real projects, and use the income to pay coaches/teachers so I can improve faster.

What I can already do:

CRUD

SQLModel

User management (JWT, OAuth2 + PasswordBearer)

Multiple databases (PostgreSQL, MySQL, MongoDB)

CORS…

Right now, I’m learning RBAC and simple online deployments on Render, DigitalOcean, Replit, Zuplo, etc.

I’m thinking of starting on Fiverr (where you can define your “gigs,” which seems better for a beginner) rather than on Upwork, where clients can request anything.

So, I’d be curious to know:

Has anyone here started freelancing early while still learning FastAPI, without waiting to reach a “high level”? How did it go?

Is it realistic to stand out on Fiverr as a motivated beginner with no reviews?

What are the minimum tasks/services one should offer to maximize chances at the start?

P.S.:

  1. I only do backend. I’m terrible at front-end — absolutely unable to handle it.

  2. For now, I’d like to focus on pure API development tasks rather than getting into advanced cloud deployment services like AWS, which I could learn later once I have a strong mastery of API development itself.

Your feedback and shared experiences would be highly valuable to me 🙏

Thanks in advance for your help!


r/FastAPI • • Jul 04 '25

Question API ideas that can generate income

15 Upvotes

I’m a CS student and I have recently made some side projects APIs with fastapi, Postgres, docker and stripe for payments. I’m wondering what are some API ideas that companies and devs will be willing to pay for and if there is a market for this. I’m not trying to make millions just a side income and get experience and launch in platforms such as rapidapi. What are some features that would make paying for the API an no brainer


r/FastAPI • • Apr 24 '25

Tutorial 📣 [Tool] fastapi-sitemap: Auto-generate sitemap.xml from your FastAPI routes

15 Upvotes

fastapi-sitemap: https://pypi.org/project/fastapi-sitemap/

Dynamically generates a sitemap.xml from your FastAPI routes.

  • Automatically includes all GET routes without path parameters.

  • Excludes routes with path parameters or marked as private.

  • Serves sitemap.xml at the root path.

  • Servess gzipped response with correct MIME type.

Usage:

from fastapi import FastAPI
from fastapi_sitemap import SiteMap

app = FastAPI()

sitemap = SiteMap(
    app=app,
    base_url="https://example.com",
    exclude_patterns=["^/api/", "^/docs/"],  # optional
    gzip=True  # optional
)
sitemap.attach()  # now GET /sitemap.xml is live

You can also add custom URLs using the @sitemap.source decorator.

You can also use it as a cli tool to generate a sitemap, if you prefer.

Source: https://github.com/earonesty/fastapi-sitemap

Disclaimer, I wrote this for myself. Feedback and contributions are welcome.


r/FastAPI • • Feb 27 '25

Hosting and deployment nginx or task queue (celery, dramatiq) ?

15 Upvotes

Hi every one.

I have a heavy task .When client call my API, the heavy task will run in the background, return the result id to user for monitoring the process of the task.

The task is both CPU/IO bound task (do some calculation along with query database and search web asynchronously (using asyncio) ). So i want the task running on different process(or different machine if needed) with the own async loop.

I searched and found tools like proxy(nginx) or task queue (celery) maybe can solve my problem. I read their documents and feel that it can but i'm still not sure about how it does exactly.

Question: What is the tools i should use (can be both or the others)? And the generic strategy to do that.

Thank you.


r/FastAPI • • Feb 26 '25

Question Downgrade openapi for gcp compatibility?

15 Upvotes

I love fast api but there is a mild problem, it serves this new sexy thing called 3.0 which our generous overlords at GCP do not support. I tried for an hour to make a converter, but I know there will always be bugs 😑

Is there a way library that I can feed the output from FastCGI’s OpenAPI and let it gracefully convert it down to 2.0 to make the big guy happy?

[edit less whimsey]

I'm trying to deploy FastAPI to GCP, with API Gateway in front of it.

There has to be a some way to get out of this situation, I'm desperate.

[edit 2]

Thank youl


r/FastAPI • • Feb 21 '25

Question Thinking about re-engineering my backend websocket code

15 Upvotes

Recently I've been running into lots of issues regarding my websocket code. In general, I think it's kinda bad for what I'm trying to do. All the data runs through one connection and it constantly has issues. Here is my alternate idea for a new approach.

For my new approach, I want to have two websocket routes. one for requests and one for events. The requests one will be for sending messages, updating presence, etc. It will have request ids generated by the client and those ids will be returned to the client when the server responds. This is so the client knows what request the server is responding to. The events one is for events like the server telling the users friends about presence updates, incoming messages, when the user accepts a friend request, etc.

What do you guys think I should do? I've provided a link to my current websocket code so you guys can look at it If you want.

Current WS Code: https://github.com/Lif-Platforms/New-Ringer-Server/blob/36254039f9eb11d8a2e8fa84f6a7f4107830daa7/src/main.py#L663


r/FastAPI • • Feb 15 '25

Question State management and separation of routes

15 Upvotes

Generelly i like the decorator style syntax to declare routs of a backend - fastapi style - , but i don't understand how to manage state propperly and separate routs into different modules..

Whenever I start writing smth ita great, but after a while i and up with state defined in globel scope and all routes in onw file..

What is good practice here? Is it possible to separete routs in different files? All routes need the decorator-method which is bound to the FastApi instance, so would i import the instance everywhere? This seems stupid to me..

Also i need to define state used by different routes in global scope which somehow turns me off..

Another question: can methids also be decorated? And if so where would i instancied the class? I guess this is nonsens..

Sorry if this is a stupid question, im fairly new to fastapi. More used to gui frameworks like qt where state is more easily separatable..


r/FastAPI • • Dec 07 '24

Question Help with JWT Auth Flow

15 Upvotes

Firstly I want to say I was super confident in my logic and design approach, but after searching around to try and validate this, I haven’t see anyone implement this same flow.

Context:

  • I have FastAPI client facing services and a private internal-auth-service (not client facing and only accessible through AWS service discovery by my other client-facing services)

  • I have two client side (Frontend) apps, 1 is a self hosted react frontend and second is a chrome extension

Current design:

  • My current flow is your typical login flow, client sends username password to client-facing auth-service. Client facing auth service calls internal-auth-service. Internal-auth service is configured to work with my AWS cognito app client as it’s an M2M app and requires the app client secret which only my internal auth service has. If all is good returns tokens (access and refresh) to my client facing auth-service and this returns response to client with the tokens attached as httponly cookies.

  • now I’ve setup a middleware/dependency in all my backend services that I can use on my protected routes like “@protected”. This middleware here is used to check incoming client requests and validate access token for the protected route and if all is good proceed with the request. NOW here is where I differ in design:

    • the common way I saw it was implemented was when an auth token is expired you return a 401 to client and client has its own mechanism whether that’s a retry mechanism or axios interceptor or whatever, to try and then call the /refresh endpoint to refresh the the token.

  • NOW what I did was to make it so that all token logic is completely decoupled from client side, this middleware in my backend on checking if an access token is valid, when faced with an expired access token will immediately then try and refresh the token. if this refresh succeeds it’s like a silent refresh for the client. If the refresh succeeds my backend will then continue to process the request as if the client is authenticated and then the middleware will reinject the newly refreshed tokens as httponly cookies on the outgoing response.

So example scenario:

  • Client has access token (expired) and refresh token. Both are stored in httponly cookie.

  • Client calls a protected route in my backend let’s say: /api/profile/details (to view users personal profile details)

  • this route in my backend is protected (requires authenticated user) so uses the “@protected” middleware

  • Middleware validates token and realizes it’s expired, instead of replying with 401 response to client, I silently try to refresh the token for the user. The middleware extracts the refresh token from the requests cookies tries to refresh token with my internal-auth-service. If this fails the middleware responds to client with 401 right away since both access and refresh tokens were invalid. Now if refreshing succeeds the middleware then let’s the /api/profile/details handler process the request and in the outgoing response to the user will inject the newly refreshed tokens as httponly.

With this flow the client side doesn’t have to manage:

  1. Retry or manual refresh mechanism

  2. Since the client doesn’t handle token logic like needing to check access token expiry I can securely store my access token in httponly cookies and won’t have to store access token in a JS accessible memory like localStorage

  3. The client side logic is super simplified a single 401 returned from my backend isn’t followed by a retry or refresh request, instead my client can assume any 401 means redirect user to /login.

  4. Lastly this minimises requests to my backend: as this one request to my backends protected route with an expired access token responded with newly refreshed tokens. So reduced it from 3 calls to 1. The 3 calls being (initial call, refresh call, retrying initial call)

So my overall question is why do people not implement this logic? Why do they opt for the client side handling the refreshes and token expiry? In my case I don’t even have a /refresh endpoint or anything it’s all internal and protected.

I know I rambled a lot so really appreciate anyone who actually reads the whole thing🙏, just looking for some feedback and to get a second opinion in case my implementation has a fault I may have overlooked.