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?
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.
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.
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
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.
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.
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.
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.
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
)
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.
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.
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
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)
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)
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
@uigen-dev/cli init → bootstraps your project
Let AI auto-annotate your spec (or use the visual config GUI)
Let AI generate your theme
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.
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:
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.
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.
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?