r/FastAPI • • Mar 30 '26

pip package fastapi-watch — health checks, metrics, and a live dashboard for FastAPI in one registry call

19 Upvotes

FastAPI doesn't ship with any real observability. I've rebuilt some version of this on every FastAPI repo I've worked on. Eventually I got tired of repeating myself and made it a proper library. It started as my own use, but I have been expanding it ever since.

registry = HealthRegistry(app)
registry.add(PostgreSQLProbe(url="postgresql://..."))
registry.add(RedisProbe(url="redis://..."), critical=False)

That gives you /health/live, /health/ready, /health/status, /health/metrics (Prometheus), and a live dashboard at /health/dashboard.

A few things that make it different:

  • Probes run concurrently — so if Redis takes 5 seconds, your Postgres check isn't waiting on it

  • Many probes are passive observers (@probe.watch) — they instrument your existing functions instead of making synthetic test requests

  • Three health states: healthy, degraded, unhealthy — degraded keeps /ready at 200 but surfaces in the dashboard and Prometheus

  • Built-in Slack, Teams, and PagerDuty alerts on state changes

  • Circuit breaker, probe history, SSE streaming, Kubernetes-ready

GitHub: https://github.com/rgreen1207/fastapi-watch

pip install fastapi-watch


r/FastAPI • • Dec 09 '25

Tutorial FastAPI Lifespan Events: The Right Way to Handle Startup & Shutdown

Thumbnail
youtube.com
19 Upvotes

In this video, we dive deep into FastAPI lifespan events - the proper way to manage startup and shutdown logic in your FastAPI applications. We cover everything from basic concepts to advanced production patterns, including database connections and shutdowns.


r/FastAPI • • Oct 09 '25

Question Help me figure out transactions in FastAPI - where should I commit?

19 Upvotes

So I'm building this FastAPI app with SQLAlchemy (async), PostgreSQL, and asyncpg, and I've run into a head-scratching problem with database transactions. Would love some advice from folks who've dealt with this before.

Here's the deal:

My setup:

I've got a pretty standard layered architecture:

Database layer - handles connections, has a get_session() dependency CRUD layer - basic database operations (create, get, update, etc)

Service layer - where my business logic lives

API layer - FastAPI routes

The problem:

Right now my CRUD methods commit immediately after each operation. This seemed fine at first, but here's where it breaks:

async def register_user(session, user_data):
    # Creates user and commits immediately
    user = await user_crud.create(session, user_data)
    
    # If this fails, user is already in the database!
    await sms_service.send_verification_code(user.phone)
    
    return user

Not great, right? I want it to be all-or-nothing.

What I'm thinking:

Idea 1: Let the dependency handle it

Remove all commits from CRUD, and have get_session() commit at the end of each request:

# database.py
async def get_session():
    async with async_session_factory() as session:
        try:
            yield session
            # Only commit if something changed
            if session.dirty or session.new or session.deleted:
                await session.commit()
        except Exception:
            await session.rollback()
            raise

# crud.py - just flush, don't commit
async def create_user(self, db, data):
    user = User(**data)
    db.add(user)
    await db.flush()  # gets the ID but doesn't commit yet
    return user

# Now the whole operation is atomic!
async def register_user(session, data):
    user = await user_crud.create(session, data)
    await sms_service.send_code(user.phone)  # if this fails, user creation rolls back
    return user

This feels clean because the entire request is one transaction. But I lose fine-grained control.

Idea 2: Handle it in the service layer

Don't auto-commit anywhere, make the service layer explicitly commit:

# database.py - no auto commit
async def get_session():
    async with async_session_factory() as session:
        try:
            yield session
        except:
            await session.rollback()
            raise

# service.py - I control when to commit
async def register_user(session, data):
    try:
        user = await user_crud.create(session, data)
        await sms_service.send_code(user.phone)
        await session.commit()  # explicit commit
        return user
    except Exception:
        await session.rollback()
        raise

More control, but now I have to remember to commit in every service method. Feels error-prone.

Idea 3: Mix both approaches

Use auto-commit by default, but manually commit when I need finer control:

# Most of the time - just let dependency commit
async def simple_operation(session, data):
    user = await user_crud.create(session, data)
    return user  # auto-commits at end

# When I need control - commit early
async def complex_operation(session, data):
    user = await user_crud.create(session, data)
    await session.commit()  # commit now
    
    # This can fail independently
    try:
        await send_welcome_email(user)
    except:
        pass  # user is already saved, that's fine
    
    return user

Best of both worlds maybe?

Questions for you all:

  1. Which approach do you use in production? What works best?

  2. Is checking session.dirty/new/deleted before committing a good idea for read-only requests?

  3. Any gotchas I should know about with dependency-level commits?

  4. What about batch operations where I want to save what I can and skip failures?

My stack:

  • FastAPI

  • SQLAlchemy 2.0 (async)

  • PostgreSQL

  • asyncpg driver

  • Following repository/service pattern

Thanks for any insights! Been going in circles on this one.


r/FastAPI • • Sep 26 '25

Question Most commom folder structure

Post image
19 Upvotes

I'm a front-end dev learning Fastapi, can u guys show me a good folder structure?

I'm using fastapi standard install + sqlalchemy + psycopg + postgres

I have this inside my main folder, i think i need to create a service folder to do the db stuff right?


r/FastAPI • • Jun 11 '25

Question Using dependency injector framework in FastAPI

19 Upvotes

Hi everyone, I'm pretty new to FastAPI, and I need to get started with a slightly complex project involving integration with a lot of AWS services including DynamoDB, S3, Batch, etc. I'm planning to use the dependency-injector framework for handling all of the dependencies using containers. I was going through the documentation examples, and it says we have to manually wire different service classes inside the container, and use inject, Provider, and Depends on every single endpoint. I'm afraid this will make the codebase a bit too verbose. Is there a better way to handle dependencies using the dependency injector framework in FastAPI ?


r/FastAPI • • Mar 31 '25

Question What's your thoughts on fastapi-users?

19 Upvotes

r/FastAPI • • Jan 21 '25

Other Create a performant Python API using FastAPI and SqlModel and deployment to Kubernetes

Thumbnail
youtu.be
19 Upvotes

r/FastAPI • • Nov 30 '24

Question Domain Driven Design in Python

19 Upvotes

Hi,

I'm recently building a hobby project backend which uses domain driven design and clean/hexagonal architecture. I'm pretty new to domain driven design, so I'm reading about it and trying to implement it. I'm using google and perplexity to get understand the concepts, clear my doubts and get different perspectives when trying to make a choice between multiple implementations. Now, I'm looking for an open-source project that makes heavy use of DDD implementing things like event sourcing, etc. so I can get a better understanding of the implementation. Does anyone know any good github repos which implements Domain driven design which I can use as reference?


r/FastAPI • • Oct 28 '24

Hosting and deployment What's a cheap way to deploy a fastapi app for computer vision?

19 Upvotes

I hage completed my first project, hosting my react frontend on netlify, but i need a place to host my fastapi.

It can get pretty cpu intensive, as I'm using yoloV11 and template matching to perform computer vision tasks on a user submitted image, peocessing it and generating a solution with beam search (it's a slider puzzle solver website).

As I'm still a student, i am hoping to be able to deploy it at a cheaper price, how should i go about it?


r/FastAPI • • Oct 18 '24

Hosting and deployment which tech-stack to use?

19 Upvotes

So I have gotten a project where I have to make a web-based inventory management system for a small manufacturing company, I’m putting it in a simple way but the project will be on the lines of Inventory Management. Some of the features will be - users should be able to generate reports, they should have an invoicing system, they can check the inventory etc., basically an ERP system but a very simpler and toned-down version, tailored to the client’s needs. Should I go ahead with flask for the backend and js for front-end, or go with a modern approach with FastAPI and React. Again emphasising on the fact that the website does not have to be fancy, but it should do the job.


r/FastAPI • • Sep 08 '24

feedback request I built a Django shell_plus equivalent for fastAPI

19 Upvotes

Hi,

I just wanted to share some code snippet that could help others. In Django, I was relying a lot on shell_plus command, a context-aware shell to interact with your application. Basically, it loads a IPython Shell and auto-imports FastAPI and Python built-in tools, but more importantly, it detects your models using introspection, and import them too. Curious to have your feedback about this.

It looks like this:

The code is on a Github Gist here.


r/FastAPI • • Apr 02 '24

Question Request for sample fastAPI projects github repos

19 Upvotes

Hi everyone

I am new to fastAPI & python, coming from the frontend side of the world and nodejs. I was hoping this community could link me through their past/present fastAPI projects where there is a proper db connection, directory structure etc. The basic stuff. I am tired of googling for blogs and not getting what I want.

Until now, I haven't been able to figure out any common pattern on directory structure, or connection using MySQL, Postgres etc. Some things I am importing from sqlmodel and some from sqlalchemy..

Idk... i am super confused and idk what I am talking about. I just need some good project links from where I can learn and not some blogs that university students wrote (sorry not trying to insult anyone, it's my frustration) Thanks ^^


r/FastAPI • • Jun 09 '23

Announcement Looking for moderators

19 Upvotes

I plan to quite reddit. Their communication with Apollo was unacceptable. Reddit is an evil corp. I will not waste my time moderating any subreddit.

https://www.reddit.com/r/apolloapp/comments/144f6xm/apollo_will_close_down_on_june_30th_reddits/

If you want to become a mod, post a comment here (not a dm).

EDIT: I arbitrarily selected a few from the comments section. Closing now.


r/FastAPI • • Feb 15 '23

Other FastAPI SaaS Template

19 Upvotes

Over the past few weeks, I have explored various ideas in the SAAS domain which is centred around collaborating on any case, which led me to always start a FastAPI project/application from scratch. Although it allowed me to perform the task of repetition which is the father of learning, I realized that I could build a template that I can reuse whenever I had an idea.

This led me to devote the whole of my day (5th of February 2023) to the development of this project.

What does this template include:

  1. Authentication (With email verification (Ships with a template):
    Login, Register, Change Password, Forget Password, Update User, Delete User.

  2. Collaboration (In the case of this template I called it Orgs): This is a group of people with basic roles such as Admin and Members.

  3. Based on point 2 above I worked on Permissions and Role-based control.

To give the tea away I recalled Pipes in NestJs and I created some logic functions thanks to Depends (Dependency Injection) provided in FastAPI. I mounted those logic blocks as route middleware, carried out before the request starts performing route-defined logic.

A unique example is, I restricted the generation of Orgs for Freemium users to Two.

What is outstanding in this template?
Tests. I am actively working on them they will be available shortly. I will also like to collaborate on the Testing as I hope to get better at writing tests.

This Template ships with permissions, a customizable template, celery job initialized. I am leaving you to do the heavy lifting of core business logic.

I wanted to share this hoping it helps you if you ever need to build a SaaS product with FastAPI.

https://github.com/philipokiokio/FastAPI_SAAS_Template


r/FastAPI • • Feb 06 '23

Other Bootstrap your FastAPI projects with Rob's Awesome Python Template

Thumbnail
blog.tedivm.com
19 Upvotes

r/FastAPI • • Aug 09 '22

pip package Starception - beautiful exception page for Starlette and FastAPI inspired by Phoenix Framework

19 Upvotes

Hi folks! I'd like to share my new library with you. This is a custom exception page for Starlette and FastAPI.

It is very simple to use and very informational. Hope you like it!

Docs and examples: https://github.com/alex-oleshkevich/starception


r/FastAPI • • Oct 13 '21

Tutorial Building a realtime ticket booking solution with Kafka, FastAPI, and Ably

Thumbnail
ably.com
19 Upvotes

r/FastAPI • • Jan 11 '21

Tutorial Implementing FastAPI Services – Abstraction and Separation of Concerns

Thumbnail
camillovisini.com
19 Upvotes

r/FastAPI • • Mar 19 '26

feedback request Made a simple uptime monitoring system using FastAPI + Celery

18 Upvotes

Hey everyone,

I’ve been trying to understand how tools like UptimeRobot or Pingdom actually work internally, so I built a small monitoring system as a learning project.

The idea is simple:

  • users add endpoints

  • background workers keep polling them at intervals

  • failures (timeouts / 4xx / 5xx) trigger alerts

  • UI shows uptime + latency

Current approach:

  • FastAPI backend

  • PostgreSQL

  • Celery + Redis for polling

  • separate service for notifications

Flow is basically:
workers keep checking endpoints → detect failures → send alerts → update dashboard

Where I’m confused / need feedback:

  • Is polling via Celery a good approach long-term?

  • How do these systems scale when there are thousands of endpoints?

  • Would an event-driven model make more sense here?

  • Any obvious architectural mistakes?

I can share the repo if anyone wants to take a deeper look.

Would really appreciate insights from people who’ve built similar systems 🙂


r/FastAPI • • Mar 17 '26

Other Multi-tenant FastAPI - features, workflows and more, configurable per customer!

18 Upvotes

Folks, ever wondered:

  • How to disable a feature for one customer but enable it for another?

  • Give limited access to one, unlimited to another?

  • Make your API behave completely differently per customer?

That's basically multi-tenant SaaS for you, where you configure features, workflows, etc at the tenant (customer) level.

I have noticed most FastAPI tutorials don't touch this, and many struggle to find the right structure/architecture.

It might sound complex, but the core idea is very simple - your app should know which customer(tenant) is calling and behave accordingly. (Usually achieved by Tenant-Id and configuration at tenant level)

I have been building production-grade multi-tenant services like these and have a rough template that I rely on every time to spin these up!

So I thought if you guys are interested, I can polish it up and share it here. Let me know!

Edit: Here the customer in this context means a business/org (B2B) and not a single user.


r/FastAPI • • Jan 30 '26

pip package Built a Zitadel auth library for FastAPI to protect our endpoints with OAuth2/OIDC

18 Upvotes

I wanted to share a library we've been using to secure our endpoints in our SaaS startup: fastapi-zitadel-auth

For those unfamiliar, Zitadel is an open source identity management solution built with Go and NextJS. Think open source like KeyCloak and "easy" like Auth0 with multi-tenancy (disclaimer: not affiliated with Zitadel at all), enterprise-ready which was important to us as clients need to integrate their own IdP (e.g. Entra and what not).

When we started we did not find a suitable library so we built our own. It handles JWT validation via JWKS (Zitadel implements Introspection Calls as a default but this would slow down our Fast API). There's built-in Swagger UI support too, and RBAC.

Basic usage is simple:

from fastapi_zitadel_auth import ZitadelAuth

auth = ZitadelAuth(
    issuer_url="https://your-instance.zitadel.cloud",
    project_id="...",
    app_client_id="..."
)

then use this dependency in the routes.

source code: https://github.com/cleanenergyexchange/fastapi-zitadel-auth (which links to the more complete documentation).

Let me know what you think.


r/FastAPI • • Dec 31 '25

Other Need contributors for an open source cybersecurity GitHUb Repository (100+ stars)

Thumbnail
github.com
18 Upvotes

Made a repo with 60 cybersecurity projects mapped out from beginner to advanced. I've full built 5 of them with source code so far, the other 55 have detailed writeups but need more help to code the rest of them and eventually have 100+ projects fully built for people to learn from - clone - build upon, etc.

The point of the repo is basically to give people actual things to build instead of asking "what should i make" and getting the same mass advice. All the projects have instructions and context so you can just pick one and go. (dont have to use the instructions, I'm super open to whatever tech stack you want to use or how to go about it)

Some few examples of whats in there:

- Port scanner

- SIEM dashboard

- Security News Scraper

- Malware analysis sandbox

- Binary Analysis Tool

- Reverse shell handler

- Docker Security Audit

- Blockchain Smart Contract Auditor

If you contribute you get your name on a repo thats already at 100+ stars and growing after just one month and just 5/60 projects built (now imagine what it could become!). Good portfolio stuff and you'd be getting in early before this thing gets way bigger.

Process is easy. Fork it, pick a project that looks interesting, build it out, submit a PR and I review everything.

(Feel free to read the CONTRIBUTING.md)

Lmk if you have questions or if theres a specific project you wanna know more about


r/FastAPI • • Nov 13 '25

feedback request Opensource FastAPI B2B SaaS Boilerplate

18 Upvotes

Hi Folks -

I recently created an opensource FastAPI Boilerplate code for anyone trying to build a B2B SaaS application with the following features :

- Multi tenancy

- RBAC

- Supabase Auth integration with API endpoints protected with JWT tokens.

- Postgres integration with RLS

- API keys for system integration

- Billing integration (Stripe/Dodopayments)

and few other nice to have features .

Please try it out and let me know if there are any best practices I can use.

https://github.com/algocattech/fastapi-backend-template


r/FastAPI • • Sep 23 '25

Question Is the official template secure?

18 Upvotes

Hi

I'm going over the official template to learn FastAPI and how to implement auth. Reading the code, it seems that the app generates an JWT with expiration of 8 days.

To my understanding, if bad actor steals credentials from one of the users, even if the user catchs it and resets the password, the bad actor will still have 8 days of full access to the data.

Is my understanding correct? If so, it feels to me that even changing the token expiry from 8 days to 30 min will not be good enough.

Is there another example of secure auth that can invalidate the token?

Alternatively, is fastapi-users ready to be used in prod? My concern is that latest commit was 8 months ago, so I'm hesitant to use it