r/FastAPI • • Oct 12 '25

Other Recreating TypeScript --strict in Python: pyright + ruff + pydantic (and catching type bugs)

30 Upvotes

Hey folks— I’ve been fighting sneaky type bugs in Python projects. I’m used to TypeScript’s --strict, so I built a Python setup that feels similar: pyright (strict) for static typing, ruff for lint + annotation discipline, and pydantic v2 for runtime validation. It warns me as I write code (VS Code / Pylance) and blocks bad types in CI.

Below is a minimal, copy-pasteable setup (pyproject.toml, pyrightconfig.json, and optional pre-commit) plus a tiny example that fails both statically and at runtime.


TL;DR

  • Static (editor/CI): pyright in strict mode → no implicit Any, strict Optional, variance checks, etc.

  • Style/discipline: ruff with “strict-ish” rules → forces annotations and catches foot-guns.

  • Runtime: pydantic models validate inputs/outputs so prod doesn’t silently drift.

  • Feedback loop: VS Code (Pylance/pyright) surfaces errors as you type; pre-commit/CI gates merges.


# ============================================================
# ULTRA-STRICT PYTHON PROJECT TEMPLATE
# Maximum strictness - TypeScript strict mode equivalent
# Tools: uv + ruff + pyright/pylance + pydantic v2
# Python 3.12+
# ============================================================

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "your-project-name"
version = "0.1.0"
description = "Your project description"
authors = [{ name = "Your Name", email = "[email protected]" }]
license = { text = "MIT" }
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "pydantic",
    "pydantic-ai",              # Agent framework with type safety
    "python-dotenv",
    "logfire",                  # Optional: Pydantic's observability platform
    "pydantic-ai-slim[openai]"  # Agent framework with type safety
]

[project.optional-dependencies]
dev = [
    "pyright",
    "ruff",
    "pytest>=8.0.0",
    "pytest-cov>=4.1.0",
    "pytest-asyncio>=0.23.0",
]

# LLM Provider extras - install with: uv pip install -e ".[openai]"
openai = ["pydantic-ai[openai]"]
anthropic = ["pydantic-ai[anthropic]"]
gemini = ["pydantic-ai[gemini]"]
all-llms = ["pydantic-ai[openai,anthropic,gemini]"]

[tool.setuptools.packages.find]
where = ["."]
include = ["*"]
exclude = ["tests*", "scripts*", "docs*", "examples*"]

# ============================================================
# UV SCRIPTS - Custom Commands
# ============================================================
[tool.uv]
# Run with: uv run format
# Formats code, fixes issues, and type checks
format = "ruff format . && ruff check . --fix && pyright"

# Run with: uv run check
# Lint and type check without fixing
check = "ruff check . && pyright"

# Run with: uv run lint
# Only linting, no type checking
lint = "ruff check . --fix"

# ============================================================
# RUFF CONFIGURATION - MAXIMUM STRICTNESS
# ============================================================
[tool.ruff]
target-version = "py312"
line-length = 88
indent-width = 4
fix = true
show-fixes = true

[tool.ruff.lint]
# Comprehensive rule set for strict checking
select = [
    "E",      # pycodestyle errors
    "F",      # pyflakes
    "I",      # isort
    "UP",     # pyupgrade
    "B",      # flake8-bugbear
    "C4",     # flake8-comprehensions
    "T20",    # flake8-print (no print statements)
    "SIM",    # flake8-simplify
    "N",      # pep8-naming
    "Q",      # flake8-quotes
    "RUF",    # Ruff-specific rules
    "ASYNC",  # flake8-async
    "S",      # flake8-bandit (security)
    "PTH",    # flake8-use-pathlib
    "ERA",    # eradicate (commented-out code)
    "PL",     # pylint
    "PERF",   # perflint (performance)
    "ANN",    # flake8-annotations
    "ARG",    # flake8-unused-arguments
    "RET",    # flake8-return
    "TCH",    # flake8-type-checking
]

ignore = [
    "E501",    # Line too long (formatter handles this)
    "S603",    # subprocess without shell=True (too strict)
    "S607",    # Starting a process with a partial path (too strict)
    "ANN101",  # Missing type annotation for self (redundant)
    "ANN102",  # Missing type annotation for cls (redundant)
]

# Per-file ignores
[tool.ruff.lint.per-file-ignores]
"__init__.py" = [
    "F401",    # Allow unused imports in __init__.py
]
"tests/**/*.py" = [
    "S101",    # Allow assert in tests
    "PLR2004", # Allow magic values in tests
    "ANN",     # Don't require annotations in tests
]

[tool.ruff.lint.isort]
known-first-party = ["your_package_name"]  # CHANGE THIS
combine-as-imports = true
force-sort-within-sections = true

[tool.ruff.lint.pydocstyle]
convention = "google"

[tool.ruff.lint.flake8-type-checking]
strict = true

[tool.ruff.format]
quote-style = "double"
indent-style = "space"
skip-magic-trailing-comma = false
line-ending = "auto"

# ============================================================
# PYRIGHT CONFIGURATION - MAXIMUM STRICTNESS
# TypeScript strict mode equivalent
# ============================================================
[tool.pyright]
pythonVersion = "3.12"
typeCheckingMode = "strict"

# ============================================================
# IMPORT AND MODULE CHECKS
# ============================================================
reportMissingImports = true
reportMissingTypeStubs = true  # Stricter: require type stubs
reportUndefinedVariable = true
reportAssertAlwaysTrue = true
reportInvalidStringEscapeSequence = true

# ============================================================
# STRICT NULL SAFETY (like TS strictNullChecks)
# ============================================================
reportOptionalSubscript = true
reportOptionalMemberAccess = true
reportOptionalCall = true
reportOptionalIterable = true
reportOptionalContextManager = true
reportOptionalOperand = true

# ============================================================
# TYPE COMPLETENESS (like TS noImplicitAny + strictFunctionTypes)
# ============================================================
reportMissingParameterType = true
reportMissingTypeArgument = true
reportUnknownParameterType = true
reportUnknownLambdaType = true
reportUnknownArgumentType = true   # STRICT: Enable (can be noisy)
reportUnknownVariableType = true   # STRICT: Enable (can be noisy)
reportUnknownMemberType = true     # STRICT: Enable (can be noisy)
reportUntypedFunctionDecorator = true
reportUntypedClassDecorator = true
reportUntypedBaseClass = true
reportUntypedNamedTuple = true

# ============================================================
# CLASS AND INHERITANCE CHECKS
# ============================================================
reportIncompatibleMethodOverride = true
reportIncompatibleVariableOverride = true
reportInconsistentConstructor = true
reportUninitializedInstanceVariable = true
reportOverlappingOverload = true
reportMissingSuperCall = true  # STRICT: Enable

# ============================================================
# CODE QUALITY (like TS noUnusedLocals + noUnusedParameters)
# ============================================================
reportPrivateUsage = true
reportConstantRedefinition = true
reportInvalidStubStatement = true
reportIncompleteStub = true
reportUnsupportedDunderAll = true
reportUnusedClass = "error"        # STRICT: Error instead of warning
reportUnusedFunction = "error"     # STRICT: Error instead of warning
reportUnusedVariable = "error"     # STRICT: Error instead of warning
reportUnusedImport = "error"       # STRICT: Error instead of warning
reportDuplicateImport = "error"    # STRICT: Error instead of warning

# ============================================================
# UNNECESSARY CODE DETECTION
# ============================================================
reportUnnecessaryIsInstance = "error"         # STRICT: Error
reportUnnecessaryCast = "error"               # STRICT: Error
reportUnnecessaryComparison = "error"         # STRICT: Error
reportUnnecessaryContains = "error"           # STRICT: Error
reportUnnecessaryTypeIgnoreComment = "error"  # STRICT: Error

# ============================================================
# FUNCTION/METHOD SIGNATURE STRICTNESS
# ============================================================
reportGeneralTypeIssues = true
reportPropertyTypeMismatch = true
reportFunctionMemberAccess = true
reportCallInDefaultInitializer = true
reportImplicitStringConcatenation = true  # STRICT: Enable

# ============================================================
# ADDITIONAL STRICT CHECKS (Progressive Enhancement)
# ============================================================
reportImplicitOverride = true    # STRICT: Require @override decorator (Python 3.12+)
reportShadowedImports = true     # STRICT: Detect shadowed imports
reportDeprecated = "warning"     # Warn on deprecated usage

# ============================================================
# ADDITIONAL TYPE CHECKS
# ============================================================
reportImportCycles = "warning"

# ============================================================
# EXCLUSIONS
# ============================================================
exclude = [
    "**/__pycache__",
    "**/node_modules",
    ".git",
    ".mypy_cache",
    ".pyright_cache",
    ".ruff_cache",
    ".pytest_cache",
    ".venv",
    "venv",
    "env",
    "logs",
    "output",
    "data",
    "build",
    "dist",
    "*.egg-info",
]

venvPath = "."
venv = ".venv"

# ============================================================
# PYTEST CONFIGURATION
# ============================================================
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
addopts = [
    "--strict-markers",
    "--strict-config",
    "--tb=short",
    "--cov=.",
    "--cov-report=term-missing:skip-covered",
    "--cov-report=html",
    "--cov-report=xml",
    "--cov-fail-under=80",  # STRICT: Require 80% coverage
]
markers = [
    "slow: marks tests as slow (deselect with '-m \"not slow\"')",
    "integration: marks tests as integration tests",
    "unit: marks tests as unit tests",
]

# ============================================================
# COVERAGE CONFIGURATION
# ============================================================
[tool.coverage.run]
source = ["."]
branch = true  # STRICT: Enable branch coverage
omit = [
    "*/tests/*",
    "*/test_*.py",
    "*/__pycache__/*",
    "*/.venv/*",
    "*/venv/*",
    "*/scripts/*",
]

[tool.coverage.report]
precision = 2
show_missing = true
skip_covered = false
fail_under = 80  # STRICT: Require 80% coverage
exclude_lines = [
    "pragma: no cover",
    "def __repr__",
    "raise AssertionError",
    "raise NotImplementedError",
    "if __name__ == .__main__.:",
    "if TYPE_CHECKING:",
    "@abstractmethod",
    "@overload",
]

# ============================================================
# QUICK START GUIDE
# ============================================================
#
# 1. CREATE NEW PROJECT:
#    mkdir my-project && cd my-project
#    cp STRICT_PYPROJECT_TEMPLATE.toml pyproject.toml
#
# 2. CUSTOMIZE (REQUIRED):
#    - Change project.name to "my-project"
#    - Change project.description
#    - Change project.authors
#    - Change tool.ruff.lint.isort.known-first-party to ["my_project"]
#
# 3. SETUP ENVIRONMENT:
#    uv venv
#    source .venv/bin/activate  # Linux/Mac
#    .venv\Scripts\activate     # Windows
#    uv pip install -e ".[dev]"
#
# 4. CREATE PROJECT STRUCTURE:
#    mkdir -p src/my_project tests
#    touch src/my_project/__init__.py
#    touch tests/__init__.py
#
# 5. CREATE .gitignore:
#    echo ".venv/
#    __pycache__/
#    *.py[cod]
#    .pytest_cache/
#    .ruff_cache/
#    .pyright_cache/
#    .coverage
#    htmlcov/
#    dist/
#    build/
#    *.egg-info/
#    .env
#    .DS_Store" > .gitignore
#
# 6. DAILY WORKFLOW:
#    # Format code
#    uv run ruff format .
#
#    # Lint and auto-fix
#    uv run ruff check . --fix
#
#    # Type check (strict!)
#    uv run pyright
#
#    # Run tests with coverage
#    uv run pytest
#
#    # Full check (run before commit)
#    uv run ruff format . && uv run ruff check . && uv run pyright && uv run pytest
#
# 7. VS CODE SETUP (recommended):
#    Create .vscode/settings.json:
#    {
#      "python.defaultInterpreterPath": ".venv/bin/python",
#      "python.analysis.typeCheckingMode": "strict",
#      "python.analysis.autoImportCompletions": true,
#      "editor.formatOnSave": true,
#      "editor.codeActionsOnSave": {
#        "source.organizeImports": true,
#        "source.fixAll": true
#      },
#      "[python]": {
#        "editor.defaultFormatter": "charliermarsh.ruff"
#      },
#      "ruff.enable": true,
#      "ruff.lint.enable": true,
#      "ruff.format.args": ["--config", "pyproject.toml"]
#    }
#
# 8. GITHUB ACTIONS CI (optional):
#    Create .github/workflows/ci.yml:
#    name: CI
#    on: [push, pull_request]
#    jobs:
#      test:
#        runs-on: ubuntu-latest
#        steps:
#          - uses: actions/checkout@v4
#          - uses: astral-sh/setup-uv@v1
#          - run: uv pip install -e ".[dev]"
#          - run: uv run ruff format --check .
#          - run: uv run ruff check .
#          - run: uv run pyright
#          - run: uv run pytest
#
# ============================================================
# PYDANTIC V2 PATTERNS (IMPORTANT)
# ============================================================
#
# ✅ CORRECT (Pydantic v2):
# from pydantic import BaseModel, field_validator, model_validator, ConfigDict
#
# class User(BaseModel):
#     model_config = ConfigDict(strict=True)
#     name: str
#     age: int
#
#     @field_validator('age')
#     @classmethod
#     def validate_age(cls, v: int) -> int:
#         if v < 0:
#             raise ValueError('age must be positive')
#         return v
#
#     @model_validator(mode='after')
#     def validate_model(self) -> 'User':
#         return self
#
# ❌ WRONG (Pydantic v1 - deprecated):
# class User(BaseModel):
#     class Config:
#         strict = True
#
#     @validator('age')
#     def validate_age(cls, v):
#         return v
#
# ============================================================
# PYDANTIC AI PATTERNS
# ============================================================
#
# ✅ CORRECT (Type-safe agent with structured output):
# from dataclasses import dataclass
# from pydantic import BaseModel, Field
# from pydantic_ai import Agent, RunContext
#
# @dataclass
# class Dependencies:
#     user_id: int
#     db: DatabaseConn
#
# class AgentOutput(BaseModel):
#     response: str = Field(description='Response to user')
#     confidence: float = Field(ge=0.0, le=1.0)
#
# agent = Agent(
#     'openai:gpt-4o',
#     deps_type=Dependencies,
#     output_type=AgentOutput,
#     instructions='You are a helpful assistant.',
# )
#
# @agent.tool
# async def get_user_data(ctx: RunContext[Dependencies]) -> dict[str, str]:
#     """Fetch user data from database."""
#     return await ctx.deps.db.get_user(ctx.deps.user_id)
#
# # Usage:
# deps = Dependencies(user_id=123, db=db_conn)
# result = await agent.run('Help me', deps=deps)
# print(result.output.response)  # Fully typed!
#
# Key Features:
# - MCP (Model Context Protocol) support for external tools
# - Human-in-the-loop tool approval
# - Streaming structured outputs with validation
# - Durable execution for long-running workflows
# - Graph support for complex control flow
#
# Environment Variables (add to .env):
# OPENAI_API_KEY=sk-...
# ANTHROPIC_API_KEY=sk-ant-...
# GEMINI_API_KEY=...
# LOGFIRE_TOKEN=...  # Optional: for observability
#
# ============================================================
# STRICTNESS LEVELS
# ============================================================
#
# This template is at MAXIMUM strictness. To reduce:
#
# LEVEL 1 - Production Ready (Recommended):
#   - Keep all current settings
#   - This is the gold standard
#
# LEVEL 2 - Slightly Relaxed:
#   - reportUnknownArgumentType = false
#   - reportUnknownVariableType = false
#   - reportUnknownMemberType = false
#   - reportUnused* = "warning" (instead of "error")
#
# LEVEL 3 - Gradual Adoption:
#   - typeCheckingMode = "standard"
#   - reportMissingSuperCall = false
#   - reportImplicitOverride = false
#
# ============================================================
# TROUBLESHOOTING
# ============================================================
#
# Q: Too many type errors from third-party libraries?
# A: Add to exclude list or set reportMissingTypeStubs = false
#
# Q: Pyright too slow?
# A: Add large directories to exclude list
#
# Q: Ruff "ALL" too strict?
# A: Replace "ALL" with specific rule codes (see template above)
#
# Q: Coverage failing?
# A: Reduce fail_under from 80 to 70 or 60
#
# Q: How to ignore specific errors temporarily?
# A: Use # type: ignore[error-code] or # noqa: RULE_CODE
#    But fix them eventually - strict mode means no ignores!
#

Why not mypy?

Nothing wrong with mypy; pyright tends to be faster, has great editor integration, and its strict defaults map cleanly to the mental model of TS --strict. If you prefer mypy, set warn-redundant-casts = True, no-implicit-optional = True, disallow-any-generics = True, etc., to achieve a similar effect.


r/FastAPI • • Sep 11 '25

Question How complicated is social auth

30 Upvotes

To everyone who has already implemented their own auth with social sign-in (Google & Apple), how long did it take you.

Currently planning a new project and deciding between 100% custom and using fireauth. I need the social sign-in in my flutter apps.


r/FastAPI • • Jul 07 '25

Question How to implement sorting, filtering and pagination in FastAPI

30 Upvotes

Hi guys, I'd like to know to implement that stuff with SQLAlchemy/SQLModel, if there is a tutorial that you can share or repos to give me ideas, would be perfect. FastAPI docs don't show anything about this.


r/FastAPI • • Nov 24 '24

Question actual difference between synchronous and asynchronous endpoints

30 Upvotes

Let's say I got these two endpoints

@app.get('/test1')
def test1():
    time.sleep(10)
    return 'ok'

@app.get('/test2')
async def test2():
    await asyncio.sleep(10)
    return 'ok'

The server is run as usual using uvicorn main:app --host 0.0.0.0 --port 7777

When I open /test1 in my browser it takes ten seconds to load which makes sense.
When I open two tabs of /test1, it takes 10 seconds to load the first tab and another 10 seconds for the second tab.
However, the same happens with /test2 too. That's what I don't understand, what's the point of asynchronous being here then? I expected if I open the second tab immediately after the first tab that 1st tab will load after 10s and the 2nd tab just right after. I know uvicorn has a --workers option but there is this background task in my app which repeats and there must be only one running at once, if I increase the workers, each will spawn another instance of that running task which is not good


r/FastAPI • • May 25 '24

pip package I made a file-based router for FastAPI because I like to watch the world burn.

30 Upvotes

Hello! Python & FastAPI were my first foray into programming, over the past year i worked a lot with sveltekit, and as much as some people might hate it I LOVE file based routing! with slugs and stuff, makes it easier to organize stuff in my mind.

So I built it! check it out and let me know what you think :)

pip install fastapi-file-router

https://github.com/Bewinxed/fastapi-file-router

https://pypi.org/project/fastapi-file-router

Usage

from fastapi import FastAPI
from fastapi_file_router import load_routes

app = FastAPI()

load_routes(app, "routes", verbose=True)

Route Structure

📁 project_root/
├ 📁 api/  # This folder is set as the directory in the load_routes function
│ ├ 📄route.py   # Translates to /api (base route of the directory)
│ ├ 📁 users/
│   │ ├ 📄route.py   # /api/users
│   │ ├ 📄[user_id].py  # /api/users/{user_id}
│   │ └ 📄route.py   # /api/users/profile
│   │
│ ├ 📁 products/
│   │ ├ 📄route.py   # /api/products
│   │ └ 📁 [product_id]/
│   │  ├ 📄route.py   # /api/products/{product_id}
│   │  └ 📄reviews.py # /api/products/{product_id}/reviews
│   │
│ └ 📁 settings/
│  ├ 📄route.py   # /api/settings
│  └ 📁 notifications/
│      ├ 📄route.py  # /api/settings/notifications

Enjoy!


r/FastAPI • • Feb 19 '23

Tutorial MVC & Layered FastAPI Boilerplate

30 Upvotes

Hey guys! I am fairly new to the FastAPI club. I really like the framework, it had a lot of room for customisation. I am big fan of MVC pattern and layered architecture. I have found great boilerplates but I thought I could build one with batter structure and scalability. That’s what I did.

https://github.com/OysterHQ/FastAPI-Production-Boilerplate

I added documentation to the readme and it also has tests! (Didn’t find them in other templates)


r/FastAPI • • Feb 25 '21

Deploying FastAPI apps with HTTPS powered by Traefik by Sebastián Ramírez, creator of FastAPI

Thumbnail
youtube.com
30 Upvotes

r/FastAPI • • Jan 04 '21

pip package I published a package for FastAPI which automatically generates and documents CRUD routes for your models.

Thumbnail
fastapi-crudrouter.awtkns.com
30 Upvotes

r/FastAPI • • May 05 '26

feedback request I create my first big fastapi project

29 Upvotes

before this I did a lot of small projects but now I've finally made a really good and big project that I really like the structure of. I did it with a friend, and I want to find feedback and see how well-structured it is.

Github: https://github.com/doorhanoff/fastapi_shop


r/FastAPI • • Apr 20 '26 Heartwarming

pip package I got tired of rebuilding OAuth for FastAPI projects, so I made a small CLI for it

29 Upvotes

Nothing new here, a while ago I needed to add OAuth login to a FastAPI project. [REPO]

But as u know: I kept running into the same setup work:

- redirect URI mismatches
- provider-specific config
- state handling
- callback routes
- env variables
- example code that was either too abstract or incomplete

So I spent some time turning the setup I kept rewriting into a small open-source package: [REPO]

Install:

pip install oauth-for-dummies

Then inside a FastAPI project:

oauth-init

It scaffolds:

- oauth_config.py
- oauth_routes.py
- oauth_example_app.py
- .env template

Right now it supports GitHub and Google OAuth.

The goal is not to replace serious production auth platforms. It is more for prototypes, internal tools, learning projects, and people who want readable OAuth code they can actually modify. I kinda use this a lot to build internal applications at work: hence this is super useful for me. And it literally solves most of the "auth" part of any application, and I never build the user database or store passwords (for internal tools I meant)

I’d appreciate feedback from users, this was just a quick impromptu build. Just wanted to share this to help anyone who finds this useful,

And yes: i can add the 2.1 requirement almost easily too.


r/FastAPI • • Jan 28 '26

Other Benchmarking Popular Async Python Web Frameworks

29 Upvotes

Hi everyone,

I’ve published a repository for benchmarking several popular asynchronous Python web frameworks. The goal was to evaluate them under a realistic setup using a standard stack: SQLAlchemy and Pydantic.

The repository, along with detailed results, is available here:
https://github.com/sidtn/python_web_frameworks_perf_test

Based on my measurements, Sanic + Granian achieved the highest performance, followed closely by FastAPI + Granian. The differences are relatively small, but consistent.

One important observation: if performance is a priority, the choice of server (WSGI/ASGI) often has a greater impact than the choice of framework itself. In these tests, switching to Granian provided a significant boost regardless of the framework.

Feel free to check out the setup, run your own benchmarks, and share your findings.


r/FastAPI • • Jan 21 '26

Other LogicPaper: A self-hosted document automation engine (FastAPI + LibreOffice + Redis). Turn Excel/JSON into PDFs using Jinja2

Thumbnail
gallery
29 Upvotes

Greetings!

I'd like to share a tool I developed called LogicPaper. It’s an open-source document automation engine designed to merge structured data with templates to generate files in bulk.

What it does: You upload a template (e.g., Word .docx) using Jinja2 placeholders (like {{ client_name | format_string('title') }}) and a dataset (Excel or JSON). LogicPaper processes every row and generates a corresponding filled document for each one.

Why I built it: I needed a way to generate hundreds of contracts and reports without manual copy-pasting. It was built to solve a problem at my work, but since I created it in my free time, I decided to make it open source. It fits any workflow that needs standardized docs populated with variable data.

Key Features:

  • Multi-Format: Supports output to .docx, .pptx, .md, and .txt.

  • Multi-Template Mapping: You can generate multiple file types (e.g., a Contract, a Slide Deck, and a Summary) from a single data row at once.

  • PDF Conversion: Includes a headless LibreOffice instance to automatically convert the generated Office files to PDF.

  • Asynchronous Batch Processing: Handles large datasets via background workers to prevent request timeouts.

  • Integration Ready: It features an API, making it easy to trigger from other self-hosted tools or CRMs.


It is containerized and ready to deploy. I hope this helps someone :)

GitHub Repo: https://github.com/rubensbraz/logicPaper/

Placeholders Documentation: https://rubensbraz.github.io/LogicPaper/help.html


r/FastAPI • • Dec 31 '25

feedback request I built a split-screen HTML-to-PDF editor on my API because rendering the PDFs felt like a waste of money and time

29 Upvotes

I’ve spent way too many hours debugging CSS for PDF reports by blindly tweaking code, running a script, and checking the file.

So I built a Live Template Editor for my API.

What’s happening in the demo:

  1. Real-Time Rendering: The right pane is a real Headless Chrome instance rendering the PDF as I type.

  2. Handlebars Support: You can see me adding a {{ channel }} variable, and it updates instantly using the mock JSON data.

  3. One-Click Integration: Once the design is done, I click "API" and it generates a ready-to-use cURL command with the template_id.

Now I can just store the templates in the dashboard and send JSON data from my backend to generate the files.

It’s live now if you want to play with the editor (it's within the Dashboard, so yes, you need to log in first, but no CC required, no nothing).


r/FastAPI • • Dec 06 '25

feedback request I built a mock payment gateway so I could stop worrying about Stripe test mode limits

29 Upvotes

Hey everyone! Got tired of running into Stripe test mode restrictions while building my side projects, so I made AcquireMock - basically a fake payment processor you can run locally.

What it does:

  • Creates payment pages with actual card forms (only accepts 4444 4444 4444 4444 though lol)

  • OTP verification via email

  • Webhooks with HMAC signatures

  • Saves cards for returning users

  • All the boring stuff like CSRF protection, rate limiting, etc.

Tech stack: FastAPI(with jinja2) + PostgreSQL + SQLAlchemy + PyDantic + vanilla JS (no React bloat). Tried to keep it simple.

Some features I'm actually proud of:

  • Works without email config (just logs OTP to console)

  • Dark mode that doesn't look like shit

  • 4 languages (UK/EN/DE/RU)

  • Docker compose setup that actually works first try

It's on GitHub if you want to check it out:https://github.com/ashfromsky/acquiremock

Not trying to compete with Stripe's actual mock - this is more for when you need something that runs completely offline or you're teaching people how payment flows work.

Would love feedback, especially on the webhook retry logic - not sure if I'm doing that part right.


r/FastAPI • • Feb 08 '25

Question Is it possible to Dockerize a FastApi application that uses multiple uvicorn workers?

29 Upvotes

I have a FastAPI application that uses multiple uvicorn workers (that is a must), running behind NGINX reverse proxy on an Ubuntu EC2 server, and uses SQLite database.

The application has two sections, one of those sections has asyncio multithreading, because it has websockets.

The other section, does file processing, and I'm currently adding Celery and Redis to make file processing better.

As you can see the application is quite big, and I'm thinking of dockerizing it, but a docker container can only run one process at a time.

So I'm not sure if I can dockerize FastAPI because of uvicorn multiple workers, I think it creates multiple processes, and I'm not sure if I can dockerize celery background tasks either, because I think celery maybe also create multiple processes, if I want to process files concurrently, which is the end goal.

What do you think? I already have a bash script handling the deployment, so it's not an issue for now, but I want to know if I should add dockerization to the roadmap or not.


r/FastAPI • • Jul 18 '24

Tutorial Fast(er)API: Optimizing Processing Time:A few tips to make FastAPI go faster.🚀

Thumbnail fabridamicelli.github.io
29 Upvotes

r/FastAPI • • Jan 04 '24

Other SOLID web api with FastAPI

29 Upvotes

I have been working with FastAPI for some time and what attracted me to it is that it's async ready and very flexible and un-opinionated. I architected a skeleton that has been used in production for a couple of projects and I want to share it with the community.

The skeleton follows the SOLID principles and uses decoupled service modules. The data layer is just a dependency, thus allowing any kind of persistance layer (sql, no-sql, files, etc). The whole architecture has at its foundation concepts such as interfaces, dependency injection and inversion of control, making everything here (including the API layer) a module.

The project is available here https://github.com/smileservices/async-solid-web-api and i'm available for clarifications and questions. It's open for contributors if you have something to improve.


r/FastAPI • • May 22 '23

pip package FastDepends - FastAPI Dependency Injection system extracted from FastAPI and cleared of all HTTP logic

29 Upvotes

Hello everyone!

As part of the implementation of my own framework for working with message brokers (Propan), I needed to implement a type conversion system based on pydantic, as well as a lightweight dependency management system similar to FastAPI Depends.

Thus, I shamelessly cut off this functionality from the FastAPI and pack it into a separate python library - FastDepends. It allows you to use a decorator to validate incoming function arguments using pydantic and resolve Depends.

All HTTP-related logic has been removed from the package, support for synchronous code has been added, as well as the ability to create your own classes that will be resolved in the way you need.

If you want to embed a piece of FastAPI into your legacy project using another asynchronous or even synchronous framework, you may be interested in FastDepends. You can also use it to write your own libraries.

Link to the FastDepends repo: https://github.com/Lancetnik/FastDepends

The Propan framework, for which I had to implement this library: https://github.com/Lancetnik/Propan


r/FastAPI • • Mar 11 '23

feedback request FastKafka - free open source python lib for building Kafka-based services

29 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.

Please take a look and tell us how to make it better. Our goal is to make using it as easy as possible for some how has experience with FastAPI.

https://github.com/airtai/fastkafka


r/FastAPI • • May 25 '21

Other ThoughtWorks adds FastAPI to the Technology Radar

Thumbnail
thoughtworks.com
29 Upvotes

r/FastAPI • • May 27 '26

Other Looking for a Fastapi coding buddy

28 Upvotes

Hey everyone!

I’ve been developing with FastAPI for the past couple of months and I’m looking for a coding buddy to exchange experience with and collaborate on projects. If you’re interested, here’s one of my recent projects on GitHub:
https://github.com/doorhanoff/light_memory
upd: sorry, i forgot to make this repo public, now its ok


r/FastAPI • • Apr 03 '26

Question How are you actually managing background/async tasks in FastAPI in production?

28 Upvotes

I’ve been building with FastAPI for a while now and I’m curious how people are really handling background work beyond simple demos.

The docs show BackgroundTasks, but that feels pretty limited once things get even slightly complex.

Some situations I keep running into:

  • sending emails, notifications, webhooks

  • retrying failed tasks

  • long running async jobs

  • tasks that depend on other tasks

  • needing visibility into what’s running or failing

Right now it feels like there are a few options:

  • stick with BackgroundTasks

  • use something like Celery or RQ

  • or just push everything into a message broker

But none of these feel very “FastAPI-native” or simple.

So I’m wondering:

  • What are you using in production?

  • Are you staying fully async or mixing in workers?

  • How are you handling retries and failures?

  • Do you have any visibility into tasks or is it just logs and hope?

Would be interesting to hear what actually works in real systems, not just tutorials.


r/FastAPI • • Mar 25 '26

Other We launched 2 weeks ago and already have 40 developers collaborating on projects

28 Upvotes

Hey everyone,

About two weeks ago, we launched a platform with a simple goal: help developers find other developers to build projects together.

Since then, around 50 users have joined and a few projects are already active on the platform, which is honestly great to see.

The idea is to create a complete space for collaboration — not just finding teammates, but actually building together. You can match with other devs, join projects, and work inside shared workspaces.

Some of the main features:

- Matchmaking system to find developers with similar goals

- Shared workspaces for each project

- Live code editor to collaborate in real-time

- Reviews, leaderboards, and profiles

- Friends system and direct messaging

- Integration with GitHub

- Activity tracking

- Recently added global chat to connect with everyone on the platform

We’re trying to make it easier for developers to go from idea to actually building with the right people.

Would love to hear what you think or get some early feedback.

https://www.codekhub.it/


r/FastAPI • • Oct 04 '25

Tutorial 6.Python | FastAPI | Clean Architecture | Setup SQLAlchemy

Thumbnail
youtu.be
28 Upvotes

🚀 Master FastAPI with Clean Architecture! In this introductory video, we'll kickstart your journey into building robust and scalable APIs using FastAPI and the principles of Clean Architecture. If you're looking to create maintainable, testable, and future-proof web services, this tutorial is for you!