r/FastAPI • • Sep 29 '24

pip package secure.py v1.0.0 – Easily Add HTTP Security Headers to Your FastAPI Apps

23 Upvotes

Hello FastAPI community,

I've just released secure.py v1.0.0, a library that makes it easy to manage HTTP security headers in your FastAPI applications. It offers presets and full customization to help secure your apps against common vulnerabilities.

Highlights:

  • BASIC and STRICT security presets

  • Full control over headers like CSP, HSTS, X-Frame-Options, and more

  • Seamless integration with FastAPI

GitHub repository: https://github.com/TypeError/secure

Feedback is welcome and appreciated!


r/FastAPI • • Aug 03 '24

Other open source project for FAST-API

23 Upvotes

Hi, I'm looking for an open source project to contribute some code to, a Python developer with two years of experience, looking for an open source project to strengthen my backend knowledge. I'm looking for a list of projects or something like that.. that you can enter the project easily on the backend side πŸ’»πŸ› οΈ


r/FastAPI • • Feb 03 '22

Tutorial A Tutorial on Developing FastAPI Applications using K8s & AWS

23 Upvotes

Here's a tutorial offered by Jetbrains on FastAPI application development, testing and deployment to AWS.

https://blog.jetbrains.com/pycharm/2022/02/tutorial-fastapi-k8s-aws/


r/FastAPI • • Jun 04 '21

Tutorial FastAPI-PostgreSQL-Celery-RabbitMQ-Redis backend with Docker containerization

23 Upvotes

Hello redditors and r/FastAPI lovers,

During the last two weeks I've been developing a r/FastAPI backend integrated with PostgreSQL, Celery, RabbitMQ, Redis, and deployed easily using $ docker compose.

Link to the github repository: https://github.com/jearistiz/guane-intern-fastapi

If you are learning how to use FastAPI or any of these other frameworks you may find this resource valuable. Oh... and the server initialization script uses u/tiangolo's Typer framework underneath πŸš€


r/FastAPI • • May 03 '20

Other Awesome FastAPI - a curated list of awesome things related to FastAPI

Thumbnail
github.com
23 Upvotes

r/FastAPI • • Oct 17 '26

Other FastAPI for the backend, Flet for the UI β€” sharing RelayDeck

22 Upvotes

Hey everyone! It’s been great seeing FastAPI grow so much and mature over time. It’s now my default choice when building APIs in Python.

I love FastAPI, so I chose it again for this project and paired it with Flet (Cross-platform interfaces in Python). Probably shows how much I love Python too πŸ™‚

RelayDeck, Independent companion for Herdr, which manages coding agents and shell sessions on your Mac. RelayDeck lets you access those sessions from a phone, iPad, or browser.

FastAPI powers the backend API and WebSocket connections, including device pairing and terminal access, while Flet handles the interface.

Here’s what’s available:

  • Usage and limits: token usage and estimated costs by tool and Herdr space, with usage history and charts. Where supported, it also shows plan limits and reset times.

  • Remote terminals: open an agent or shell, check its output, send a prompt, or answer a question directly.

  • Image attachments: attach screenshots and images to prompts, with support for PNG, JPEG, and WebP.

  • Different ways to type: a composer for longer prompts, direct terminal input, and ordinary shell access. Unsent drafts are kept when switching.

  • Web Push notifications: get notified when an agent is blocked or finished, with preferences for each device.

A companion runs on your Mac, and approved devices connect over your private Tailscale network. There’s no RelayDeck cloud service or separate account to create.

Web app and PWA are available now, installed from source. Native Android and iPhone builds are in progress, with branch visibility and code-change review planned.

Repo: https://github.com/Hybridhash/relaydeck

I’d love feedback from other FastAPI developers, Contributions are welcome tooβ€”code, docs, bug reports, or ideas.

If you like the project, I’d appreciate a star! ⭐


r/FastAPI • • Apr 20 '26

Other I built UIGen to auto-generate React frontends from FastAPI OpenAPI specs - here's what happened when I used it on a real internal app

22 Upvotes

Hey veryone,

So a few days back, I shared UIGen here - a tool that generates a full React frontend from your FastAPI OpenAPI spec. The response was very encouraging.

So I iterated on it with a better usecase app.

The Test Case: AI powered Meeting Minutes Generator

I needed an internal tool for work. The requirements:

  • Upload Word templates with Jinja2 variables

  • Create meetings with audio recordings

  • Associate multiple templates with each meeting

  • Fill template data (either AI-generated or manual entry)

  • Generate Word docs, convert to PDF, merge them in order

  • Download the final merged PDF

Standard CRUD stuff, but with file uploads, many-to-many relationships, and some custom actions. Perfect test case.

Backend: FastAPI with async SQLAlchemy, PostgreSQL, Alembic migrations. About 2,000 lines of Python across models, services, repositories, and routers. Full OpenAPI spec auto-generated by FastAPI.

Frontend: Pointed UIGen at the generated yaml.

Improvements that were made

1. Too Much Noise in the UI

FastAPI generates comprehensive specs. That's great for documentation, but not every endpoint needs to be in the UI. I had internal metrics endpoints, health checks.

I didn't want to modify my FastAPI code or the generated spec just to hide these.

Fix: Built vendor extension support, starting with x-uigen-ignore. Now I can annotate my OpenAPI spec:

paths:
  /internal/metrics:
    x-uigen-ignore: true
  /users:
    get:
      x-uigen-ignore: false  # Explicitly include
    post:
      x-uigen-ignore: true   # Hide this specific operation

Or better yet, use the config system (using the cli) so the spec stays untouched:

# .uigen/config.yaml
annotations:
  POST:/internal/metrics:
    x-uigen-ignore: true
  User.internal_id:
    x-uigen-ignore: true

Works on operations, paths, schema properties, and parameters. Operation-level annotations override path-level ones.

2. File Uploads

FastAPI makes file uploads trivial with UploadFile. But UIGen had no idea what to do with type: string, format: binary in the spec.

Fix: Added file upload detection across both OpenAPI 3.x and Swagger 2.0. UIGen now generates a drag-and-drop file upload component with:

  • Type validation (images, documents, videos)

  • Size limits from x-uigen-max-file-size

  • Preview thumbnails

  • Proper multipart/form-data handling

3. Ugly Field Labels

Pydantic field names like created_at, user_id, and is_active get auto-humanized to "Created At", "User Id", "Is Active". Close, but not always right. And I didn't want to change my Python code just for UI labels.

Fix: Added x-uigen-label vendor extension:

# In spec or config
User.created_at:
  x-uigen-label: "Created At"
User.user_id:
  x-uigen-label: "User ID"

Now labels are exactly what I want without touching the FastAPI models.

5. Config Without Touching the Spec

I wanted to hide internal endpoints, rename ugly field labels, and tweak the UI without modifying my FastAPI code or the generated OpenAPI spec.

Fix: Built a config reconciliation system. You create a .uigen/config.yaml file with all your customizations, and UIGen merges them at runtime without touching your source spec:

annotations:
  POST:/internal/metrics:
    x-uigen-ignore: true
  User.created_at:
    x-uigen-label: "Created At"
  POST:/auth/login:
    x-uigen-login: true

Your spec stays clean, your FastAPI code stays clean, but the UI reflects your preferences.

There's a visual config GUI (npx @uigen-dev/cli config openapi.yaml) so you don't have to write YAML by hand. Point-and-click to hide endpoints, rename fields, and customize the theme.

What Actually Works Now

After building this app and fixing the gaps, here's what UIGen generates from my FastAPI spec:

  • Table views with sorting, pagination, and filtering (query params from the spec)

  • Create/edit forms with validation matching my Pydantic models

  • Detail views with related resource links (meetings β†’ templates)

  • File upload UI for template and recording uploads

  • Custom action buttons - "Generate Documents", "Convert to PDF", "Download PDF"

  • Full authentication cycle - login, signup, password reset, token storage, automatic header injection

  • Vendor extensions - x-uigen-ignore, x-uigen-label, x-uigen-login for customization

  • Config GUI - visual editor for annotations and theme customization

  • Dark/light theme toggle

Try It Yourself

The meeting minutes app is in the UIGen repo as a full example:

git clone https://github.com/darula-hpp/uigen
cd examples/apps/fastapi/meeting-minutes

# Start backend (FastAPI + PostgreSQL)
docker compose up -d
docker compose exec app alembic upgrade head

# Generate frontend
cd ../../../
pnpm install && pnpm build
npx @uigen-dev/cli serve examples/apps/fastapi/meeting-minutes/openapi.yaml

Or try it on your own FastAPI app:

npx @uigen-dev/cli serve http://localhost:8000/openapi.json

Limitations

There are still gaps:

  • Circular references - Deeply nested recursive Pydantic models might skip the deepest levels

  • Complex relationships - Many-to-many with extra fields on the join table needs manual handling

  • Custom validation - Pydantic validators with custom logic don't translate to the frontend

  • WebSockets - Not supported yet

  • Streaming responses - Not supported

  • GraphQL - OpenAPI/REST only for now

  • Every OAuth variant - Works for Bearer/API Key/Basic, but not every custom auth flow

V1 will probably be suited for internal tools, admin panels, and rapid prototyping. Not a replacement for a polished consumer-facing app with custom UX requirements. But yeah, its an intereting challenge to include even more usecases.

What's Next

I'm trying to figure out:

  • Better relationship detection and easy relationship config.

  • A non bloat way to do layout customizations

  • Adding Polish & a non Bloat way to configure your app (App name etc)

If you've built a FastAPI app and want to see what UIGen generates, I'd love feedback. The more real-world specs I test against, the better this gets.

GitHub: https://github.com/darula-hpp/uigen
npm: https://www.npmjs.com/package/@uigen-dev/cli
Docs: https://uigen-docs.vercel.app
Architecture: https://uigen-docs.vercel.app/blog/uigen-architecture


Happy to hear what you think.


r/FastAPI • • Apr 05 '26

Question What's the best practice for exception handling in FastAPI?

22 Upvotes

Learning FastAPI and not sure what the right approach is. Should I just use HTTPException directly in my endpoints or should I be creating custom exception classes with global handlers?

What do you do in production?


r/FastAPI • • Mar 08 '26

pip package Chanx : Structured WebSockets for FastAPI

22 Upvotes

Hi guys, I want to share a library I built to help FastAPI handle WebSockets more easily and in a more structured way, as an alternative to https://github.com/encode/broadcaster, which is now archived.

Basically, it allows you to broadcast WebSocket messages from anywhere: background jobs, HTTP endpoints, or scripts. It also makes it easy to handle group messaging (built-in support for broadcasting). The library is fully type-hinted and supports automatic AsyncAPI documentation generation.

Here is how you can define a WebSocket in FastAPI using chanx:

@channel(name="chat", description="Real-time chat API")
class ChatConsumer(AsyncJsonWebsocketConsumer):
    groups = ["chat_room"]  # Auto-join this group on connect

    @ws_handler(
        summary="Handle chat messages",
        output_type=ChatNotificationMessage
    )
    async def handle_chat(self, message: ChatMessage) -> None:
        # Broadcast to all clients in the group
        await self.broadcast_message(
            ChatNotificationMessage(
                payload=ChatPayload(message=f"User: {message.payload.message}")
            )
        )

The package is published on PyPI at https://pypi.org/project/chanx/

The repository is available at https://github.com/huynguyengl99/chanx

A full tutorial on using it with FastAPI (including room chat and background jobs) is available here: https://chanx.readthedocs.io/en/latest/tutorial-fastapi/prerequisites.html

Hope you like it and that it helps make handling WebSockets easier.


r/FastAPI • • Jan 15 '26

Tutorial [Update] Bookstore API Guide

22 Upvotes

πŸš€ Major Update v3.0: Production-Ready Python FastAPI Course - Now with Interactive Learning Roadmap!

Hey r/FastAPI! πŸ‘‹

I'm excited to share another major update to my free, open-source Python development course! After amazing community feedback, I've added something special - an interactive web-based learning roadmap that makes navigating this comprehensive course incredibly easy!

This is NOT an advertisement - just sharing valuable learning resources with the community! πŸŽ“


πŸ†• What's New in v3.0:

πŸ—ΊοΈ Interactive Learning Roadmap Website

The biggest addition - a beautiful, interactive roadmap that helps you navigate the entire learning journey!

βœ… Visual Learning Paths - See all 6 learning paths in an intuitive tree structure
βœ… Direct GitHub Integration - Every topic links directly to the relevant code
βœ… Expandable Sections - Drill down into topics that interest you
βœ… Progress Tracking - Know exactly where you are in your learning journey
βœ… Mobile-Responsive - Learn on any device
βœ… Beautiful UI - Gradient design with smooth animations

Live Demo: bookstore-api-course.vercel.app

πŸ“š BookStore API Learning Roadmap
β”œβ”€β”€ πŸš€ Quick Explorer (5 min)
β”‚   β”œβ”€β”€ Setup Environment β†’ [Direct link to QUICK_START.md]
β”‚   β”œβ”€β”€ Start Development Server β†’ [Direct link to run_bookstore.py]
β”‚   └── Explore API Documentation β†’ [Direct link to docs]
β”œβ”€β”€ πŸ“± API User (30 min)
β”‚   β”œβ”€β”€ Authentication Flow β†’ [Direct link to auth.py]
β”‚   └── Core Operations β†’ [Direct link to routers/]
β”œβ”€β”€ πŸ‘¨β€πŸ’» Developer (2 hours)
β”‚   β”œβ”€β”€ Code Structure β†’ [Direct link to PROJECT_STRUCTURE.md]
β”‚   └── Testing Deep Dive β†’ [Direct link to tests/]
β”œβ”€β”€ 🏭 Production User (1 hour)
β”‚   β”œβ”€β”€ Docker Deployment β†’ [Direct link to deployment/docker/]
β”‚   └── Monitoring Setup β†’ [Direct link to monitoring/]
└── ☸️ DevOps Engineer (3 hours)
    β”œβ”€β”€ Kubernetes Deployment β†’ [Direct link to k8s/]
    └── CI/CD Pipeline β†’ [Direct link to .github/workflows/]

πŸ“ Beginner-Friendly Code Comments

Added comprehensive English comments throughout the codebase:

βœ… Educational explanations - Not just what, but WHY
βœ… Concept introductions - Learn patterns as you read
βœ… Best practices - Understand production standards
βœ… Architecture insights - See how everything fits together

Perfect for newcomers studying the repository!


πŸ”₯ What's Still Included (Production-Ready Features):

πŸ—οΈ Enterprise-Grade Architecture

  • FastAPI with async/await and automatic OpenAPI docs

  • SQLAlchemy 2.0 with proper relationship management

  • Pydantic v2 for bulletproof data validation

  • JWT Authentication with secure token handling

  • Alembic migrations for professional database management

πŸ§ͺ Comprehensive Testing (95%+ Coverage)

  • Unit tests - Core functionality validation

  • Integration tests - API endpoint testing

  • Property-based tests - Hypothesis for edge cases

  • Performance tests - Load testing with Locust

  • Security tests - Automated vulnerability scanning

🐳 Production Deployment Stack

  • Multi-stage Docker builds - Optimized for production

  • Kubernetes manifests - Auto-scaling and high availability

  • Docker Compose - Both dev and production environments

  • Nginx load balancer - SSL termination and routing

πŸ“Š Monitoring & Observability

  • Prometheus - Metrics collection and alerting

  • Grafana - Beautiful dashboards and visualization

  • Loki - Centralized log aggregation

  • Structured logging - JSON format with request tracing

πŸ”„ CI/CD Pipeline

  • GitHub Actions - Automated testing and deployment

  • Multi-environment - Staging and production workflows

  • Security scanning - Bandit, Safety, Semgrep integration

  • Automated releases - Version management and tagging


🎯 Six Learning Paths (Now with Interactive Roadmap!):

πŸš€ Quick Explorer (5 minutes)

Just want to see it work? One command setup!

  • Clone β†’ Run β†’ Explore API docs

  • Make your first API request

  • See production-quality code in action

πŸ“± API User (30 minutes)

Learn to integrate with professional APIs

  • JWT authentication flow

  • CRUD operations with pagination

  • Advanced filtering and search

  • Error handling patterns

πŸ‘¨β€πŸ’» Developer (2 hours)

Understand and modify production-quality code

  • FastAPI application architecture

  • SQLAlchemy models and relationships

  • Pydantic schemas and validation

  • Testing strategies and patterns

🏭 Production User (1 hour)

Deploy and monitor in real environments

  • Docker containerization

  • Environment configuration

  • SSL/HTTPS setup

  • Monitoring dashboards

☸️ DevOps Engineer (3 hours)

Master the complete infrastructure pipeline

  • Kubernetes deployment

  • Auto-scaling configuration

  • CI/CD automation

  • Security best practices

πŸŽ“ Learning Path (Ongoing)

Use as comprehensive Python/DevOps curriculum

  • FastAPI cheatsheets and examples

  • OOP and advanced Python patterns

  • Testing methodologies

  • Production deployment guides


πŸ’‘ What Makes This Special:

βœ… Interactive roadmap - Navigate visually with direct GitHub links (NEW!)
βœ… Beginner-friendly comments - Learn as you read the code (NEW!)
βœ… Real production patterns - Not toy examples
βœ… Database migrations - Professional schema management
βœ… Clean architecture - Organized for scalability
βœ… Complete CI/CD - From commit to production
βœ… Security-first - Best practices built-in
βœ… Monitoring ready - Observability from day one
βœ… Interview prep - Discuss real architecture in interviews


πŸ› οΈ Tech Stack:

Backend: FastAPI, SQLAlchemy, Pydantic, Alembic
Database: PostgreSQL, Redis
Deployment: Docker, Kubernetes, Nginx
Monitoring: Prometheus, Grafana, Loki
Testing: pytest, Hypothesis, Locust
CI/CD: GitHub Actions
Roadmap: Flask, Vercel (NEW!)


⚑ Quick Start:

# 30-second setup
git clone https://github.com/f1sherFM/bookstore-api-course.git
cd bookstore-api-course
cd deployment/docker && docker-compose up -d

# API docs: http://localhost:8000/docs
# Grafana: http://localhost:3000
# Interactive Roadmap: bookstore-api-course.vercel.app 

πŸ“Š Project Stats:

πŸ“ˆ 95%+ test coverage - Comprehensive quality assurance
πŸ—οΈ Production-ready - Used in real deployments
πŸ—ΊοΈ Interactive roadmap - Visual learning experience (NEW!)
πŸ“ Educational comments - Learn from the code (NEW!)
πŸ”„ Professional migrations - Alembic integration
πŸ“ Clean structure - Organized for teams
πŸš€ 6 learning paths - Something for everyone
πŸ“š Complete documentation - Every feature explained
πŸ”’ Security hardened - Best practices implemented


πŸŽ“ Learning Outcomes:

By the end, you'll have:

βœ… Built a scalable, monitored API from scratch
βœ… Mastered database migrations and schema management
βœ… Learned production deployment with Docker/K8s
βœ… Implemented comprehensive testing strategies
βœ… Set up monitoring and observability
βœ… Created a portfolio project for interviews
βœ… Navigated a real production codebase with confidence (NEW!)


πŸ”— Links:

GitHub: https://github.com/f1sherFM/bookstore-api-course
Interactive Roadmap: bookstore-api-course.vercel.app
Quick Start: Check QUICK_START.md in the repo
Documentation: Browse documentation/ directory


πŸ™ Community:

This project has grown thanks to community feedback! The new interactive roadmap was inspired by requests for better navigation and learning structure.

If you find this useful:

⭐ Star the repo - Helps others discover it
πŸ› Report issues - Help make it better
πŸ’‘ Suggest features - What would you like to see?
🀝 Contribute - PRs welcome!

Remember: This is a learning resource, not a commercial product. Everything is free and open-source!


🎨 Screenshots:

[You can add screenshots of the interactive roadmap here]

  • Beautiful gradient design

  • Expandable tree structure

  • Direct GitHub integration

  • Mobile-responsive layout

  • Statistics and progress tracking


What do you think of the new interactive roadmap? Does it make the learning journey clearer? Any features you'd like to see added? πŸ€”

P.S. The roadmap website itself is also open-source and deployed on Vercel - check out the roadmap-site branch to see how it's built! w/ love, your f1sherFM πŸ’•


r/FastAPI • • Jun 23 '25

Question Memory Optimization in Fast API app

22 Upvotes

I'm seeking architectural guidance to optimize the execution of five independent YOLO (You Only Look Once) machine learning models within my application.

Current Stack:

  • Backend: FastAPI

  • Caching & Message Broker: Redis

  • Asynchronous Tasks: Celery

  • Frontend: React.js

Current Challenge:

Currently, I'm running these five ML models in parallel using independent Celery tasks. Each task, however, consumes approximately 1.5 GB of memory. A significant issue is that for every user request, the same model is reloaded into memory, leading to high memory usage and increased latency.

Proposed Solution (after initial research):

My current best idea is to create a separate FastAPI application dedicated to model inference. In this setup:

  1. Each model would be loaded into memory once at startup using FastAPI's lifespan event.

  2. Inference requests would then be handled using a ProcessPoolExecutor with workers.

  3. The main backend application would trigger inference by making POST requests to this new inference-dedicated FastAPI service.

Primary Goals:

My main objectives are to minimize latency and optimize memory usage to ensure the solution is highly scalable.

Request for Ideas:

I'm looking for architectural suggestions or alternative approaches that could help me achieve these goals more effectively. Any insights on optimizing this setup for low latency and memory efficiency would be greatly appreciated.


r/FastAPI • • May 05 '25

pip package FastAPI swagger dark theme plugin.

22 Upvotes

Following on from a post yesterday from u/Fit_Tell_8592. The idea of a darkthemed swagger ui appealed to me, but there wasn't a simple plugin to just enable it (that I have found).

Using the existing dark theme css as a base, I give you fastapi-swagger-dark.

Supports out of the box /docs with minimal code, and also supports custom prefix and custom path definitions.

If you are rolling your own docs implemenations with custom auth etc, that use case is also supported.

pypi

github


r/FastAPI • • May 30 '24

Hosting and deployment What is the right way to deploy a FastAPI app?

22 Upvotes

Hello Community,
I recently developed a FastAPI project and it's currently hosted on AWS lightsail and the code is on a private repo on github.

I have test cases, pre-commit hooks to do linting and formatting and setup tox for isolated testing. I learned docker and was able to dockerise my app on my local system and everything is working fine.

Now my questions are the following.

  1. How can I setup a CI/CD pipeline to deploy the app using docker to lightsail. One way is I push to docker hub and then pull into AWS. But the docker free plan only allows limited push and pull. Even if I do this, I still need to manually sync the docker compose file for changes.

  2. I there any other way which might not be fully automated but gets the job done in a reliable fashion.

  3. Do we need to run all the tests from inside the docker container also?

I'd love to know your thoughts/Ideas and suggestions. I'm new to this deployment game so I don't know how things work in production.

Thank You

Update : Finally, completed the CI/CD pipeline for my fastAPI project. Used Github actions to build the docker image and push to AWS ECR, SSH into EC2 instance from github runner -> copy the docker-compose.yml file and pull the latest image from ECR, and restart the container.
I have also added Github actions for testing and linting the code on every push. Used Pre-commit to do the basic checks before every commit.

Thank you, everyone for the help, Ideas, and suggestions!


r/FastAPI • • Feb 09 '24

pip package We made a one-line frontend generation package for FastAPI

22 Upvotes

Hello r/FastAPI!

A friend of mine and I, big time users of fastapi, were at a Generative UI hackathon a couple weeks ago. We don't like building frontend stuff when building backend is so easy, so we invented Natural Frontend (Github).

Just add this one line and an AI will read your code, add a /frontend endpoint to your api, and generate frontends for you there based on who it thinks would use your api.

It makes it very quick to prototype different types of frontends.

Please let us know what you think!


r/FastAPI • • Jun 04 '23

Other Example app using FastAPI, SQLModel, Celery, Alembic and Supertokens

22 Upvotes

Hello FastAPI subreddit!

https://github.com/petrgazarov/FastAPI-app

This is a small app I built while learning Python and FastApi. Most of the time was spent learning the best practices for accomplishing common tasks in the FastAPI ecosystem and churning through third-party libraries to achieve an overall better design.
There aren't very many examples online that go beyond the "hello-world" basic stuff for how to build production applications with FastAPI. So I decided to open-source mine for the benefit of those who may be starting out on their FastAPI journey.


r/FastAPI • • Mar 23 '23

feedback request FastAPI Repository Pattern - cookiecutter template

22 Upvotes

Hi! I wanted to share this simple cookiecutter template that I built.

After some time looking for the best FastAPI structure and getting inspired from existing resources like FastAPI Best practices and FastAPI Layered architecture I created this template.

The main goal was to apply the repository pattern approach but always with simplicity in mind.

It's also a design decision not to include docker or any form of infrastructure coupling.

The main features are:

  • Quick and simple setup

  • Compatibility with SQL and NoSQL repositories, thanks to Redbird

  • Ready CRUD entity to start with 100% test coverage

  • Tests mocked with pydantic-factories

  • Ruff + black for code linting and styling

  • Python dependency-injector for repository and services injection

  • Poetry for dependency management

I'm very open to feedback because I'm currently using this template in production and it's working great, but I'd like to achieve the best production-ready template possible with the repository pattern approach in FastAPI.Β 

Link to the repository: Fastapi Repository Pattern Template


r/FastAPI • • Feb 17 '23

Hosting and deployment Cookiecutter template to build and deploy FastAPI backends…batteries included

22 Upvotes

I’ve seen a few template projects posted, so I thought I would share mine. A small Cookiecutter I use to get up and running with my backends https://github.com/nickatnight/cookiecutter-fastapi-backend

Comes with some nice bells and whistles: nginx web proxy, postgres, async, ci/cd, pre-commit hooks and auto certbot renewal to name a few.


r/FastAPI • • Nov 22 '21

Tutorial Part 3 of my FastAPI tutorial. We'll use SQLAlchemy and Pydantic to build some CRUD endpoints (well mostly R :p). As always, all feedback is welcomed !

Thumbnail
dev.indooroutdoor.io
22 Upvotes

r/FastAPI • • Nov 20 '21

Tutorial FastAPI + SQLModel + FastAPI-crudrouter + testcontainers setup

22 Upvotes

https://dimmaski.com/fastapi-sqlmodel-crud/

Hey all! It's my first time posting on this subreddit. I wrote a blog post on how I've been using FastAPI to create API services with zero boilerplate code, using sqlmodel + fastapi-crudrouter. I found that the methods described here allow me to prototype really quick, and take a test-first approach using testcontainers. I would appreciate a lot if you took a look and provided some feedback or possible improvements!


r/FastAPI • • Nov 09 '21

pip package Pydbantic - A single model ( DB & Pydantic) with automatic migrations

22 Upvotes

Hello All,

I wanted to quickly share a project that I am actively maintaining, in the hopes that it may help to make your development lives a little easier:

Pydbantic

Pydbantic provides a single model abstraction for Database Models & Pydantic BaseModels and all of their `goodness` that we use within FastAPI. I have tried to mirror much of the same API's that Django provides to querying objects, and abstracted away one of the biggest pains that we developers are destined to face: Changing the Model.

Pydbantic stores existing DB & Model schema's as metdata alongside data tables, which provides the ability to inspect & detect model changes at runtime, and subsequently migrate the data for you to match and meet the new Models definition.

Pydbantic also provides a simple way to implement query caching with Redis. Simply plugin a Redis URL and Pydbantic handles caching your queries and invalidation.

Pydbantic is very flexible on data types. Large, or nested BaseModel structures? Feel free to use these in the `DataBaseModel`. Pydbantic will store these models & handle the serialization / de-serialization for you.

Related Data? Pydbantic `DataBaseModel` s can refer to one another, and automatically create and join available foreign models, just like combining pydantic BaseModels.

Pydbantic is constantly improving, so any feedback is appreciated.


r/FastAPI • • Jul 22 '21

Tutorial How to Deploy a Secure API with FastAPI, Docker and Traefik

22 Upvotes

Putting your API to production comes with securing it with HTTPS and encrypting data transfer: something a lot of people neglect or take for granted.

HTTPS cannot just be turned on by changing a config file: a few steps are required.

In this post, I detail the process of securing a FastAPI app with HTTPS by using Docker and Traefik (the procedure is the same for other types of web applications)

Here's what's covered

  • A brief introduction to HTTPS: how does it work and why you should care about it?

  • Building a simple API with FastAPI

  • Introducing Traefik as and how it can handle HTTPS by integrating with Let's Encrypt and Docker

  • Deploying on AWS

https://towardsdatascience.com/how-to-deploy-a-secure-api-with-fastapi-docker-and-traefik-b1ca065b100f


r/FastAPI • • May 17 '26

Question Admin Dashboard for FastAPI

21 Upvotes

What’s a good admin dashboard for FastAPI? I have a bunch of project ideas I plan on working on in the next few months and I don’t want to be building out a dashboard for each of them. I’ve done some research and while there are some decent ones out there I wanted to see what the community had to say.


r/FastAPI • • Apr 24 '26

Question Concurrency issues

21 Upvotes

My company has products spread over multiple countries and the user of these products are increasing rapidly that results in concurrent requests. Due to such highly concurrent requests fastAPI Microservices were showing heavy latency and delays. So the company is shifting towards GO lang.

So is this true in case of fastAPI that it can not handle the large user base?


r/FastAPI • • Apr 07 '26

pip package I built a task visibility layer for FastAPI's native BackgroundTasks (retries, live dashboard, logs, no broker)

21 Upvotes

If your team uses FastAPI's BackgroundTasks for tasks like sending emails, webhooks, processing uploads or similar, you've probably felt the lack of built-in observability.

The bare API gives you no task IDs, no status tracking, no retries, and no persistence across restarts. When something goes wrong you're digging through app logs hoping the right line is there.

Celery, ARQ, and Taskiq solve this well, but they come with a broker, separate workers, and a meaningful ops footprint. For teams whose tasks genuinely need that, those tools are the right call.

fastapi-taskflow is for the other case: teams already using BackgroundTasks for simple in-process work who want retries, status tracking, and a dashboard without standing up extra infrastructure.

What it adds on top of BackgroundTasks:

  • Automatic retries with configurable delay and exponential backoff per function

  • Every task gets a UUID and moves through PENDING > RUNNING > SUCCESS / FAILED

  • A live dashboard at /tasks/dashboard over SSE with filtering, search, and per-task details

  • task_log() to emit timestamped log entries from inside a task, shown in the dashboard

  • Full stack trace capture on failure, also in the dashboard

  • SQLite persistence out of the box

  • Tasks that were still pending at shutdown are re-dispatched on the next startup

The route signature does not change. You keep your existing BackgroundTasks annotation, one line at startup wires everything in:

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

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


@task_manager.task(retries=3, delay=1.0, backoff=2.0)
def send_email(address: str) -> None:
    task_log(f"Sending to {address}")
    ...


@app.post("/signup")
def signup(email: str, background_tasks: BackgroundTasks):
    task_id = background_tasks.add_task(send_email, address=email)
    return {"task_id": task_id}

To be clear about scope: this is not a distributed task queue and does not try to be. If you need tasks to survive across distributed services, run on dedicated workers, or integrate with a broker, reach for Celery or one of the other proper queues.

This is for teams who are already happy with BackgroundTasks for in-process work and just want retries, visibility, and persistence without changing their setup.

Available on PyPI: pip install fastapi-taskflow

Docs and source: https://github.com/Attakay78/fastapi-taskflow

Would be good to hear from anyone using BackgroundTasks in production. What do you actually need to make it manageable? Retries, visibility, persistence, something else?
Trying to understand what's missing for teams in this space before adding more.