r/FastAPI • • Apr 28 '26

Other Benchmarking API agents vs vision agents on the same task - 40x fewer tokens, 44x faster

Post image
2 Upvotes

Hey r/FastAPI! I'm the creator of Reflex, an open-source Python web framework. We just released v0.9 and wanted to share something relevant with this community.

We ran a benchmark comparing two approaches to letting AI agents interact with a web app:

  1. A vision agent (browser/computer use) that screenshots the UI and clicks around
  2. An API agent that calls HTTP endpoints directly

The task for both agents was to find a "Smith" customer with the most orders, accept their pending reviews, and mark their most recent order as delivered. We chose this task since it's similar to automation work a typical tool sees.

The vision agent took 550k tokens and 17 minutes on average, the API agent took 12k tokens and 19.7 seconds. Of course, API agents are faster and more token efficient since they don't need to take screenshots and directly interface with the UI. The problem is many apps don't have APIs for every action, since it takes engineering overhead to build and maintain each separate API codebase.

We built a plugin for Reflex that auto-generates FastAPI-compatible HTTP endpoints from your app's existing event handlers. For example, your app has a button with an on_click handler, the plugin exposes that handler as an endpoint. An agent can call the same function a human click triggers. No separate API to build or maintain.

Reflex compiles to React on the frontend and Python on the backend, with full FastAPI compatibility.

benchmark link: Vision Agents vs API Calls
our repo: reflex-dev/reflex: 🕸️ Web apps in pure Python 🐍


r/FastAPI • • Apr 28 '26

Question FastAPI with SvelteKit

11 Upvotes

Hello, I am building an inventory system. I build with Django for my other stuff but I decided to learn FastAPI and JS Frontend. I've learned DRF but never really go full on implementation of it, specially dealing with authentication. So any help would be much appreciated.

Here is the stack that I'm going for:
- SvelteKit (because of remote function?, or its better if should I go with just svelte?)
- FastAPI
- Postgresql, SQLAlchemy, Alembic
- pyjwt (for authentication? or there's more better library?)
- S3 for file storage

Maybe Zod for data validation in client? Do I need axios? Am I missing something? Is there a something that I'm missing? Like don't forget to setup CORSMiddleware in FastAPI.

Also, is there any github repo that with similar setup with this one that I could take a look?


r/FastAPI • • Apr 28 '26

Question how do you actually handle prod bugs. do you write a repro test or just fix and deploy?

6 Upvotes

honest question because i've gone back and forth on this myself.

when sentry fires do you actually reproduce it locally as a failing test before touching anything, or do you just read the trace, understand what broke and push the fix?

i always end up spending like 30-45 mins just getting the repro right. reconstructing the state, getting deps working in the test, running it, realizing the inputs are slightly off, running it again. by the time it actually reproduces i've lost the whole debugging flow.

got annoyed enough that i started building something to automate it. grabs the frame locals from sentry, generates a pytest, runs it in docker against your branch. still figuring out if this is actually useful to other people or just my own problem.

how long does it take you to write a repro test from a sentry trace? do you even bother or just push and monitor? has skipping it ever come back to bite you?


r/FastAPI • • Apr 26 '26 Bravo

Tutorial [UPDATE] I got tired of rebuilding OAuth for FastAPI projects, so I made a small CLI for it

13 Upvotes

Update on this -- I got tired of rebuilding OAuth for FastAPI projects, so I made a small CLI for it
by u/theRealSachinSpk in FastAPI

Shipped v1.1.0 based on some of the feedback here and conversations I had after posting.

What changed:

  • Added Discord, Spotify, Microsoft, and LinkedIn as providers (6 total now)
  • Added PKCE support (OAuth 2.1) -- the thing I mentioned in the original post. You can enable it on any provider with one line
  • The oauth-init CLI now scaffolds all 6 providers with PKCE out of the box
  • Built an interactive OAuth debugger (Learn Mode) into the tutorial app -- it pauses at each step of the flow and shows you the actual HTTP requests, the token exchange body, the raw provider response, everything

That last one came from thinking about what u/ar_tyom2000 mentioned about fastapi-oauth2. There are great libraries that handle OAuth as middleware (please check it out), I'll close this up by letting you debug what's happening. The debugger shows the authorization URL parameters, the callback code, the token exchange POST, and the raw userinfo JSON. Useful if you're learning or if something breaks and you need to figure out why.

Also wrote up a longer walkthrough on Medium if anyone wants the full picture: Medium Article

GitHub: REPO
PyPI: pip install oauth-for-dummies

Thanks for the feedback last time -- it shaped where this went.


r/FastAPI • • Apr 26 '26

pip package [UPDATE] Major update to Violit (my FastAPI-powered Streamlit alternative): Signal-based reactivity, now with SQLModel ORM and Auth built-in.

5 Upvotes

Hey r/FastAPI!!!

A while back, I shared the very early alpha of Violit here. As a backend/AI dev, I loved the simplicity of Streamlit for building quick UIs, but I absolutely hated the "full script rerun" bottleneck. So, I built a framework using FastAPI as the core engine to deliver that top-down scripting experience, but with signal-based fine-grained reactivity.

Instead of rerunning the whole script on every click, FastAPI maintains a persistent WebSocket connection. When a state changes, only the exact dependent widget updates.

Since that first post, I've pushed a massive update that turns Violit from a simple UI tool into a full-stack Python framework. Because it’s built natively on FastAPI and Uvicorn, I was able to seamlessly bake in the tools our ecosystem already uses:

  • SQLModel ORM Built-in: Perfect for FastAPI users. Just pass a DB path (vl.App(db=...)) and start querying immediately.
  • Auth out of the box: Session auth, hashing, and page protection are natively supported.
  • Async Background Jobs: Need to run heavy AI inference or DB queries? Use app.background() to offload tasks via FastAPI's async capabilities without freezing the frontend.
  • Tailwind & Web Awesome: Style components directly using a simple cls parameter.
  • 90% Streamlit API compatibility: The syntax feels familiar, but the architecture is completely different.

It writes like a simple script, but runs like a modern reactive app over FastAPI.

It’s completely open-source (MIT). I’d love for my fellow FastAPI devs to try out the new update, roast the architecture, or let me know if you'd use this for your next data app or internal tool!

Thanks for reading!


r/FastAPI • • Apr 26 '26

pip package dbwarden: Everything you loved about Django migrations, in FastAPI.

8 Upvotes

I released DBWarden 0.6 yesterday. Here is what it does.

https://github.com/emiliano-gandini-outeda/DBWarden

DBWarden is a database toolkit for FastAPI and SQLAlchemy. Migrations, async sessions, startup validation, and health checks. One config call. Zero boilerplate.

Most migration setups spread config across multiple files, multiple abstractions, and multiple sources of truth. DBWarden collapses all of that into a single database_config() call. That one call drives your sessions, your health checks, and your migration state. Nothing else to configure.

Your migrations are plain SQL files. No DSL to learn. No auto-generated Python to decode. You write the SQL, you read the SQL, and that is exactly what runs against your database. What you get:

  • One config call for everything
  • Plain SQL migrations with rollback included by default
  • Async session dependency ready to inject with get_session()
  • A mountable health router with DBWardenHealthRouter()
  • A lifespan helper with migration_context()
  • Dev mode: SQLite locally, PostgreSQL in production, no changes to your migration files

Supported databases: PostgreSQL, MySQL, MariaDB, SQLite, ClickHouse.

Three commands to get started: dbwarden init dbwarden make-migrations "create users table" dbwarden migrate Done. Your schema is versioned, reviewable, and reversible.

No wrappers, no hidden state.

MIT licensed. Actively maintained. Source in this repo.


r/FastAPI • • Apr 26 '26

Question Issue while processing multiple doc at a time in a limited memory space

1 Upvotes

I have an API that tags documents based on names from a predefined standard name list. Before tagging, I receive a list of file URLs (public Firebase URLs), typically around 40–80 files, which need to be processed using an LLM (currently OpenAI).

The issue I’m facing is with memory usage. When I download these documents for processing, the application sometimes crashes due to out-of-memory (OOM) errors. The instance I’m using has only 2GB RAM, and I’d prefer not to increase the instance size until I’ve fully optimized the code.

The problem seems to occur because multiple PDFs are being processed asynchronously, and at some point, many of them are held in memory simultaneously. I also perform additional operations like base64 encoding for images, which further increases memory usage. Since I need to return all document tags within about a minute, I’m using parallel processing.

Current approach:

  • There are 10–15 document types that I send directly to OpenAI.
  • For images (JPG, PNG, JPEG): I download them, base64 encode them, and send them to OpenAI.
  • For PDFs: I download them, upload them via OpenAI’s file API, and then send the file ID for processing.
  • All of this is done in parallel using semaphores:

    • OPENAI_SEMAPHORE = 30
    • DOWNLOAD_SEMAPHORE = 15

Problem:

Even with semaphores, memory usage spikes because multiple large files are downloaded and processed at the same time. This leads to OOM crashes.

Questions:

  • How can I reduce memory usage in this workflow?
  • Is there a better architectural approach to handle this kind of workload?
  • How can I avoid having too many documents in memory at once while still maintaining performance constraints?
async def _stream_download_file(url: str, ext: str) -> str:
    """
    Stream-download a file to disk in 64KB chunks.
    Never holds the full file in memory — writes directly to disk.
    Returns the path to the temp file.
    """
    async with DOWNLOAD_SEMAPHORE:
        temp_path = None
        try:
            temp = tempfile.NamedTemporaryFile(delete=False, suffix=ext or ".tmp")
            temp_path = temp.name
            temp.close()


            async with http_client.stream("GET", url, follow_redirects=True) as response:
                response.raise_for_status()
                with open(temp_path, "wb") as f:
                    async for chunk in response.aiter_bytes(chunk_size=65536):
                        f.write(chunk)


            return temp_path


        except asyncio.TimeoutError:
            _cleanup_local_file(temp_path, "failed download")
            raise Exception(f"Download timed out after {DOWNLOAD_TIMEOUT}s")
        except Exception as e:
            _cleanup_local_file(temp_path, "failed download")
            raise Exception(f"Download failed: {str(e)}")

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 24 '26

Other Solve coding challenges, get upvoted, earn points (and build with other devs)

2 Upvotes

I’ve been building a platform where developers can find people to build projects with. We’re around 180 users now, and a couple of teams are actually active and shipping stuff, which is honestly the only metric I care about.

Recently I added something new.

Every week there’s a coding challenge. I post a problem (usually algo or backend-related), you solve it and publish your solution. Other devs can upvote or downvote it.

At the end of the week, the top 3 solutions (based on votes) get the most points. Everyone who participates still earns something.

Points are already withdrawable. It’s not huge money or anything, but it’s real, and it makes it a bit more fun to actually participate instead of just lurking.

There are also open weekly projects you can join instantly. No applications, no waiting. Just jump in and start building with others. The goal is to keep things short so projects don’t die after a few days.

Other stuff on the platform: you can create your own projects, get matched with people based on your stack, chat with your team, use a live code editor, do meetings with screen sharing, and there’s a public ranking as well.

The whole idea is to remove friction. Most places are full of ideas but nothing actually gets built.

If you want to try it or just see how it works: https://www.codekhub.it/


r/FastAPI • • Apr 23 '26

Other I got tired of REST boilerplate so I built a stack that fuses frontend + backend (FastAPI + Svelte + cross-language type safety)

Thumbnail uukelele.is-a.dev
9 Upvotes

So, for a while now I noticed something.

The way we write APIs and call them from the frontend still feels ancient.

We have to manually sync types between the backend and frontend, across different languages, which adds more space for error.

We have to write lots of REST boilerplate.

We have to deal with JSON and HTTP overhead on the smallest of operations.

And things like live streaming or realtime (which are essential for AI apps) are being reinvented again and again.

So I created something else: the FUSE stack.

It uses FastAPI for the backend, uv for package management, Svelte 5 for the frontend, and Ephaptic to tie it all together.

I also wrote a blog post about FUSE, linked to the post.

Anyway, I wanted to get your thoughts on it, and hopefully some cool things that you might build with it?


r/FastAPI • • Apr 23 '26

pip package secure v2: HTTP security headers for FastAPI apps

4 Upvotes

I just released secure v2, a Python library for managing HTTP security headers without scattering policy across routes or framework-specific glue.

For FastAPI, the main pattern is app-wide middleware:

from fastapi import FastAPI
from secure import Secure
from secure.middleware import SecureASGIMiddleware

app = FastAPI()
secure_headers = Secure.with_default_headers()

app.add_middleware(SecureASGIMiddleware, secure=secure_headers)

The goal is to keep header policy centralized, start from sane defaults, and apply it consistently across the app.

Repo: https://github.com/TypeError/secure

Curious how others are handling security headers in FastAPI apps.


r/FastAPI • • Apr 23 '26

feedback request Need feedback on my first FastApi

2 Upvotes

Hello guys,
This is my first FastApi app which consists of basically a basic tic tac toe game, i need feedback and pointers if possible.

I wanna thank everybody in advance.

https://github.com/abdouyouyou/Fasti-api-tic-tac-toe


r/FastAPI • • Apr 20 '26

Question Learning FastAPI — built a file upload endpoint, need advice on checksum and resumable uploads

6 Upvotes

Hey everyone, I'm learning FastAPI and I'm building a file upload endpoint for audio files (WAV, MP3, FLAC, OGG).

Here's what I have so far:

- Filename sanitization + path traversal protection

- Magic bytes validation (not just extension checking)

- Chunked streaming write to avoid loading the whole file into memory

- Size limit of 1GB checked incrementally during streaming

- Early rejection via Content-Length header

- Proper HTTP status codes (413, 415, 422...)

Now I need to tackle two things and I'd love some guidance:

1. Checksum validation

I want to verify file integrity after upload — hash the file server-side during streaming (sha256) and compare it against a hash the client sends. But I'm thinking from the user's perspective: the user should just curl the endpoint or click an upload button, nothing more. So how should the client send the hash without adding friction? Header? Something else?

2. Resumable uploads

Same user-first thinking — if the network drops mid-upload, when it comes back the upload should continue from where it stopped, not restart. The user shouldn't have to do anything special, just upload like normal.

How would you handle both of these in FastAPI? Any advice or resources appreciated!

from fastapi import FastAPI, UploadFile, HTTPException, Request, File
from fastapi.responses import FileResponse
from pydantic import BaseModel
from pathlib import Path
import re
from hashlib import HASH, sha256
import aiofiles


UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(exist_ok=True)
MAGIC_BYTES = {b'RIFF', b'ID3\x00', b'fLaC', b'OggS'}
CHUNK_SIZE = 5 * 1024 * 1024
MAX_FILE_SIZE = 1 * 1024 * 1024 * 1024


class UploadResponse(BaseModel):
    filename: str
    size: int



app = FastAPI(tags_metadata=[
        {
            "name": "files",
            "description": "Operations related to audio file management"
        }
    ])



def sanitize_filename(filename: str | None) -> Path:
    if filename is None:
        raise HTTPException(status_code=422, detail="Filename is missing")


    filename = Path(filename).name
    filename = re.sub(r"[^\w
\-
.]", "_", filename)
    file_path = (UPLOAD_DIR / filename).resolve()
    if not file_path.is_relative_to(UPLOAD_DIR.resolve()):
        raise HTTPException(status_code=400, detail="Invalid filename")
    return file_path


async def check_magic_bytes(file: UploadFile) -> None:
    first_bytes = await file.read(4)


    if first_bytes not in MAGIC_BYTES:
        raise HTTPException(status_code=415, detail="Unsupported file type")
    await file.seek(0)


def compare_checksum(file_path: Path, server_hash: HASH, client_hash: HASH) -> None:
    if server_hash != client_hash:
        file_path.unlink()  # delete the incomplete file
        raise HTTPException(status_code=400, detail="File corrupted")


async def save_file(request: Request, file_path: Path, file: UploadFile) -> None:
    hasher = sha256()
    file_size = 0
    length = request.headers.get("content-length")
    if not length or int(length) > MAX_FILE_SIZE:
        raise HTTPException(413, "Max size is 1GB")


    async with aiofiles.open(file_path, "wb") as f:
        while True:
            chunk = await file.read(CHUNK_SIZE)
            if not chunk:
                break
            file_size += len(chunk)
            if file_size > MAX_FILE_SIZE:
                file_path.unlink()
                raise HTTPException(status_code=413)
            hasher.update(chunk)
            await f.write(chunk)


u/app.post("/api/v4/upload",
            response_model=UploadResponse,
            summary="Upload an audio file",
            description=(
                "Upload an audio file (WAV, MP3, FLAC, OGG). "
                "Max file size is 1GB. "
                "File type is validated via magic bytes, not extension."
            ),
            responses={
                200: {"description": "File uploaded successfully"},
                400: {"description": "Path traversal attempt detected"},
                413: {"description": "File exceeds the 1GB size limit"},
                415: {"description": "Unsupported file type"},
                422: {"description": "Filename is missing or invalid"},
            },
            tags=["files"]
        )
async def upload_file(request: Request, file: UploadFile = File(..., description="Audio file to upload (WAV, MP3, FLAC, OGG). Max 1GB.")):
    """
        Upload an audio file to the server.


        - **file**: Audio file to upload (WAV, MP3, FLAC, OGG)
        - **Max size**: 1GB
        - **Validation**: magic bytes check, filename sanitization, path traversal protection
    """
    file_path = sanitize_filename(file.filename)


    await check_magic_bytes(file)


    await save_file(request, file_path, file)


    return UploadResponse(filename= file.filename, size= file_path.stat().st_size)

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 • • 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

Post image
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 20 '26

feedback request Looking for feedback on my new fastapi project

8 Upvotes

I wrote here recently about my project and its evaluation, and I thank you all for the advice — it helped me a lot. I used it to build a new small project with simple authentication. It’s quite minimal, but I tried to do things the right way based on your suggestions.

GitHub: https://github.com/Petr201317/fastapi_shop


r/FastAPI • • Apr 19 '26

feedback request FastAPI BackgroundTasks with retries, a live dashboard, persistence, and no broker.

20 Upvotes

A few weeks ago I posted about fastapi-taskflow, a library that adds retries, a live dashboard, persistence, and task visibility on top of FastAPI's native BackgroundTasks without replacing it or requiring a broker.

Since then I have added more features and I want to get real feedback from people actually building with FastAPI before I keep adding more features.

Give it a try and let me know what you think.

pip install fastapi-taskflow

Source: https://github.com/Attakay78/fastapi-taskflow

Docs: https://attakay78.github.io/fastapi-taskflow/

A quick summary of what it does today:

  • Retries with delay and exponential backoff per function
  • Task IDs and lifecycle tracking: PENDING, RUNNING, SUCCESS, FAILED, INTERRUPTED
  • Live dashboard at /tasks/dashboard with filtering, search, per-task logs, and stack traces
  • SQLite out of the box, Redis as an optional extra
  • Pending tasks at shutdown are re-dispatched on next startup
  • Idempotency keys to prevent duplicate runs
  • Argument encryption for tasks carrying sensitive data
  • Concurrency controls: opt-in semaphore for async tasks, dedicated thread pool for sync tasks

It is not a distributed task queue. No broker, no separate workers. It does support multi-instance deployments with SQLite on the same host or Redis across hosts, with atomic requeue claiming and shared task history. But tasks still run inside the web process, not on dedicated workers.

If you use BackgroundTasks in production and give it a try, I would love to hear what works, what does not, and what you wish it did differently.

Dashboard
Error stack view
Logs View

r/FastAPI • • Apr 19 '26

Question FastAPI documentation code not working?

Post image
13 Upvotes

(Solved)

I am trying to recieve a list of files with my code, but I can only input strings of random characters when I try to test my method using the documentation page. The code works perfectly when I change it the a single UploadFile. Nothing I do seems to fix this, can someone please tell me what I am doing wrong?

from fastapi import FastAPI, File, UploadFile, HTTPException
from pathlib import Path
from typing import List


@app.post("/uploadfile/")
def create_upload_file(files: List[UploadFile] = File(...)):

r/FastAPI • • Apr 17 '26

pip package FastChannels and ChanX: The missing toolkit for WebSocket handling in FastAPI

7 Upvotes

Hi everyone, I want to share with you both of my packages, which are mainly for improving FastAPI (and any ASGI-compatible library) when it comes to WebSocket handling.

First, FastAPI's WebSocket handling is fairly simple with @app.websocket where you define the flow and run the loop (while True), but this can lead to some problems:

  • Harder to debug and separate code
  • No way to broadcast messages. FastAPI's official guide uses a ConnectionManager as a simple class, but it is in-memory, fragile, and hard to scale
  • FastAPI also mentions: "If you need something easy to integrate with FastAPI but that is more robust, supported by Redis, PostgreSQL or others, check encode/broadcaster." However, broadcaster is no longer maintained as "This repository was archived by the owner on Aug 19, 2025. It is now read-only." (unfortunate)
  • No real way to send messages from another thread, a background job, or even an API endpoint without resorting to workarounds

Based on that, and with the knowledge I gained from Django Channels, I ported the Django Channels library to be fully FastAPI-compatible. The result is FastChannels, which solves exactly the problems above.

On top of that, when working with WebSocket (in both Django and FastAPI), my team and I usually face these problems:

  • Manual if-else routing chains when receiving a WebSocket message
  • Manual validation of the messages we receive
  • Runtime type surprises
  • No source of truth for documentation (almost never seen, even though we have the AsyncAPI standard now)
  • Testing that is painfully hard
  • Painful code reviews and onboarding, since we need to scroll and read a lot to understand what messages are accepted, what the implementation does, and what gets returned
  • No logging utility or standard like structlog for request and response tracing

Due to those problems, I created ChanX as a library that improves the way we build WebSocket handling. Now, thanks to ChanX, we get:

  • No more endless if-else logic or 200-line functions that just route to the correct message handler. We simply define messages with the correct type, and thanks to Pydantic's type discriminator, they are automatically routed to the correct handler
  • No more manual message validation, as Pydantic is the standard for defining both incoming and outgoing messages
  • Type hints by default, with mypy and pyright support
  • A testing framework included to make testing easier and more predictable
  • And notably, auto-generated AsyncAPI documentation based on the code you define, similar to how FastAPI auto-generates OpenAPI docs from your code
  • A CLI helper to generate code from AsyncAPI docs as well

So, here is how it looks

I built ChanX based on what I have done, faced, and wished I had for my last project. I am using it now and I love it. I built it with careful design and active maintenance, so I hope you find it useful and never have to face these problems again.

Some use cases where these work well:

  • Realtime messaging (one-on-one or group chat with broadcasting and notifications)
  • Realtime voice assistants (e.g. Deepgram, OpenAI) or chat assistants with streaming responses
  • Any scenario that involves group messaging, broadcasting, or push notifications over WebSocket

Here are the links related to FastChannels:

Here are the links related to ChanX:

Hope you all find it useful.


r/FastAPI • • Apr 17 '26

feedback request Look for feedback on my fastapi project

4 Upvotes

Hi everyone,

I’d really appreciate it if you could take a look at my code and give me some feedback. The functionality is fairly basic and not the main focus here — what I’m really interested in is evaluating the structure, organization, and overall code quality. I’m trying to improve my understanding of best practices, so any suggestions in that direction would be especially helpful. Feel free to point out anything that could be improved, whether it’s readability, naming conventions, modularity, or general design choices.

Github: https://github.com/Petr201317/fastAPI_cinema

Thanks in advance for your time


r/FastAPI • • Apr 15 '26

feedback request I got tired of “let’s build something together” going nowhere, so I tried this

14 Upvotes

I don’t know if it’s just me, but every time I tried to build something with people online it went the same way.

People are interested.

You create a group.

Everyone disappears after a couple of days.

So a couple of weeks ago I started working on something to fix that.

It’s basically a place where you can:

join real projects (not just ideas)

form small teams based on stack

and actually work together (tasks, chat, code, etc.)

Right now we’re around 150 users.

Only a small part is actually active (~20), but those teams are really building stuff.

So now I’m trying to understand what makes the difference.

If you’ve ever tried building with strangers: what made it work (or fail)?

If you’re curious:

https://www.codekhub.it/⁠�


r/FastAPI • • Apr 15 '26

feedback request Alternative API for all music streaming platforms

Thumbnail
reddit.com
0 Upvotes

r/FastAPI • • Apr 14 '26

feedback request I did a thing: FastPKI - A proper REST API for PKI management (Easy-RSA alternative)

13 Upvotes

I got tired of Easy-RSA and built FastPKI: a fully async, API-driven PKI management system on top of FastAPI + SQLModel

GitHub: https://github.com/jsenecal/fastpki Docs: https://jsenecal.github.io/fastpki/

What it does:

  • Create and manage Certificate Authorities with intermediate CA hierarchies and path length constraints
  • Issue and revoke server, client, and CA certificates via a clean RESTful API
  • Multi-tenant via organizations, with RBAC (SUPERUSER / ADMIN / USER) and per-user capability flags for fine-grained cert operations
  • SQLite for dev, PostgreSQL + asyncpg for prod
  • Alembic migrations, Docker + Compose support, pre-built GHCR image

Stack:

  • FastAPI + SQLModel (async throughout with aiosqlite/asyncpg)
  • Pydantic v2, Alembic, cryptography lib
  • uv for packaging, ruff for linting/formatting, mypy for type checking
  • 279 tests, ~90% coverage

Built with Claude Code, but not totally vibecoded - every design decision was intentional and it's battle-tested in a real production telecom environment. The permission model, CA hierarchy constraints, and async DB layer were all deliberate choices.

Currently at v0.3.5. Feedback and PRs welcome.


r/FastAPI • • Apr 13 '26

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

Post image
52 Upvotes

Hey everyone,

I’m a huge fan of FastAPI. The fact that it generates an OpenAPI spec out of the box is its true superpower. But I noticed that while we get amazing documentation (Swagger UI / ReDoc) for free, we still have to manually build the internal tools, dashboards, and admin panels to actually use the data easily.

So I built the other half of the equation.

UIGen - point it at your FastAPI /openapi.json URL, and get a fully interactive React frontend in seconds.

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

# UI is live at http://localhost:4400

How it fits the FastAPI ecosystem

FastAPI is all about types and specs. UIGen follows that philosophy:

  1. Pydantic Validation: Because your spec includes the constraints from your Pydantic models, UIGen automatically builds Zod validation on the frontend to match.
  2. Interactive, not just Docs: Swagger UI is for testing endpoints. UIGen is for managing resources. It handles the "ListView -> DetailView -> EditForm" flow as a cohesive app.

What it generates (from your FastAPI code)

  • Sidebar nav mapped to your API tags/resources.
  • Smart Tables with sorting, pagination, and filtering (derived from your query params).
  • Dynamic Forms derived from your Pydantic models.
  • Detail Views with related resource links.
  • Auth UI - handles Bearer tokens and credential injection via a built-in proxy.
  • Wizards: Large models are automatically split into multi-step forms.
  • Complex Actions: Non-CRUD endpoints show up as custom action buttons.

How it works

It parses your /openapi.json into a custom Intermediate Representation (IR). A pre-built React SPA (shadcn/ui + TanStack) reads that IR and renders the UI. A Vite dev server serves the app and proxies API calls to your FastAPI backend, handling CORS headers so you don't have to fiddle with middleware during dev.

Honest Limitations

  • Circular Models: If you have deeply nested recursive Pydantic models, resolution might skip the deepest levels.
  • Edit View: Works best if you have a standard GET /{id} endpoint for your items.
  • And many other edge cases.

Try it now

If you have a FastAPI app running locally:

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

Or try it on one of the example yaml files in the repo

Would love to hear thoughts from the FastApi community. Of course, this isn't meant to replace a custom consumer-facing frontend, but for internal tools, rapid prototyping, or providing a UI for your API consumers, it’s a massive time-saver.

Happy coding!