r/FastAPI • • May 10 '21

Tutorial Asynchronous Tasks with FastAPI and Celery

Thumbnail
testdriven.io
34 Upvotes

r/FastAPI • • May 04 '21

Tutorial Dockerizing FastAPI with Postgres, Uvicorn, and Traefik

Thumbnail
testdriven.io
34 Upvotes

r/FastAPI • • Oct 12 '26

feedback request Built my first real FastAPI project a few months ago, it finally has a proper frontend now

Thumbnail
gallery
33 Upvotes

Some of you might recognize the repo. I posted an earlier version here it was basically just a FastAPI backend and Swagger docs. A few people gave it really useful feedback then the market-data part stopped working, so I deleted the post instead of pretending it was fine.

It’s working again now, and it has an actual frontend.

It’s a stock research/watchlist app I use myself. I'm from finanace background, I trade, and I wanted somewhere to track stocks and write research notes that save the price I was looking at when I wrote them. It tracks 14 market indices and supports stock watchlists, quotes, news, and notes.

The stack is FastAPI, async SQLAlchemy, Postgres, JWT auth, Docker, and a small HTML/CSS/JS frontend.

The most annoying bug was that Yahoo Finance worked locally but started returning '401 Invalid Crumb' errors from Render. I changed the quote path to fall back to Yahoo’s chart/history data, and added RSS sources for news when the main news path fails. It took longer than I expected to get local and deployed behavior lined up.

Note: This isn’t a trading platform, and it’s definitely not finished. I’m posting it again because it’s now more than API docs, and because the last round of feedback was genuinely helpful. If you spot something badly designed, confusing, or fragile, I’d rather hear it.

Repo: https://github.com/ah4ddd/first-order

I’m leaving the live Render URL out of the post; it’s linked from the repo for anyone who wants to try it.


r/FastAPI • • Sep 22 '25

Hosting and deployment We just launched Leapcell, deploy 20 FastAPI services for free

33 Upvotes

hi r/fastapi 👋

In the past, I had to shut down small Python projects because cloud costs and maintenance overhead were just too high. They ended up sitting quietly on GitHub, untouched. I kept wondering: what would happen if these projects could stay online?

That’s why we created Leapcell: a platform designed so your FastAPI ideas can stay alive without getting killed by costs in the early stage.

Deploy up to 20 API services for free (included in our free tier)

Most PaaS platforms give you a single free VM (like the old Heroku model), but those machines often sit idle. Leapcell takes a different approach: we use a serverless container architecture to maximize resource usage and let you host multiple APIs simultaneously. While other platforms only let you run one free project, Leapcell lets you run up to 20 FastAPI services side by side.

We were inspired by platforms like Vercel (multi-project hosting), but Leapcell goes further:

  • Multi-language support: Python (FastAPI, Django, Flask), Node.js, Go, Rust, etc.

  • Two compute modes:

    • Serverless: cold start < 250ms, scales automatically with traffic (perfect for early-stage FastAPI apps).

    • Dedicated machines: predictable costs, no risk of runaway serverless bills, better unit pricing.

  • Built-in stack: PostgreSQL, Redis, async tasks, logging, and even web analytics out of the box.

So whether you’re testing a new API idea, building a microservice, or scaling into production, you can start for free and only pay when you truly grow.

If you could host 20 FastAPI services for free today, what would you deploy first?


r/FastAPI • • 20d ago

Tutorial fastapi-multiauth: accept cookies, bearer tokens and API keys on the same route, with correct OpenAPI docs

32 Upvotes

Hey everyone,

I wanted to share a library I've been working on over the past 3 months: fastapi-multiauth.

My FastAPI apps usually need more than one way to log in: a session cookie for the frontend, a bearer token for scripts, an API key for automation. Getting one route to accept all of them, with Swagger showing it right, takes a lot of boilerplate. The libraries I tried either handled one scheme at a time or pushed their own user model, so I built my own.

You bring the validator: one function (sync or async) that takes a credential and returns your user. Use SQLAlchemy, Redis, an identity provider or a plain dict. No ORM, no database and no user model are imposed.

The library pulls the credential from the request, tries each scheme, and documents them all in OpenAPI.

from fastapi import FastAPI, Security
from fastapi_multiauth import APIKeyCookieAuth, HTTPBearerAuth, MultiAuth, UnauthorizedError


async def validate_token(token: str) -> dict:
    user = await find_user_by_token(token)  # your logic
    if user is None:
        raise UnauthorizedError()
    return user


async def validate_session(user_id: str) -> dict:
    user = await get_user(user_id)  # your logic
    if user is None:
        raise UnauthorizedError()
    return user


bearer = HTTPBearerAuth(validator=validate_token, prefix="user_")
session = APIKeyCookieAuth(name="__Host-session", validator=validate_session, secret_key=SECRET_KEY)
auth = MultiAuth(bearer, session)

app = FastAPI()


@app.get("/me")
async def me(user: dict = Security(auth)):
    return user

That's it. /me accepts a valid bearer token or a valid session cookie, and Swagger lists both.

Some of the more advanced stuff:

  • Signed cookie sessions with key rotation and optional revocation

  • Opaque tokens with prefixes (user_...), hash-only storage and checksums

  • Fail-closed scope checks and step-up auth (fresh(), stepped_up()) for sensitive routes

  • OAuth2/OIDC login helpers: discovery, PKCE, state, code exchange

  • auth_surface(app) to audit which guard protects each route

More examples and recipes: https://fastapi-multiauth.d3vyce.fr/recipes

Feedback welcome, especially if you've handled multi-scheme auth in FastAPI another way.


r/FastAPI • • Jul 10 '26

feedback request PEP 835: A native shorthand for Annotated

32 Upvotes

Ivan Levkivskyi and I are proposing a native shorthand for Annotated (PEP 835) to clean up heavy type-hinting patterns. We have confirmed this syntax is fully compatible with FastAPI and works out of the box with zero changes required.

Before:

def create_user(
    id: Annotated[int, Path(gt=0)],
    name: Annotated[str, Query(min_length=3)],
    role: Annotated[str, Query(min_length=2)] = "user"
) -> User: ...

After:

def create_user(  
    id: int @Path(gt=0),  
    name: str @Query(min_length=3),  
    role: str @Query(min_length=2) = "user"  
) -> User: ...

The Spec: PEP 835 Full Draft

We are gathering community sentiment before moving forward. If you are a heavy user of Annotated in FastAPI, your feedback is valuable. You can register your stance in the official Discourse poll before it closes on July 15.


r/FastAPI • • May 12 '26

feedback request How are you handling production background tasks in FastAPI without Celery?

32 Upvotes

Hey everyone 👋

A while ago I built an open source library called FastAPI Taskflow:

fastapi-taskflow GitHub repository

The goal was to make FastAPI BackgroundTasks more production-ready by adding retries, resiliency, control and visibility without workers or brokers.

It adds extra features like:

  • task persistence

  • concurrency limits

  • scheduling

  • task lifecycle management

  • monitoring dashboard

I’m trying to understand how people are actually using it in real projects and where the pain points still are.

If you’ve used it (even briefly), I’d really love to know:

  • what problem you used it for

  • what worked well

  • what felt awkward or missing

  • where it broke down

  • features you expected but weren’t there

  • whether you eventually switched to Celery/TaskIQ/etc and why

Even if you’re not using it, I’m curious what your current approach is for handling background tasks in FastAPI at scale.

If you find the project interesting or useful, a star on GitHub would also really help support it 🙏


r/FastAPI • • Apr 29 '26

Other You Probably Don't Need Celery in Your FastAPI App

32 Upvotes

A lot of FastAPI developers end up with Celery not because they need a distributed task queue, but because BackgroundTasks stopped being enough and Celery was the first thing that came up when they searched for a solution.

This is about that gap, and a library that fills it without the overhead.

What BackgroundTasks does not give you

FastAPI's built-in BackgroundTasks is straightforward. You attach a function to the response and Starlette calls it after the response is sent.

@app.post("/signup")
def signup(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_welcome_email, email)
    return {"ok": True}

That covers fire-and-forget. But in a real application you quickly hit walls:

No retries. If send_welcome_email fails because the SMTP server returned a 503, the task is gone. There is no retry, no backoff, no record of what happened.

No persistence. If the app restarts during a deploy, every queued task disappears. Tasks that were waiting to run simply never run.

No visibility. You cannot see what is running, what has run, what failed, or how long things took. The only way to know a task failed is to catch it in your logs, if you are logging at all.

No scheduling. BackgroundTasks runs things once, after the current request. There is no built-in way to run something on a schedule.

These are not edge cases. They are the baseline requirements for any background job in production.

Why Celery is the wrong answer for most of these

When developers hit these limitations, the standard advice is: add Celery. And Celery does solve all four problems. But it solves them by giving you a distributed task queue, which comes with the full infrastructure that entails.

To use Celery with FastAPI you need:

  • A message broker. Usually Redis or RabbitMQ. A separate service to run, configure, monitor, and back up.

  • A worker process. A separate process that consumes from the broker. Needs to be deployed, restarted on failure, and kept in sync with the app on every deploy.

  • Celery Beat for scheduling. Another separate process.

  • Flower or similar if you want visibility. Yet another service.

Celery was built for teams running tasks on dedicated workers across multiple machines at high volume. If that describes your situation, it is the right tool. But most FastAPI apps sending emails, processing uploads, running nightly reports, and syncing data are not in that category. They just needed BackgroundTasks to grow up a little.

What actually fills the gap

fastapi-taskflow is built specifically for this problem: FastAPI apps that have outgrown BackgroundTasks but do not need a distributed task queue.

It runs inside your FastAPI process. No broker. No separate worker. Tasks execute the same way they do today, after the response, but now with retries, persistence, scheduling, and a live dashboard.

Setup:

from fastapi import BackgroundTasks, FastAPI
from fastapi_taskflow import TaskAdmin, TaskManager

task_manager = TaskManager(snapshot_db="tasks.db", requeue_pending=True)
app = FastAPI()
TaskAdmin(app, task_manager, auto_install=True)

Retries:

@task_manager.task(retries=3, delay=60.0, backoff=2.0)
def send_welcome_email(email: str):
    _send(email)  # raise any exception — the retry handles it

The function stays a plain function. Raise an exception on failure and it retries automatically with exponential backoff.

Your routes stay the same:

@app.post("/signup")
def signup(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_welcome_email, email=email)
    return {"ok": True}

Same annotation. Same calling convention. Nothing changes in your routes.

Persistence across restarts:

requeue_pending=True saves tasks that were queued at shutdown and re-dispatches them on the next startup. Tasks no longer disappear on deploy.

Scheduling:

@task_manager.schedule(cron="0 2 * * *")
def nightly_cleanup():
    _run_cleanup()

No Beat process. No separate service. The scheduler runs inside the app.

Eager dispatch:

BackgroundTasks always runs after the response is sent. If you need a task to start immediately, before the response goes out, set eager=True:

@task_manager.task(retries=3, eager=True)
async def notify_user(user_id: int):
    await push_service.send(user_id, "Your request is processing")

The task starts via asyncio.create_task the moment add_task() is called. It is still tracked, still retried on failure, still visible in the dashboard. You can also set it per call:

background_tasks.add_task(notify_user, user_id, eager=True)

Visibility:

/tasks/dashboard is a live dashboard that shows every task, its current status, duration, logs, and the full stack trace on failure. It updates over SSE in real time. No Flower setup, no external monitoring service.

The honest trade-offs

This is not a Celery replacement. If your tasks are CPU-intensive and need isolation from request handlers, if you need to route different task types to dedicated worker machines, or if you are processing thousands of tasks per minute, you need a proper task queue.

What fastapi-taskflow covers is the case where you reached for Celery because BackgroundTasks gave you nothing, not because you genuinely needed distributed workers.

For a single-host deployment, multiple instances on the same host share a SQLite file. For multiple hosts, swap to Redis or PostgreSQL as the backend and idempotency, requeue claiming, and task history all work across instances without any coordination overhead.

What you skip entirely

No broker to run or monitor. No worker process to deploy or restart. No Celery app instance or separate tasks module. No Beat process for scheduling. No Flower for visibility.

Local development stays at uvicorn app.main:app. New developers on the project do not need to learn a separate system.

The four things that pushed you toward Celery in the first place, retries, persistence, scheduling, and visibility, are covered.


r/FastAPI • • Feb 01 '26

Question Advice on logging in production

32 Upvotes

Hey everyone,

I’m exploring different logging options for my projects (fastapi RESTful backend and I’d love some input.

So far I’ve monitored the situations as following:

  • fastapi dev  and fastapi run commands display logs in stdout

  • fastapi run --workers 4 command doesn't display logs in stoud

Is this intended behavior? Am i supposed to get logs in stdout and schedule a task in the server running Docker or should I handle my logs internally?

I’m mostly interested in:

  • Clean logs (readability really matters)

  • Ease of use / developer experience

  • Flexibility for future scaling (e.g., larger apps, integrations)

Is there a best practice here for logging in production that I should know about, feels like it since stdout is disabled on prod?
Is there some hidden gem I should check out instead?

Thanks in advance!


r/FastAPI • • Jan 17 '26

pip package I built TimeTracer, record/replay API calls locally + dashboard (FastAPI/Flask)

32 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 it does:

  • Records an API request into a JSON “cassette” (timings + inputs/outputs)

  • Lets you replay it locally with dependencies mocked (or hybrid replay)

What’s new/cool:

  • Built-in dashboard + timeline view to inspect requests, failures, and slow calls

  • Works with FastAPI + Flask

  • Supports capturing httpx, requests, SQLAlchemy, and Redis

Security:

  • More automatic redaction for tokens/headers

  • PII detection (emails/phones/etc.) 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, documentation, or new integrations), I’d love the support.

Looking for feedback: What would make you actually use something like this, pytest integration, better diffing, or more framework support?


r/FastAPI • • Jan 05 '26

pip package FastAPI caching with more flexibility

32 Upvotes

Working on a project that needed different caching strategies for different endpoints. fastapi-cache2 felt too limiting, raw redis-py meant too much boilerplate.

So I made fastapi-rc. It's definitely nothing super special or groundbreaking, but the main difference is you get three approaches:

Pattern 1: Direct Redis access Full control for complex operations (bulk invalidation, pipelines, etc)

Pattern 2: CacheService wrapper Handles common patterns automatically:

  • Cache-aside (get_or_set)

  • Automatic serialization with Pydantic models

  • Pattern based invalidation

  • TTL management with jitter

Pattern 3: Custom cache dependencies Define caching strategy once, inject everywhere:

async def get_user_cache(redis: RedisClient) -> CacheService[User]:
    return CacheService(
        redis,
        namespace="users",
        model=User,
        default_ttl=600,
        use_jitter=True,
    )

UserCache = Annotated[CacheService[User], Depends(get_user_cache)]

All three patterns use FastAPI's Depends() so it feels native.

Out of the box:

  • Connection pooling with configurable size

  • Retry logic with exponential backoff

  • Health checks

  • Graceful degradation if Redis unavailable

Type safety with generics. CacheService[User] enforces return type.

Install: pip install fastapi-rc

Source: https://github.com/CarterPerez-dev/fastapi-rc

I just built it for one of my projects then decided I might as well make it a package, so lmk what you think or if you have any feedback.


r/FastAPI • • Dec 26 '25

Hosting and deployment Where do you deploy your FastAPI app to?

32 Upvotes

Not many edge function solutions support FastAPI. I wonder how and where you deploy your FastAPI app to?


r/FastAPI • • Oct 20 '25

Question How do you optimize speed

32 Upvotes

Here's what I've done so far

  1. Used redis

  2. Used caching on the frontend to avoid too many backend calls

  3. Used async

  4. Optimised SQL alchemy query

I think I'm missing something here because some calls are 500ms to 2sec which is bad cause some of these routes return small data. Cause similar project I build for another client with nodejs gives me 100ms-400ms with same redis and DB optimizing startegy.


r/FastAPI • • Sep 04 '25

Question Looking for a high-quality course on async Python microservices (FastAPI, Uvicorn/Gunicorn) and scaling them to production (K8s, AWS/Azure, OpenShift)

32 Upvotes

Hey folks,

I’m searching for a comprehensive, high-quality course in English that doesn’t just cover the basics of FastAPI or async/await, but really shows the transformation of microservices from development to production.

What I’d love to see in a course:

  • Start with one or multiple async microservices in Python (ideally FastAPI) that run with Uvicorn/Gunicorn(using workers, concurrency, etc.).

  • Show how they evolve into production-ready services, deployed with Docker, Kubernetes (EKS, AKS, OpenShift, etc.), or cloud platforms like AWS or Azure.

  • Cover real production concerns: CI/CD pipelines, logging, monitoring, observability, autoscaling.

  • Include load testing to prove concurrency works and see how the service handles heavy traffic.

  • Go beyond toy examples — I’m looking for a qualified, professional-level course that teaches modern practices for running async Python services at scale.

I’ve seen plenty of beginner tutorials on FastAPI or generic Kubernetes, but nothing that really connects async microservice development (with Uvicorn/Gunicorn workers) to the full story of production deployments in the cloud.

If you’ve taken a course similar to the one Im looking for or know a resource that matches this, please share your recommendations 🙏

Thanks in advance!


r/FastAPI • • May 17 '25

Question Using Supabase with FastAPI: Do I still need SQLAlchemy Models if tables are created directly?

32 Upvotes

Hi everyone,
I’m building an app using FastAPI and Supabase as my database. I have already created the database schema and tables directly in Supabase’s interface. Now, I’m wondering - do I still need to create SQLAlchemy models in my FastAPI app, or can I just interact with the database directly through Supabase’s API or client libraries? I am not sure whether I should only use schemas or make models.py for each table. Thanks!!


r/FastAPI • • May 09 '25

Question When and why FastAPI with MongoDB or PostgreSQL?

32 Upvotes

Which is better in terms of scalability, development, performance, and overall ease of use. Wanting to figure out what backend will be best for my mobile apps.


r/FastAPI • • Mar 23 '25

Question Building a SaaS backend with FastAPI

32 Upvotes

Does anyone now of a template, open source example, online course/tutorial, or YouTube video discussing all the steps and features needed to build a SaaS using FastAPI

Just trying to think of all the features (not including the features of the SaaS itself) is a bit overwhelming

  • Auth — social media sign-on — lost password reset — 2FA

  • Manage Profile — subscription management — payment management — history

  • Administration — reports —- sales —- users —- MAU —- cost of customer acquisition —- churn —- subscription levels

  • Help/Support (can this be outsourced) — open a case — add comment — close a case — reports

Back in my PHP days, using Laravel there was a product called Backpack that was a jump start to all of these kinds of features. So far I have not found anything similar for FastAPI


r/FastAPI • • Dec 02 '24

Question "Roadmap" Backend with FastAPI

32 Upvotes

I'm a backend developer, but I'm just starting to use FastAPI and I know that there is no miracle path or perfect road map.

But I'd like to know from you, what were your steps to become a backend developer in Python with FastAPI. Let's talk about it.

What were your difficulties, what wrong paths did you take, what tips would you give yourself at the beginning, what mindset should a backend developer have, what absolutely cannot be missed, any book recommendations?

I'm currently reading "Clean code" and "Clean Architecture", great books, I recommend them, even though they are old, I feel like they are "timeless". My next book will be "The Pragmatic Programmer: From Journeyman to Master".


r/FastAPI • • Jan 11 '26

feedback request [Release] FastKit Core: an open-source, lightweight toolkit developed for the FastAPI framework

31 Upvotes

Hey everyone!

In the last several months, we have been working on the FastKit Core package. FastKit Core is an open-source, lightweight toolkit developed for the FastAPI framework. It provides common patterns, code structure, and infrastructure solutions following modern Python and FastAPI conventions.

The main idea is improve the development experience and speed up the development proces focusing on solving common problems that we have on a daily bases on production.

FastKit Core provides:

  • Repository Pattern for database operations

  • Service Layer for business logic

  • Multi-language support - built into models and translation files

  • Validation with structured and translated error messages

  • HTTP Utilities for consistent API responses

And more.

You can find full documentation here.

We invite you to take a look at the code on GitHub. We would truly appreciate any feedback or contributions!


r/FastAPI • • Sep 04 '24

pip package Introducing fastapi-endpoints library

31 Upvotes

Hello everyone.

For the last 3 projects I have been using a file-based router that I developed a few months back at work. This is a very lightweight library that can help with the overhead of defining and importing routers in the FastAPI app.

I deployed the first version on PyPI with the goal of seeing how the projects behaves and how its used out there. I plan to improve and add more tutorials and usages to this project for the next 2 months so I say its in the works.

Documentation: https://vladned.github.io/fastapi-endpoints/
Repository: https://github.com/vladNed/fastapi-endpoints

Please let me know what you think, I am here to build stuff not to feed my ego. I would really love to see some suggestions and improvements if any. Thank you


r/FastAPI • • Feb 23 '22

Other Talked to FastAPI Creator Sebastian Ramirez and it's in becoming the third most loved framework after just 2 years of existence 🔥

Thumbnail
flagsmith.com
31 Upvotes

r/FastAPI • • Jun 21 '26

Question Transitioning from Node.js to FastAPI: Does the non-blocking mental model still apply?

30 Upvotes

Hi everyone,

I’m an experienced Node.js developer who recently picked up Python and is now diving into FastAPI.

In Node.js (and Express), my mental model revolves around a single-threaded, non-blocking, event-driven architecture.
When building APIs in Node/Express, I default to thinking in terms of the Event Loop—a single-threaded, non-blocking architecture where I/O operations are offloaded.
Can I safely carry my Node.js mental model over to FastAPI, or are there fundamental differences in how Python handles asynchronous requests under the hood that I should be aware of?

P.S. Phrasing refined by Gemini.


r/FastAPI • • Mar 01 '26

pip package LoopSentry: Detect who is blocking python asyncio eventloop

30 Upvotes

Hello Fastapi community, this is not directly specifically linked to fastapi but mostly useful for people who are using any async eco system in python.

i have built lightweight utility to detect what is blocking the python asyncio event loop.

2 years ago when i was still beginner in asyncio , i had nightmarish experience in understanding why my application suddenly pauses everything, i had to spent 3-4 nights awake to understand and monkey patch essentially via asyncio.to_thread and semaphores to get to the breathing point. it was hell. at that time i did not find any utils for this which can find me what is blocking my eventloop. and this year i got one project when that developer left and man it was same story everything is blocking in name of colored async function. so today i built this. to reduce the pain of debugging async application.

project is pretty straight forward. you get depth report of what is blocking and exactly where it is blocking , is the blocking in library you use? or in your actual code, is this logic block etc... , what was CPU , RAM and gc at that time and also allows you to capture arguments at runtime.

ps: idk if this is correct subreddit for this post , but main reason for loopsentry was i was making apis using fastapi , so thought to share here


r/FastAPI • • Feb 13 '26

Other Finally got Cursor AI to stop writing deprecated Pydantic v1 code (My strict .cursorrules config)

30 Upvotes

Hi All,

I spent the weekend tweaking a strict 

.cursorrules file for FastAPI + Pydantic v2 projects because I got tired of fixing:

  • class Config: instead of model_config = ConfigDict(...)

  • Sync DB calls inside async routes

  • Missing type hints

It forces the AI to use:

  • Python 3.11+ syntax (| types)

  • Async SQLAlchemy 2.0 patterns

  • Google-style docstrings

If anyone wants the config file, let me know in the comments and I'll DM it / post the link (it's free)."

==========================================
Here it is. Please leave feedback. Replace "[dot]" with "."

tinyurl [dot] com/cursorrules-free