r/FastAPI • • Apr 12 '26

Other Open-Source Full-Stack Template inspired by FastAPI Template and Netflix's Dispatch

Thumbnail
gallery
26 Upvotes

For educational and commercial purposes, I developed my minimalist full-stack template inspired by official FastAPI template and Netflix's Dispatch service.

Backend: FastAPI, SQLAlchemy, Pydantic

Frontend: React, Material UI, Nginx

Link to live-demo: https://full-stack-template.xyz

Github project: https://github.com/konverner/full-stack-template

I have tried to respect the best practices of API and UI/UX design. I put sources in README for educational purposes.

I have tested this template across 5 commercial projects, and I am (my clients are as well) satisfied with the results as for now.

I would be happy share it with you and to hear feedback


r/FastAPI • • Feb 21 '26

Question When to use background tasks considering their non-persistence?

26 Upvotes

What is the best use case for background tasks?

I am wondering when to use them because once the service restarts, the tasks could be lost without finishing execution, which leads to inconsistent behavior, after successfully returning the response to the client


r/FastAPI • • Sep 05 '25

Question Does anyone use this full-stack-fastapi-template?

26 Upvotes

Does anybody ever tried this

https://github.com/fastapi/full-stack-fastapi-template

If yes , then how was the experience with it. Please share your good and bad experiences as well.


r/FastAPI • • Sep 03 '25

Question Admin Panel for FastAPI + SqlAlchemy 2.0 project?

26 Upvotes

Any recommendations? Thanks in advance.


r/FastAPI • • Aug 23 '25

pip package APIException v0.2.0 – Consistent FastAPI Responses + Better Logging + RFC Support

26 Upvotes

Hey all,

A while back, I shared APIException, a library I built to make FastAPI responses consistent and keep Swagger docs clean. Quite a few people found it useful, so here’s the update.

Version 0.2.0 is out. This release is mainly about logging and exception handling. APIException now:

  • catches both expected and unexpected exceptions in a consistent way

  • lets you set log levels

  • lets you choose which headers get logged or echoed back

  • supports custom log fields (with masking for sensitive data)

  • supports extra log messages

  • adds header and context logging

  • has simplified imports and added full typing support (mypy, type checkers)

  • adds RFC7807 support for standards-driven error responses

I also benchmarked it against FastAPI’s built-in HTTPException. Throughput was the same, and the average latency difference was just +0.7ms. Pretty happy with that tradeoff, given you get structured logging and predictable responses.

It was also recently featured in Python Weekly #710, which is a nice boost of motivation.

PyPI: https://pypi.org/project/apiexception/

GitHub: https://github.com/akutayural/APIException

Docs: https://akutayural.github.io/APIException/

Youtube: https://youtu.be/pCBelB8DMCc?si=u7uXseNgTFaL8R60

If you try it out and spot bugs or have ideas, feel free to open an issue on GitHub. Always open to feedback.


r/FastAPI • • Aug 14 '25

Question Lifespan on Fastapi

26 Upvotes

Hey guys, been enjoying fastapi for a bit now. How much do you use lifespan on fastapi and on what purposes have you used it on?


r/FastAPI • • Jun 10 '25

Hosting and deployment Fixing FastAPI Throughput Without Going Fully Async

Thumbnail dpdzero.com
26 Upvotes

We had a lot of trouble over the last couple of years in getting good throughput in our APIs due to sync IO libraries. A migration to async libraries would be the best thing to do - we figured out the next best option


r/FastAPI • • Feb 09 '25

Question New to FastApi

26 Upvotes

Hey there, I am new to FastApi, I come from django background, wanted to try fastapi and it seems pretty simple to me. Can you suggest me some projects that will help me grasp the core concepts of fastapi? Any help is appreciated


r/FastAPI • • Jan 10 '25

Other Real world scenario FastAPI vs Node.js k8s cluster benchmarks

26 Upvotes

Here is a video comparing FastAPI vs node.js and you can clearly see the performance difference between them.

FastAPI is clearly writing false advertisement on their site !

Same machine resources, using the same Redis/DB instance real time. It’s closest as possible to a modern prod environment. And FastAPI is not at all close to being as fast as NodeJS, as said on the site.

https://m.youtube.com/watch?v=i3TcSeRO8gs

Disclaimer:

On the site it does talk about actual performance of code not about how fast you can develop an app with it.

Quote from the oficial site (https://fastapi.tiangolo.com/) :

“Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.

Fast to code: Increase the speed to develop features by about 200% to 300%. *”

See the difference between “Fast” and “Fast to code”

Edit: there’s also one for Golang:

https://m.youtube.com/watch?v=sxdpKG-6HSY

And as you can see actually the number between Golang and Nodejs are not that far away, they are both far away from the claims from the site.

Simple test: Nodejs: 50k Golang: 65k Fastapi: 11k

DB/Redis: Nodejs: 9k Golang: 18k Fastapi: 2.5k


r/FastAPI • • Nov 18 '24

Question Should I use async or sync DB (DB driver? i'm not sure ) with FastAPI

26 Upvotes

Building my first project in FastAPI and i was wondering if i should even bother using async DB calls, normally with SQLAlchemy all the calls are synchronous but i can also use an async engine for it async DB's. But is there even any significant benefit to it? I have no idea how many people would be using this project and writing async code seems a bit more complicated compared to the sync code i was writing with SQLModel but that could be because of SQLAlchemy only.

Thanks for any advice and suggestions


r/FastAPI • • Jul 09 '24

Question Any FastAPI GitHub Repositories with Good Practices for Serving ML Models

26 Upvotes

Hello everyone,

I'm looking for great FastAPI GitHub repositories that serve machine learning models. I want to learn from the best examples. Do you have any recommendations?

Thanks in advance!


r/FastAPI • • Apr 14 '23

Question Is it really advisable to try to run fastapi with predominantly sync routes in a real world application?

26 Upvotes

I worry the fastapi docs are misleading. It says “If you just don't know, use normal `def`.” and “in any of the cases above, FastAPI will still work asynchronously and be extremely fast.”

You also have people latching on to this guy scaremongering about async. To me it is a serious problem that fastapi’s docs don’t themselves take any stance on best practices, sync vs async. The docs just say magically everything will be fast and magically sync will “work asychronously”
https://www.reddit.com/r/Python/comments/wrt7om/fastapi_best_practices/

People afraid of async but who like fastapi otherwise will think that the framework is really ready to go in production with sync only routes.

The reality seems to be different. The starlette thread pool is shared across all threaded things including background tasks and things like this, so it’s easy to exhaust the threadpool. What about applying safe request timeouts which is an absolute necessity when using a sync approach? Why the don’t say anything about this either?

And all across github I am finding people close to fastapi recommending that people should use async rather than sync, if they don’t know any better. And yet the stupid docs say the exact opposite!

I am about ready to open a PR to modify the docs a bit. But I just want to hear it from someone who has more experience or has been following fastapi longer (for me I just started looking into this aspect of it in the past few days). Really, it would be nice for the devs or the part of the community really driving it, to take a stance on sync vs async. I can scarcely believe their claim that everything will be fine, whichever one you choose. I almost suspect they are just trying to make the framework seem magical to get people hooked and then they will worry about actually fixing things later (dishonest, not transparent, risky).

The reasons are:

  1. In this thread, starlette people admitting they don’t have anywhere near the tuning features necessary for more heavily sync oriented people https://github.com/encode/starlette/issues/1724

  2. Lack of docs explaining how to deal with configuring timeouts which is absolutely essential when using sync workers, and for example this absolute trainwreck of a discussion about configuring timeouts, which the lead dev / creator of fastapi fails to contribute to or offer any guidance
    https://github.com/tiangolo/fastapi/discussions/7364

  3. The clear fact that the frameworks which do manage to be good at sync are either a) using async workers e.g. via gunicorn gevent patching or b) offer lots of tuning options and documentation for sync workers, not just a single threadpool and an absolute chaos on github.

If you can sense I’m frustrated, it’s because I work on a team who picked up fastapi because of its cool features, and then they got scared of async and read those lines of the docs which make fastapi sound magical at turning sync into async, and decided to throw out async and make all their routes sync, and now I’m having to try to wade through the absolute chaos of this framework not being able to convincingly take a stance on the issue.


r/FastAPI • • Sep 26 '21

pip package Imia - the authentication library for Starlette and FastAPI

26 Upvotes

r/FastAPI • • Mar 13 '26

pip package Why fastapi-guard

25 Upvotes

Some of you already run fastapi-guard. For those who don't... you probably saw the TikTok. Guy runs OpenClaw on his home server, checks his logs. 11,000 attacks in 24 hours. I was the one who commented "Use FastAPI Guard" and the thread kind of took off from there. Here's what it actually does.

from guard import SecurityMiddleware, SecurityConfig

config = SecurityConfig(
    blocked_countries=["CN", "RU"],
    blocked_user_agents=["Baiduspider", "SemrushBot"],
    block_cloud_providers={"AWS", "GCP", "Azure"},
    rate_limit=100,
    rate_limit_window=60,
    auto_ban_threshold=10,
    auto_ban_duration=3600,
)

app.add_middleware(SecurityMiddleware, config=config)

One middleware call. 17 checks on every inbound request before it hits your path operations. XSS, SQL injection, command injection, path traversal, SSRF, XXE, LDAP injection, code injection. The detection engine includes obfuscation analysis and high-entropy payload detection for novel attacks. On top of that: rate limiting with auto-ban, geo-blocking, cloud provider IP filtering, user agent blocking, OWASP security headers.

Every attack from that TikTok maps to a config field. Those 5,697 Chinese IPs? blocked_countries. Done. Baidu crawlers? blocked_user_agents. The DigitalOcean bot farm? Cloud provider ranges are fetched and cached automatically, blocked on sight. Brute force sequences? Rate limited, then auto-banned after threshold. .env probing and path traversal? Detection engine catches those with zero config.

The OpenClaw audit makes it worse. 512 vulnerabilities across the codebase, 8 critical, 40,000+ exposed instances. 60% immediately takeable. ClawJacked (CVE-2026-25253) lets any website hijack a local instance through WebSocket. If you're exposing FastAPI endpoints to the internet, you need request-level security.

Decorator system works per-route, async-native:

from guard.decorators import SecurityDecorator

guard_decorator = SecurityDecorator(config)

@app.get("/api/admin")
@guard_decorator.require_ip(whitelist=["10.0.0.0/8"])
@guard_decorator.block_countries(["CN", "RU", "KP"])
async def admin():
    return {"status": "ok"}

What people actually use it for: startups building in stealth mode with remote teams, public API but whitelisted so nobody outside the company can even see it exists. Casinos and gaming platforms using decorators on reward endpoints so players can only win under specific conditions. Honeypot traps for LLMs and bad bots that crawl and probe everything. And the one that keeps coming up more and more... AI agent gateways. If you're running OpenClaw or any agent framework on FastAPI, those endpoints are publicly reachable by design. The audit found 512 vulnerabilities, 8 critical, 40,000+ exposed instances. fastapi-guard would have blocked every attack vector in those logs. This is going to be the standard layer for anyone deploying AI agents in production.

I also just shipped a Flask equivalent if anyone's running either or both. flaskapi-guard v1.0.0. Same detection engine, same pipeline, same config field names.

fastapi-guard: https://github.com/rennf93/fastapi-guard flaskapi-guard: https://github.com/rennf93/flaskapi-guard flaskapi-guard on PyPI: https://pypi.org/project/flaskapi-guard/

If you find issues with either, open one.


r/FastAPI • • Sep 25 '25

Tutorial Want to use FastAPI with the AI SDK frontend? I built this

25 Upvotes

Tired of wiring glue to stream chat from Python to your app? I made a small helper that connects FastAPI to the AI SDK protocol so you can stream AI responses with almost no hassle.

What you get:

  • Full event coverage: text, reasoning, tool calls, structured data, errors

  • Built-in streaming with SSE

  • Typed models with Pydantic

  • Simple API: builder and decorators

Links: GitHub: github.com/doganarif/fastapi-ai-sdk

Feedback is welcome!


r/FastAPI • • Aug 24 '25

feedback request Smart Plug Notifier – Microservice system for real-time appliance monitoring built using FastAPI

Thumbnail
github.com
25 Upvotes

Hey everyone,

I recently built a small project called Smart Plug Notifier (SPN). It uses TP-Link Tapo smart plugs to monitor when my washer and dryer start or finish their cycles. The system is built as an async, event-driven microservice architecture with RabbitMQ for messaging and a Telegram bot for notifications.

For my personal use I only run it on two plugs, but it’s designed to support many devices. Everything is containerized with Docker, so it’s easy to spin up the full stack (tapo service, notification service, and RabbitMQ).

I’m mainly using it to never forget my laundry again 😅, but it could work for any appliance you want real-time power usage alerts for.

I’d love to get some feedback on the architecture, setup, or ideas for improvements.
Here’s the repo: 👉 https://github.com/AleksaMCode/smart-plug-notifier


r/FastAPI • • Jul 16 '25

Question Idiomatic usage of FastAPI

25 Upvotes

Hello all. I plan on shifting my backend focus to FastAPI soon, and decided to go over the documentation to have a look at some practices exclusive to FastAPI (mainly to see how much it differs from Flask/asyncio in terms of idiomatic usage, and not just writing asynchronous endpoints)

One of the first things I noticed was scheduling simple background tasks with BackgroundTasks included with FastAPI out of the box.

My first question is: why not just use asyncio.create_task? The only difference I can see is that background tasks initiated this way are run after the response is returned. Again, what may be the issues that arise with callingasyncio.create_task just before returning the response?

Another question, and forgive me if this seems like a digression, is the signatures in path operation function using the BackgroundTask class. An example would be:

async def send_notification(email: str, background_tasks: BackgroundTasks): ...

As per the documentation: "FastAPI will create the object of type BackgroundTasks for you and pass it as that parameter."

I can't seem to understand why we aren't passing a default param like:

background_task: BackgroundTasks = BackgroundTask()

Is it simply because of how much weightage is given to type hints in FastAPI (at least in comparison to Flask/Quart, as well as a good chunk of the Python code you might see elsewhere)?


r/FastAPI • • Jun 13 '25

Question Scaling a real-time local/API AI + WebSocket/HTTPS FastAPI service for production how I should start and gradually improve?

25 Upvotes

Hello all,

I'm a solo Gen AI developer handling backend services for multiple Docker containers running AI models, such as Kokoro-FastAPI and others using the ghcr.io/ggml-org/llama.cpp:server-cuda image. Typically, these services process text or audio streams, apply AI logic, and return responses as text, audio, or both.

I've developed a server application using FastAPI with NGINX as a reverse proxy. While I've experimented with asynchronous programming, I'm still learning and not entirely confident in my implementation. Until now, I've been testing with a single user, but I'm preparing to scale for multiple concurrent users.The server run on our servers L40S or A10 or cloud in EC2 depending on project.

I found this resources that seems very good and I am reading slowly through it. https://github.com/zhanymkanov/fastapi-best-practices?tab=readme-ov-file#if-you-must-use-sync-sdk-then-run-it-in-a-thread-pool. Do you recommend any good source to go through and learn to properly implement something like this or something else.

Current Setup:

  • Server Framework: FastAPI with NGINX

  • AI Models: Running in Docker containers, utilizing GPU resources

  • Communication: Primarily WebSockets via FastAPI's Starlette, with some HTTP calls for less time-sensitive operations

  • Response Times: AI responses average between 500-700 ms; audio files are approximately 360 kB

  • Concurrency Goal: Support for 6-18 concurrent users, considering AI model VRAM limitations on GPU

Based on my research I need to use/do:

  1. Gunicorn Workers: Planning to use Gunicorn with multiple workers. Given an 8-core CPU, I'm considering starting with 4 workers to balance load and reserve resources for Docker processes, despite AI models primarily using GPU.

  2. Asynchronous HTTP Calls: Transitioning to aiohttp for asynchronous HTTP requests, particularly for audio generation tasks as I use request package and it seems synchronous.

  3. Thread Pool Adjustment: Aware that FastAPI's default thread pool (via AnyIO) has a limit of 40 threads supposedly not sure if I will need to increase it.

  4. Model Loading: I saw in doc the use of FastAPI's lifespan events to load AI models at startup, ensuring they're ready before handling requests. Seems cleaner not sure if its faster FastAPI Lifespan documentation.

  5. I've implemented a simple session class to manage multiple user connections, allowing for different AI response scenarios. Communication is handled via WebSockets, with some HTTP calls for non-critical operations.

  6. Check If I am not doing something wrong in dockers related to protocols or maybe I need to rewrite them for async or parallelism?

Session Management:

I've implemented a simple session class to manage multiple user connections, allowing for different AI response scenarios. Communication is handled via WebSockets, with some HTTP calls for non-critical operations. But maybe there is better way to do it using address in FastApi /tag.

To assess and improve performance, I'm considering:

  • Logging: Implementing detailed logging on both server and client sides to measure request and response times.

WebSocket Backpressure: How can I implement backpressure handling in WebSockets to manage high message volumes and prevent overwhelming the client or server?

Testing Tools: Are there specific tools or methodologies you'd recommend for testing and monitoring the performance of real-time AI applications built with FastAPI?

Should I implement Kubernetes for this use case already (I have never done it).

For tracking speed of app I heard about Prometheus or should I not overthink it now?


r/FastAPI • • Mar 25 '25

Question FastAPI database migrations

25 Upvotes

Hi everyone, In your FastAPI projects, do you prefer using Alembic or making manual updates for database migrations? Why do you choose this approach, and what are its advantages and disadvantages?


r/FastAPI • • Dec 22 '24

Question Slow DB ORM operations? PostgresSQL+ SQLAlchemy + asyncpg

25 Upvotes

I'm running a local development environment with:

  • FastAPI server

  • PostgreSQL database

  • Docker container setup

I'm experiencing what seems to be performance issues with my database operations:

  • INSERT queries: ~100ms average response time

  • SELECT queries: ~50ms average response time

Note: First requests are notably slower, then subsequent requests become faster (possibly due to caching).

My current setup includes:

  • Connection pooling enabled

  • I think SQLAlchemy has caching???

  • Database URL using "postgresql+asyncpg" driver

I feel these response times are slower than expected, even for a local setup. Am I missing any crucial performance optimizations?

If I remove connection pooling to work with serverless enviroments like vercel is SO MUCH WORSE, like 0.5s/1s second per operation.

EDIT: Here is an example of a create message function

EDIT2:

I am doing the init in the startup event and then I have this dep injection:

Thanks everyone!
The issue is I am running session.commit() everytime I do a DB operation, I should run session.flush() and then the session.commit() at the end of the get_db() dependency injection lifecycle


r/FastAPI • • Sep 15 '24

Question How to you justify not going full stack TS?

25 Upvotes

Hi, I'm getting challenged in my tech stack choices. As a Python guy, it feels natural to me to use as more Python as I can, even when I need to build a SPA in TS.

However, I have to admit that having a single language on the whole codebase has obvious benefits like reduced context switching, model and validation sharing, etc.

When I used Django + TS SPA, it was a little easier to justify, as I could say that there is no JS-equivalent with so many batteries included (nest.js is very far from this). But with FastAPI, I think there exists equivalent frameworks in term of philosophy, like https://adonisjs.com/ (or others).

So, if you're using fastAPI on back-end while having a TS front-end, how do you justify it?


r/FastAPI • • Aug 07 '24

Hosting and deployment How does FastAPI utilize the CPU?

25 Upvotes

I've been running the fastapi app with a single worker uvicorn instance in Docker container (FYI the API is fully async).

Now, I need to adjust k8s resources to fit the application usage. Based on the FastAPI documentation here: FastAPI in Containers - Docker - FastAPI (tiangolo.com), it's clear that there should be an assigned max 1 CPU per single app instance. But is it true tho?

On paper, it makes sense, because GIL bounds us with a single process, also FastAPI uses parallelism (asyncio) with additional threads to handle requests but in the end, there is no multiprocessing. So this means that it can't utilize more than 100% of 1 CPU effectively.

But.. I've run several load tests locally and on the DEV environment and the logs and stats show that the single app instance often reaches over 100% of a single CPU. Here is the screenshot from Docker desktop from the container with the app:

So how is it possible? How does FastAPI utilize the CPU?


r/FastAPI • • Jun 28 '24

Question FastAPI + React

25 Upvotes

Hey
I am using FastAPI and React for an app. I wanted to ask a few questions:

  1. Is this is a good stack?

  2. What is the best way to send sensitive data from frontend to backend and backend to frontend? I know we can use cookies but is there a better way? I get the access token from spotify and then i am trying to send that token to the frontend.

  3. How do I deploy an app like this? Using Docker?

Thanks!


r/FastAPI • • Jul 17 '22

Tutorial FastAPI starter template with SQLModel, Alembic and Pytest

25 Upvotes

Check out my FastAPI starter template with SQLModel, Alembic, Pytest. It also includes Docker and CI support.

https://github.com/mirzadelic/fastapi-starter-project/

Any feedback/PR is welcome.