r/FastAPI • • Jul 26 '25

Question Multithreading in FastAPI?

17 Upvotes

Hello,

I am currently writing an Ollama wrapper in FastAPI. The problem is, I have no idea how to handle multithreading in FastAPI, and as such, if one process is running (e.g. generating a chat completion), no other processes can run until the first one is done. How can I implement multithreading?


r/FastAPI • • Jul 09 '25

Question How to use implement SSO on a FastAPI app?

17 Upvotes

I want to add "Log in with LinkedIn" button to my FastAPI app.

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

I've been looking into using this library. Does anybody know if it's legit and actually works?


r/FastAPI • • May 03 '25

Question How to learn FastAPI + Jinja2 + HTMX?

17 Upvotes

In my last post, many of you suggested me to go pair the backend built in FastAPI with Jinja and HTMX to build small SaaS projects, since I don't know React or any other frontend frameworks.

Now my question is, how do I learn this stack? I feel like there are very few resources online that combine this three tools in a single course/tutorial.

What would you suggest me to do?


r/FastAPI • • Feb 02 '25

Tutorial Developing a Single Page App with FastAPI and React

Thumbnail
testdriven.io
17 Upvotes

r/FastAPI • • Jan 23 '25

Question Response model performance improvements

17 Upvotes

Hi,

I recently upgrade an application based on fastapi from 0.57 to 0.115.

One of the reasons to do that was the response models validation taking most of the time of the request on the server. For a request taking 1 second, 700ms was the response model validation. Removing the response model for the router the request total time goes to 300ms.

I read that recent versions of fastapi now use pydantic v2 and this should improve the model validation however I'm not seeing a big difference on the time it takes to validade the response model.

I'm using pydantic 2.9.2 and fastapi 0.115.0.

Should I expect better processing times?

Thank you


r/FastAPI • • Jan 02 '25

Question How to handle high number of concurrent traffic?

17 Upvotes

Guys how to handle high number of concurrent requests say 2000-5000 request at a single time

I am trying to build a backend reservation system (first come first serve logic) using postgres and fastapi but I hit the max connection limit

Also there are levels in this reservation, level a can only have 100 people and so on.

Am using sqlalchemy and using nullpool and aws rds proxy, am following docs to use dependency in fastapi but I always hit max connection usage in my db. I am confused why doesn't connection gets closed as soon as request is served


r/FastAPI • • Oct 15 '23

Question best public,active fastapi projects

17 Upvotes

Im looking for some fastapi projects to study and look over. I've been building my own mostly from tutorials here and there but they don't always piece together the big picture so I figure reading through a codebase would be good practice.


r/FastAPI • • Jun 17 '23

Announcement Reddit Blackout: Should we continue to participate?

17 Upvotes

Hey y'all! We've been locked for the better part of the week after running a poll and finding that the community believed this was a worthwhile cause.

Figured this would be a good time to repoll and gauge how the community felt moving forward things should be handled. Happy to abide by whatever we decide!

Upvote one of the three comments I made below to either:

Also happy to hear other ideas on this thread in the meantime if any others exist!

EDIT: Gonna close this poll come Tuesday evening so we catch all the weekend browsers and then the weekday reddit-at-work-ers for a good chunk of time each.


r/FastAPI • • Apr 28 '23

Tutorial Cerbos + FastAPI + AWS Cognito: Do not reinvent user permissions

17 Upvotes

Cerbos is a self-hosted, open source user authorization layer for your applications.

In this tutorial, we're building a simple application which integrates Cerbos with a FastAPI server using AWS Cognito for authentication. FastAPI provides us with the `OAuth2PasswordRequestForm` middleware, which extracts the credentials from the form on the UI, and makes them available within the `form_data` object.

Dependencies

Full tutorial: https://cerbos.dev/blog/using-aws-cognito-with-cerbos-how-to
GitHub repo: https://github.com/cerbos/python-cognito-cerbos

Tutorial UI sample screenshot:


r/FastAPI • • Apr 11 '23

pip package The new release of FastKafka improves testability

17 Upvotes

We were searching for something like FastAPI for Kafka-based service we were developing, but couldn’t find anything similar. So we shamelessly made one by reusing beloved paradigms from FastAPI and we shamelessly named it FastKafka. The point was to set the expectations right - you get pretty much what you would expect: function decorators for consumers and producers with type hints specifying Pydantic classes for JSON encoding/decoding, automatic message routing to Kafka brokers and documentation generation.

https://github.com/airtai/fastkafka

The new release adds in-memory Kafka broker that can be used for testing without the need to install Java and start a broker. It allows you to write a simple-to-understand tests such as this one:

from fastkafka.testing import Tester

msg = IrisInputData(
    sepal_length=0.1,
    sepal_width=0.2,
    petal_length=0.3,
    petal_width=0.4,
)

# Start Tester app and create InMemory Kafka broker for testing
async with Tester(kafka_app) as tester:
    # Send IrisInputData message to input_data topic
    await tester.to_input_data(msg)

    # Assert that the kafka_app responded with IrisPrediction in predictions topic
    await tester.awaited_mocks.on_predictions.assert_awaited_with(
        IrisPrediction(species="setosa"), timeout=2
    )

r/FastAPI • • Jan 02 '22

feedback request URL shortener using FASTAPI

Thumbnail
github.com
17 Upvotes

r/FastAPI • • May 06 '21

Question Any open-source project that uses FastAPI?

17 Upvotes

Hey guys,

I wanted to know if there are any open-source projects that use FastAPI? I would like to try and make open-source contributions.

Thanks


r/FastAPI • • Apr 13 '21

pip package OPAL - a new open-source for access control based on FastAPI and Typer

17 Upvotes

Hello, fellow fastapi users! 💜

I'm happy to share we just shipped a huge new open-source project - OPAL.

OPAL adds real time updates to OPA (open-policy-agent) - making building access control for your products much easier. OPAL is based on fastapi (for apis), pydantic (for datatypes) and typer (for the cli).

Would love your stars 🌟 and feedback 🙏 And of course - you're more than welcome to try it.

Check out our website at opal.ac and the project on github.


r/FastAPI • • Jul 23 '26

feedback request Pydantic extra types

16 Upvotes

I have been going through my codebase this morning and asked claude Ai how I can validate the phone number field of my schema model and it has recommended the official python phonenumber library, but suprisigley I checked out the Pydantic docs and found the same library which is wrapped on a Pydantic type and does all the validations as the Python phonenumber libarary plus less code and less mantainance, you just use it as type annotation and BUM it does the underhood workd for you.
I want to read it this is the link https://pydantic.dev/docs/validation/latest/api/pydantic-extra-types/pydantic_extra_types_phone_numbers/#_top

You can even configure the accepted regions and the default region as well.


r/FastAPI • • May 20 '26

feedback request My first fullstack project using FastAPI on backend

16 Upvotes

Hi guys, I received a challenge for a junior swe position (the position was canceled for remote workers, so I'm unempolyed still) and I put a couple of hours of work into it, it's a storage system

You guys can look into it at https://github.com/edufcarvalho/filecano

Tips and ideas will be much appreciated, until the end of the week I will be adding pagination to front-end in order to make sure everything is smoother (rn it's taking a while to do some operations with over 500 files)


r/FastAPI • • May 02 '26

Other FastAPI gives you the spec. UIGen gives you the full React Frontend. Zero code. [Update]

16 Upvotes

Hey everyone - UIGen just got way easier to try (Faster AI assisted config and theming)

A few days ago I shared UIGen: a CLI tool that turns your OpenAPI spec into a full React frontend at runtime - no code generation, no build step. Update your FastAPI backend → restart the CLI → UI updates instantly. Your spec stays the source of truth.

What UIGen gives you out of the box

  • Auto CRUD views (list, detail, create, edit)

  • Full auth flows (login, signup, password reset)

  • File uploads, relationships, pagination, search

  • Data visualizations (new x-uigen-chart)

  • Production-ready React output you can extend/customize

The big new upgrade: AI-assisted setup

I added two AI skills that understand UIGen's architecture and do the heavy lifting:

1. Auto-Annotate Skill

Feeds your spec to your AI assistant (Cursor, Claude, etc.) and it automatically:

  • Detects & marks login/signup endpoints (x-uigen-login etc)

  • Finds relationships (users → posts, orders → customers)

  • Identifies file uploads

  • Spots good candidates for charts

2. Auto-Style Skill

Generates beautiful, production-ready CSS with simple prompts like:

"Make it look like Material Design" or "Dark theme with blue accents"

No manual CSS files or build processes - styles inject at runtime.

New super simple workflow

  1. @uigen-dev/cli init → bootstraps your project

  2. Let AI auto-annotate your spec (or use the visual config GUI)

  3. Let AI generate your theme

  4. Run npx @uigen-dev/cli serve yourspec.yaml and iterate

No frontend code to maintain.

Real example you can try right now

There's a full Meeting Minutes app in the repo (FastAPI + async SQLAlchemy + PostgreSQL + Alembic). ~2,000 lines of clean Python. Just clone, spin up the backend with Docker, and point UIGen at the auto-generated OpenAPI spec. Full CRUD, auth, file uploads, relationships — all working.

Current priorities for v1

  • Charting polish

  • Better layout options (without bloat)

  • App branding (name, icon, etc.)

  • Theme registry for instant beautiful starts

The goal

You focus on building a great API. UIGen + AI handles the frontend UI so you can ship faster.

Links

Happy to hear what you think


r/FastAPI • • Apr 01 '26

pip package Rate Limiting in FastAPI: What the Popular Libraries Miss

16 Upvotes

Rate limiting is how you stop a single client from hammering your API. You cap the number of requests per time window and return a 429 when they go over. Simple idea, but the implementation details matter in production.

Here is how the two most popular FastAPI rate limiting libraries work:

slowapi

from slowapi import Limiter
from slowapi.util import get_remote_address
from fastapi import Request

limiter = Limiter(key_func=get_remote_address)

@app.get("/search")
@limiter.limit("10/minute")
async def search(request: Request):
    return {"results": []}

fastapi-limiter

from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
import redis.asyncio as redis
from fastapi import Depends

@app.on_event("startup")
async def startup():
    r = await redis.from_url("redis://localhost")
    await FastAPILimiter.init(r)

@app.get("/search", dependencies=[Depends(RateLimiter(times=10, seconds=60))])
async def search():
    return {"results": []}

Both get the job done for basic IP-based limiting. But here is where they fall short:

No runtime mutation. Every limit is locked to the code. If you want to update the limit on an existing route or apply a rate limit to a route that was not decorated at deploy time, you have to change code and redeploy.

No management tooling. There is no dashboard or CLI to view current policies, add limits to unprotected routes, update existing limits, or see which requests are being blocked. Everything lives in code and the only way to inspect the state of your rate limits is to read the source.

This is what the same thing looks like in waygate:

from waygate.fastapi import rate_limit

# IP-based (default)
@router.get("/search")
@rate_limit("10/minute")
async def search():
    return {"results": []}

# Per user, with tiered limits for different plans
@router.get("/reports")
@rate_limit(
    {"free": "10/minute", "pro": "100/minute", "enterprise": "unlimited"},
    key="user",
)
async def reports(request: Request):
    return {"reports": []}

# Exempt internal IPs
@router.get("/metrics")
@rate_limit("20/minute", exempt_ips=["10.0.0.0/8", "127.0.0.1"])
async def metrics():
    return {"metrics": {}}

Change a limit at runtime without touching code:

waygate rl set GET:/search 50/minute
waygate rl reset GET:/search
waygate rl hits

The admin dashboard shows all registered policies, lets you add limits to unprotected routes, and logs every blocked request.

For multi-service architectures, waygate lets you set a rate limit policy that applies to every route of a specific service without touching individual handlers, and manages all policies across services from a single dashboard.

waygate also covers feature flags with OpenFeature support, maintenance mode, scheduled windows, percentage rollouts, webhooks, and a full audit log, all in one library with no redeploy required.

pip install "waygate[rate-limit]"

Docs: https://attakay78.github.io/waygate


r/FastAPI • • Mar 24 '26

feedback request I built a production-ready FastAPI boilerplate with auth, logging, and scalable structure — feedback welcome

16 Upvotes

I was tired of setting up the same things every time I start a FastAPI project, so I created a reusable boilerplate.

It includes:

  • JWT authentication setup

  • Structured logging

  • Modular folder architecture

  • Environment-based config

  • Ready-to-use Docker setup

The goal was to make something that’s actually usable in production, not just a basic template.

Would love feedback on:

  • Project structure

  • Anything missing for real-world use

  • Improvements for scalability

Repo: https://github.com/yashsinghviwork/fastapi-boilerplate


r/FastAPI • • Mar 19 '26

pip package I built a FastAPI middleware for Machine Payments Protocol (402 → wallet payment → signed receipt retry

16 Upvotes

Hey folks, I just released fastapi-mpp and would love feedback from the FastAPI crowd.

It lets a route require real-time machine payments with a decorator:

  • add @mpp.charge() to any route.

  • If unpaid, API returns 402 Payment Required + payment challenge

  • Client/agent pays via wallet and retries

Why I built it: API key + credit card billing doesn’t map well to autonomous agents making micro-transactions.

It’s still beta. I’m especially looking for critiques on security model and FastAPI ergonomics.

Repo:https://github.com/SylvainCostes/fastapi-mpp

PyPI: pip install fastapi-mpp


r/FastAPI • • Mar 10 '26

feedback request Self-hosted social media scheduler with FastAPI, APScheduler and Beanie - dashboard, auth, file uploads and more

Thumbnail
gallery
16 Upvotes

Hello everyone!

After seeing some tutorials on FastAPI, it was time to finally create something useful from it. Been building Post4U over the past few weeks, an open source self-hosted scheduler that cross-posts to X, Telegram and Discord from a single REST API call. Just hit a point where the project feels substantial enough to share here.

What it does: One API call with your content, a list of platforms and an optional scheduled time. It handles delivery, tracks per-platform success and failure, persists jobs across container restarts and retries only the platforms that failed.

Stack decisions worth discussing: APScheduler with a MongoDB job store instead of Celery + Redis. MongoDB was already there for post history so using it as the job store too meant zero extra infrastructure and jobs survive restarts automatically. Genuinely curious if anyone here has hit issues with APScheduler in production because that is the decision I keep second guessing.

Beanie + Motor for async MongoDB ODM. Pairs really cleanly with FastAPI's async nature and the TimestampMixin pattern for automatic createdAt on documents saved a lot of repetition.

Security: After some good feedback from the community, added API key auth on all routes via X-API-Key header, validated using secrets.compare_digest to prevent timing attacks. File uploads go through python-magic to verify actual MIME type against an AllowList rather than just trusting content_type, size limit enforced in chunks before anything hits disk.

Dashboard: Built the frontend in Reflex, pure Python, compiles down to a React + Vite bundle. You can compose and schedule posts, post directly, view history, unschedule pending posts and attach media files, all without touching curl or API docs.

What is missing: Reddit integration is pending their manual API approval process. Will try Bluesky and Mastodon integrations after that.

Would love genuine feedback, comments, suggestions to improve on the APScheduler choice specifically or anything in general about the codebase.

GitHub: https://github.com/ShadowSlayer03/Post4U-Schedule-Social-Media-Posts


r/FastAPI • • Mar 10 '26

pip package Built a tiny dependency injection library for Python with FastAPI-style Depends

16 Upvotes

I really like FastAPI’s Depends, but I wanted that same developer experience in plain Python without bringing in a whole framework.

You declare dependencies in the function signature, add one decorator, and it just works.

from typing import Annotated
from injekta import Needs, inject

def get_db() -> Database:
    return PostgresDB(...)

@inject
def create_user(db: Annotated[Database, Needs(get_db)], name: str):
    return db.create_user(name)

Would genuinely love feedback on the idea and whether this solves a real pain point or just scratches my own itch.

https://github.com/autoscrape-labs/injekta


r/FastAPI • • Dec 10 '25

Question How can I level up from basic Python API dev to building scalable, production-grade APIs in 6 months?

Thumbnail reddit.com
16 Upvotes

r/FastAPI • • Oct 19 '25

feedback request Production-ready FastAPI template with CI/CD and GHCR releases

16 Upvotes

I’ve been reusing the same FastAPI boilerplate for small services, so I turned it into a template.

CI runs tests, lint, and CodeQL on every push

Tag vX.Y.Z to build & publish a Docker image to GHCR

First run works with no secrets; Postgres and Sentry steps light up if you add them

Looking for feedback from fellow FastAPI devs.

Repo: https://github.com/ArmanShirzad/fastapi-production-template


r/FastAPI • • Oct 15 '25

Question Middleware x Router-Level Dependencies | Auth

16 Upvotes

I'm new in Python and FastAPI development and I'm working in my first API. I'm at the point where I need to implement authentication by validating a JWT token from the request header, and I'm not sure about the best approach.

I have analyzed both options, and here is my current understanding:

Using Depends: It gives me more granular control to decide which routes are protected and which are public. But it doesn't feel very robust, as I would have to rely to add the authentication dependency to every new protected endpoint.

Using Middleware: It seems like a good choice to avoid code repetition and ensure that all routes are protected by default. The disadvantage is that I would have to explicitly maintain a list of public routes that the middleware should ignore.

I was a little confused about which approach to use and what the real advantages and disadvantages of each would be.

What is the generally recommended approach or best practice for handling JWT authentication in a FastAPI application? Are there other possibilities I am missing?