r/FastAPI • • Jan 24 '26

Tutorial Understanding concurrency on FastAPI

36 Upvotes

While starting with FastAPI, I had a lot of trouble getting to understand how concurrency works. I heard of defining async methods but never understand its underlying implications. So I tried to write an article on my understanding and how I used Locust to visualise the concurrency. I would love to hear your feedback on it.

https://medium.com/@bhaveshparvatkar/understanding-concurrency-in-fastapi-fbbe09dc4979


r/FastAPI • • Dec 27 '25

Question Do I need FASTAPI?

36 Upvotes

I’m an experienced django developer, I have worked mostly on small scale backends for iot APIs, and also mobile development, I have recently starting to see more contents on fastapi and I have been wondering, do I need it? Is it worth it to learn fastapi?


r/FastAPI • • Dec 22 '25

pip package FastAPI full-stack template v0.1.6 – multi-LLM providers, powerful new CLI options, and production presets

36 Upvotes

Hey r/FastAPI,

For anyone new: This is a CLI-based generator (pip install fastapi-fullstack) that creates complete, production-ready FastAPI projects with optional Next.js frontend – perfect for AI/LLM apps with zero boilerplate.

Repo: https://github.com/vstorm-co/full-stack-fastapi-nextjs-llm-template

Everything you get:

  • Modern FastAPI with Pydantic v2, async everything, layered architecture (routes → services → repositories)

  • Auth (JWT + refresh, API keys, Google OAuth), databases (PostgreSQL/MongoDB/SQLite), background tasks

  • AI agents (PydanticAI or LangChain) with streaming WebSockets

  • 20+ integrations: Redis, rate limiting, admin panel, Sentry, Prometheus, Docker/K8s

  • Django-style project CLI with auto-discovered commands

New in v0.1.6:

  • Multi-LLM providers: OpenAI, Anthropic, OpenRouter (PydanticAI)

  • New --llm-provider flag + interactive prompt

  • Rich CLI options: --redis, --rate-limiting, --admin-panel, --task-queue, --kubernetes, --sentry, etc.

  • Presets: --preset production and --preset ai-agent

  • make create-admin command

  • Better feature validation and post-generation cleanup

  • Fixes: WebSocket cookie auth, paginated conversations, Docker env paths

FastAPI devs – how does this compare to your usual setups? Any features missing? Contributions encouraged! 🚀


r/FastAPI • • Dec 07 '25

Other How to build a WhatsApp AI Chatbot with FastAPI [Open Source Starter Kit]

36 Upvotes

After building several WhatsApp bots for clients, I noticed I kept rewriting the same boilerplate: webhook verification, message parsing, conversation state management, etc.

So I extracted the common patterns into an open-source starter kit.

What it handles:

  • WhatsApp Cloud API webhook setup

  • Message routing and parsing (using Pydantic schemas)

  • Async AI responses (OpenAI integration)

  • Conversation context tracking (SQLModel)

  • Background task processing

  • Docker deployment config

Why FastAPI was the right choice:

  • Native async support (critical for AI API calls)

  • Pydantic validation for WhatsApp payloads

  • Auto-generated API docs

  • Modern Python type hints throughout

Repo: https://github.com/gendonholaholo/Python-starter-kit-FastAPI-WhatsApp-AI-Chatbot

For anyone building WhatsApp integrations, this should save you 3-4 days of setup. Open to suggestions on what else to include!


r/FastAPI • • Jun 21 '25

feedback request Opinion Needed!!

Post image
36 Upvotes

Is anyone here familiar with this book? It was just released this year. I was thinking to buy so any feedback is appreciated.


r/FastAPI • • Apr 27 '25

Question Fastapi observability

36 Upvotes

Hi guys, Fairly new to Fastapi and backend ecosystems. What are the tools you use to monitor and observe the behaviour of you backend?

So my current stack is prometheus+grafana but would like to explore more tools like adding loki to have traces. I would like to see how much each function execution takes time/resources.

How do you monitor your db peformance?(using timescale\postgres)

Any feedback is helpful! Happy coding!


r/FastAPI • • Jan 24 '25

Question Fastapi best projects

36 Upvotes

what projects can you recommend as the best example of writing code on fastapi?


r/FastAPI • • Oct 19 '23

Announcement The FastAPI reference docs

Thumbnail
fastapi.tiangolo.com
36 Upvotes

Just released, a lot of work behind, the FastAPI reference docs. 🎉


r/FastAPI • • Jul 22 '26

Question Where to learn FastAPI?

35 Upvotes

I have a good Python experience. I did basic backend dev with PHP and Flask before, so the beginner concepts won't be that much challenging. What I'm looking for is a single well-organized course to learn FastAPI deeply. I've checked out the official documentation, which is absolutely great and lovely, and I will use that as a reference.

It doesn't matter if the course is certified or not. I focus on the skills I'll gain. It's more preferred to be a free course though (but don't hesitate to share paid courses too if they are really worth paying for).


r/FastAPI • • Jan 31 '26

Other Small complexity comparison Django vs. FastAPI

Thumbnail
gallery
35 Upvotes

Explanation

This visualizations work by assigning every file a dot.

  • Green = Low Complexity

  • Red = High Complexity

Complexity is defined as Cyclomatic complexity (McCabe).

The first image is Fast APIs dependency graph.

Very structured and modularized. Very few Complex files and lower rates of connection between files. Most of the files are tests and tutorials.

The second image shows Djangos graph:

Much more interconnected and less modularized. More high complexity files but again most of the codebase is related to testing.

Hope you found the comparison as interesting as I did!


r/FastAPI • • Oct 02 '25

feedback request A FastApi-style framework for Cpp

35 Upvotes

Hello everyone, I am trying to make something similar to fastapi for c++

Repo:- https://github.com/YashArote/fastapi-cpp

So far I’ve implemented:

  • FastAPI-style route definitions with APP_GET / APP_POST macros

  • Automatic parsing of path params and JSON bodies into native C++ types or models

  • Validation layer using nlohmann::json (pydantic like)

  • Support for standard HTTP methods

Due to lack of reflection in cpp, working on few parts was somewhat challenging to me as a beginner. It’s still early-stage and experimental, but I’d love guidance, feedback, and contributions from the community.


r/FastAPI • • Jun 06 '25

pip package CRUDAdmin - Modern and light admin interface for FastAPI built with FastCRUD and HTMX

35 Upvotes

Hey, guys, for anyone who might benefit (or would like to contribute)

Github: https://github.com/benavlabs/crudadmin
Docs: https://benavlabs.github.io/crudadmin/

CRUDAdmin is an admin interface generator for FastAPI applications, offering secure authentication, comprehensive event tracking, and essential monitoring features.

Built with FastCRUD and HTMX, it's lightweight (85% smaller than SQLAdmin and 90% smaller than Starlette Admin) and helps you create admin panels with minimal configuration (using sensible defaults), but is also customizable.

Some relevant features:

  • Multi-Backend Session Management: Memory, Redis, Memcached, Database, and Hybrid backends

  • Built-in Security: CSRF protection, rate limiting, IP restrictions, HTTPS enforcement, and secure cookies

  • Event Tracking & Audit Logs: Comprehensive audit trails for all admin actions with user attribution

  • Advanced Filtering: Type-aware field filtering, search, and pagination with bulk operations

There are tons of improvements on the way, and tons of opportunities to help. If you want to contribute, feel free!

https://github.com/benavlabs/crudadmin


r/FastAPI • • Apr 25 '25

pip package Signal-based State Management in Python: How I Brought Angular's Best Feature to Backend Code

35 Upvotes

Hey Pythonistas,

I wanted to share a library I've been working on called reaktiv that brings reactive programming to Python with first-class async support. I've noticed there's a misconception that reactive programming is only useful for UI development, but it's actually incredibly powerful for backend systems too.

What is reaktiv?

Reaktiv is a lightweight, zero-dependency library that brings a reactive programming model to Python, inspired by Angular's signals. It provides three core primitives:

  • Signals: Store values that notify dependents when changed

  • Computed Signals: Derive values that automatically update when dependencies change

  • Effects: Execute side effects when signals or computed values change

This isn't just another pub/sub library

A common misconception is that reactive libraries are just fancy pub/sub systems. Here's why reaktiv is fundamentally different:

Pub/Sub SystemsReaktiv
Message delivery between componentsAutomatic state dependency tracking
Point-to-point or broadcast messagingFine-grained computation graphs
Manual subscription managementAutomatic dependency detection
Focus on message transportFocus on state derivation
Stateless by designIntentional state management

"But my backend is stateless!"

Even in "stateless" services, ephemeral state exists during request handling:

  • Configuration management

  • Request context propagation

  • In-memory caching

  • Rate limiting and circuit breaking

  • Feature flag evaluation

  • Connection pooling

  • Metrics collection

Real backend use cases I've implemented with reaktiv

1. Intelligent Cache Management

Derived caches that automatically invalidate when source data changes - no more manual cache invalidation logic scattered throughout your codebase.

2. Adaptive Rate Limiting & Circuit Breaking

Dynamic rate limits that adjust based on observed traffic patterns with circuit breakers that automatically open/close based on error rates.

3. Multi-Layer Configuration Management

Configuration from multiple sources (global, service, instance) that automatically merges with the correct precedence throughout your application.

4. Real-Time System Monitoring

A system where metrics flow in, derived health indicators automatically update, and alerting happens without any explicit wiring.

Benefits for backend development

  1. Eliminates manual dependency tracking: No more forgotten update logic when state changes

  2. Prevents state synchronization bugs: Updates happen automatically and consistently

  3. Improves performance: Only affected computations are recalculated

  4. Reduces cognitive load: Declare relationships once, not throughout your codebase

  5. Simplifies testing: Clean separation of state, derivation, and effects

How Dependency Tracking Works

One of reaktiv's most powerful features is automatic dependency tracking. Here's how it works:

1. Automatic Detection: When you access a signal within a computed value or effect, reaktiv automatically registers it as a dependency—no manual subscription needed.

2. Fine-grained Dependency Graph: Reaktiv builds a precise dependency graph during execution, tracking exactly which computations depend on which signals.

# These dependencies are automatically tracked:
total = computed(lambda: price() * (1 + tax_rate()))

3. Surgical Updates: When a signal changes, only the affected parts of your computation graph are recalculated—not everything.

4. Dynamic Dependencies: The dependency graph updates automatically if your data access patterns change based on conditions:

def get_visible_items():
    items = all_items()
    if show_archived():
        return items  # Only depends on all_items
    else:
        return [i for i in items if not i.archived]  # Depends on both signals

5. Batching and Scheduling: Updates can be batched to prevent cascading recalculations, and effects run on the next event loop tick for better performance.

This automatic tracking means you define your data relationships once, declaratively, instead of manually wiring up change handlers throughout your codebase.

Example: Health Monitoring System

from reaktiv import signal, computed, effect

# Core state signals
server_metrics = signal({})  # server_id -> {cpu, memory, disk, last_seen}
alert_thresholds = signal({"cpu": 80, "memory": 90, "disk": 95})
maintenance_mode = signal({})  # server_id -> bool

# Derived state automatically updates when dependencies change
health_status = computed(lambda: {
    server_id: (
        "maintenance" if maintenance_mode().get(server_id, False) else
        "offline" if time.time() - metrics["last_seen"] > 60 else
        "alert" if (
            metrics["cpu"] > alert_thresholds()["cpu"] or
            metrics["memory"] > alert_thresholds()["memory"] or
            metrics["disk"] > alert_thresholds()["disk"]
        ) else 
        "healthy"
    )
    for server_id, metrics in server_metrics().items()
})

# Effect triggers when health status changes
dashboard_effect = effect(lambda: 
    print(f"ALERT: {[s for s, status in health_status().items() if status == 'alert']}")
)

The beauty here is that when any metric comes in, thresholds change, or servers go into maintenance mode, everything updates automatically without manual orchestration.

Should you try it?

If you've ever:

  • Written manual logic to keep derived state in sync

  • Found bugs because a calculation wasn't triggered when source data changed

  • Built complex observer patterns or event systems

  • Struggled with keeping caches fresh

Then reaktiv might make your backend code simpler, more maintainable, and less buggy.

Let me know what you think! Does anyone else use reactive patterns in backend code?

Check it out on GitHub | PyPI


r/FastAPI • • Jan 29 '25

Tutorial Tutorial: FastAPI + Socket + Redis

35 Upvotes

Which are the best public repos to use as a guide to implement websockets using FastAPI and Redis.

So far I tried this one link

Thanks in advance.


r/FastAPI • • Feb 12 '26

pip package I added a Dark / Light mode toggle to FastAPI Swagger UI

34 Upvotes

Hey folks

I’ve been using FastAPI for ~5 years now and I probably spend an unhealthy amount of time staring at Swagger every single day.

I actually like the default theme. It’s clean and familiar. But after a few hours… especially at night… it starts feeling like I’m getting flashbanged by my own API docs :D

So I thought, instead of replacing Swagger with a completely different theme, why not just add a proper Dark / Light toggle?

I’ve seen dark-mode versions before ( u/BlueFriends and u/Fit_Tell_8592 did some cool stuff), but I wanted something that keeps the original Swagger vibe and just enhances it a bit.

My goal was to:

• Keep the original Swagger feel
• Add a smooth Dark / Light toggle
• Not break FastAPI defaults
• Implement smth that is easy to plug into existing projects(actually 1 line)

You can enable it with literally one line of code. Your eyesight is worth more than 1 line of code :D

So I built this:

Repo:

https://github.com/akutayural/fastapi-swagger-ui-theme

Pypi:

https://pypi.org/project/fastapi-swagger-ui-theme/

Contributions, ideas, improvements, or even nitpicks are very welcome.


r/FastAPI • • Jan 27 '26

Other Fast APIs Internal Architecture

Thumbnail
gallery
34 Upvotes

Explanation of the visuals:

First Image:

You can see a visual of the official GitHub repo of Fast API.

Each of these dots is a Python file.

The red ones are the most complex whilst green means low complexity.

Each line represents a connection between the files (usually an import).

Second image:

Shows the AST of one of the main testing files

Complexity again highlighted in red.

The graph at the very bottom is the complexity index per line of code.

The very visual spike of complexity toward the end of the file is caused by test_openapi_schema(): which contains a huge dictionary.

Other Images:

Different impressions throughout the codebase.

How is complexity Measured:

Cyclomatic complexity (McCabe) is being used to assign each file/section a complexity score between 0 and infinity. This score represents the number linearly independent paths in a program. TLDR: Big number = more complex because more possible paths

Personal thoughts:

This medium level of complexity is interesting because it highlights that FastAPI is focused on a lightweight approach (as opposed to battery included frameworks like Django).

There are very few truly complex files. The hardest part about understanding this codebase is its sheer size which is almost inevitable for a framework like this.

Most of the files are either helpers or intended for tests... this means the actual code you will be running on a day to day Fast ApI project is much more compact than the 100s of files you see here.

Kudos to all maintainers!


r/FastAPI • • Nov 26 '25

feedback request To much handy work ? i switched from django to fast api

34 Upvotes

Hi, I was working on a project with Django, but then I thought of switching to FastAPI because I want a real-time app along with GraphQL.

Man, I’m frustrated there’s too much manual work. Every file I need to create myself, and keeping track of all these layers is exhausting.

I’m using Pydantic for the database with Strawberry for GraphQL, and I have separate layers for DTOs, services, CRUD, REST APIs, and GraphQL.

Am I doing something wrong, or what is the best approach? I can’t seem to find a way to generate simple CRUD operations automatically like in Django.

Edit:
so hello guys again after last night and after i saw many of your comments i felt like i was a damn little girl who is crying over why unicorn do not exist so i took my shit together and i m doing it the hard way the right way and i m happy and i m moving forward in very good way thank you


r/FastAPI • • Oct 21 '25

feedback request FastApi style Framework for C++

34 Upvotes

Hey folks! I’m reintroducing fastapi-cpp, my experimental C++ framework inspired by FastAPI.

So far I have implemented:-

  • FastAPI-style route definitions (APP_GET / APP_POST)

  • Automatic parsing of path params and JSON bodies into native C++ types or models

  • Validation layer using nlohmann::json (pydantic like)

  • Support for standard HTTP methods

The framework was header only, we have changed it to a modular library that can easily build and integrate using Cmake. I'd love feedback and contributions improving the architecture and extending it further to integrate with databases.


r/FastAPI • • Sep 25 '25

Question Django dev here - need to learn FastAPI in 3 weeks for work. What's the fastest path?

34 Upvotes

Hey everyone,

So my company is starting a new microservice and they've decided on FastAPI (something about better performance and async support). I've been doing Django for the past few years and pretty comfortable with it, but now I need to get up to speed with FastAPI FAST - like I need to start building actual production stuff in 3-4 weeks.

I'm not starting from zero - I know Python well, understand REST APIs, have worked with DRF, know my way around databases (MYSQL mainly), and I get the general web dev concepts. But FastAPI seems quite different from Django's "batteries included" approach.

For those who've made this jump:

  • What are the biggest differences I should watch out for?

  • Any good resources that specifically help Django devs transition? Most tutorials I'm finding assume you're new to everything

  • What's the FastAPI equivalent of Django's ORM? I see people mentioning SQLAlchemy but also Tortoise-ORM?

  • How do you handle stuff like auth, migrations, admin panel that Django just gives you?

  • Should I bother learning Pydantic separately first or just pick it up as I go?

Also worried about the "blank canvas" problem - Django tells you where to put things, but FastAPI seems more like "do whatever you want" which is kinda overwhelming when you're on a deadline.

My plan so far is to rebuild one of our smaller Django services in FastAPI this weekend as practice. Good idea or should I just follow tutorials first?

Would really appreciate any tips, especially from people who use both frameworks. Thanks!


r/FastAPI • • Mar 27 '25

Question What's the difference between celery and a cron job?

34 Upvotes

I have a fastapi application running with 2 workers behind Nginx. The fastapi does a lot of processing. It's an internal tool for my company used by a maximum of 30 employees, lets not complicate the architecture, I like simplicity in everything in life, from food to code to all of it.

The current flow, the user uploads a file, it gets stored in SQLite, and then processed by cronjob and then I send an email back to the user when done. Some users don't want to wait in the queue there are many files to be processed, so I do the file processing in an asyncio background thread and send the results back in real time via websockets to the user.

That's all done, it's working, no issues. There's slight performance degradation at times, when the user is using the real time websockets flow and I'm not sure if this can be solved by upgrading the server or the background threads and whatnot.

I keep seeing people recommending celery for any application that has a lot of processing and I just want to know what would I gain from using celery? I'm not going to get rid of the cronjob anyway, because I don't care about the performance of the cronjob flow.

What I care about is the performance of the WebSocket flow because that's real time, can celery be used to replace background threads and would one be able to use it to send real-time websockets? Or is it just a fancier cronjob?

I keep avoiding celery because it comes with a lot of baggage, one can't simply install celery and call it a day, one has to install celery, and then install reddis, and dockerize everything and make sure that all docker containers are working and then install flowers to make sure that celery is working and then create a policy to be in place if a container goes down. I like simple things in life, I started programming 20 years ago, when code simplicity was all that mattered.


r/FastAPI • • Feb 19 '25

Other A SuperCharged FastAPI based framework for AI Development. Looking for collaborators

Thumbnail
github.com
34 Upvotes

Love fastapi and it’s pretty de-facto for building microservices in the AI space (agents, rag, backends)

But after building dozens of AI microservice and re-doing the routes every single time, I wanted to really standardize this.

So I came up with

https://github.com/epuerta9/whisk

The idea is to enhance Fastapi and automatically make it OpenAI endpoint compatible so AI engineers can have a standard way of building microservices and agents and can use the same client for all services I.e OpenAI sdk

Would love to find other collaborators and people who would be interested in building something like this

One cool thing you can do is make your Jupyter notebooks OpenAI compatible so you can chat with your notebooks WHILE you’re experimenting! Makes the process feel more natural

I made a demo video around it

https://www.loom.com/share/92fc161d5b2248df8875e29c874b2aac


r/FastAPI • • Feb 05 '25

feedback request Simple boilerplate

34 Upvotes

Hey there guys, I have been working on a simple boilerplate project that contains user authentication, authorization, role-based access control, and CRUD. It's my first time using Python for web development, and I had issues like modularization, and handling migrations. Check the repo and drop your comments. Thanks in advance

Repo


r/FastAPI • • Jun 28 '24

pip package FastCRUD - powerful CRUD methods and automatic endpoint creation for FastAPI - Reached 450 Stars on Github and Over 24k Downloads!

34 Upvotes

I talked about FastCRUD here a few months ago and got great feedback.

FastCRUD is a Python package for FastAPI, offering robust async CRUD operations and flexible endpoint creation utilities, streamlined through advanced features like auto-detected join conditions, dynamic sorting, and offset and cursor pagination.

With more users joining our community, there's a lot of work ahead. Whether you're a fan of Python, FastAPI, or SQLAlchemy, or just interested in contributing to open-source projects, we'd love your help!

You can contribute by:

  • Opening issues

  • Finding and reporting bugs

  • Testing new features

  • Improving documentation

  • Fixing bugs

  • Adding new features

  • Creating tutorials

GitHub: https://github.com/igorbenav/fastcrud

Docs: https://igorbenav.github.io/fastcrud/


r/FastAPI • • May 20 '23

Other Fastapi minimal starter template

34 Upvotes

Hi everyone,

I found myself rebuilding a lot of basic stuff such as sign up, login, async database functionality and unit tests every time I wanted to quickly POC something. Now I like to keep things simple and customisable when starting and thus usually don't opt for using one of the already existing templates (such as this great generator: https://github.com/s3rius/FastAPI-template) since I feel I spend more time cutting stuff out I don't need.

So, I've put together a minimal starter template that tries to do just the basics and stay out of your way. Included functionalities are:

  • Minimal Fastapi app

  • Async/Await Functionality

  • JWT based OAuth security on a per endpoint basis

  • Unit tests

  • Type hints

  • Basic Database Functionality Included (SQLite3)

  • Support for .env

I figured this also might be useful for others, so I wanted to share it here! You can find the repo here:

https://github.com/StefanVDWeide/fastapi-api-template