r/FastAPI • • May 23 '26

Question Interview Preparation

4 Upvotes

Hi folks,

I have some questions on my mind that I would like to ask all Backend Engineers, and the Applied AI engineers who currently work in the EU/US market:

The sector is evolving, as all of us know, and the interviewing process is changing every day, so it's becoming quite complex to decide what to study because some of the companies ask questions and want you to solve them using AI, while others still ask about algorithms. I understand that most of them for sure ask for the system design. 3 years ago, it was quite common to ask programming language-specific questions, for example, generators and context managers in Python. Do they ask similar questions now? How do they proceed in the interviews? How do we get prepared for the interviews? I'm quite confused, actually, because of the industry's undeterministic interview styles.

Should we be ready for Python and FastAPI questions or skip them?

Should we work on databases? Queries, optimisation, etc., or just skip them?

What should we study? 😃 Any help is appreciated. Keen to discuss with you all.

Also, I shouldn't be the only one who feels like this. The sector is bullshitting; they don't know what to do with the interviews. 😃 They're quite confused, as well as we are.

Any kind of resource for interview preparation would be amazing! Appreciate those legends!

Thanks in advance, guys. Happy weekend to all!


r/FastAPI • • Apr 11 '26

pip package CommIPC: A type-safe, asynchronous IPC library for Python (FastAPI for IPC)

4 Upvotes

I wanted high speed communication between multiple scripts of mine.

Long ago i had started to use fastapi for that purpose and then i just got into modular monolithic architecture for web UIs.

but then as i kept doing things i didnt feel like that is satisfactory recently i was kinda intrested to build native applications and wanted IPC and i googled it first didnt find anything simple enough for me to just use out of the box.

like grpc too complex i tried using it once but was complex for my use case and added unnecessary friction.

and then to go for simpler microservice architecture rather than multiple fastapi servers/workers in future for my web uis i thought wont this be simpler and have come out with a simpler library for making a more microservices kinda architecture and just wrap the calls in fastapi for distributed.

With regular setups it kinda gets more complex to implement IPC this library abstracts a lot of that and makes it feel almost like fastapi on provider side and on consumer side it somewhat like requests.

With my current system i believe it is simpler to build Fully distributed mircoservices and then use them through a single fastapi server.

Like i can have 10 seperate services which all do different things and then u can have a fastapi server which send requests to differnt process on same device or distributed and just use them without worrying about how to communicate and you can restart any microservice and it wont matter to the fastapi server, if you use load balanced events then you can even have 0 downtime updates to code.

I have added support for:

- events (RPC like)

- streaming (streaming RPC calls)

- pub/sub (1->many)

- groups (load balanced events)

- full pydantic integration

- IPC to HTTP using fastapi

I tried some benchmarking and have got like sub ms latencies

| Metric | Mean | Median | P95 | P99 |

|----------------------------|----------|----------|----------|----------|

| RPC Latency (RTT) | 0.32ms | 0.29ms | 0.60ms | 0.66ms |

| Group Latency (LB RTT) | 0.30ms | 0.29ms | 0.36ms | 0.55ms |

| PubSub Latency (Relay) | 18.50ms | 19.36ms | 21.76ms | 21.91ms |

| Throughput Metric | Result |

|----------------------------|------------------------|

| RPC Throughput | 8551.8 calls/sec |

| Group Throughput (LB) | 8877.5 calls/sec |

| Streaming Throughput | 12278.6 chunks/sec |

I wanted better performance while being simpler than regular web stack

and have benchmarked my lib and have gotten decent results id say

the benchmark scripts are in the repo you may check them out

have added some example scripts on how you may want to implement things (check out examples/decoupled_demo) almost like fastapi but just IPC

https://github.com/shashstormer/comm_ipc/tree/master


r/FastAPI • • May 03 '26

Question I’m working on a mini Vercel-like deployment platform as a student project and would love some guidance, the backend is fully in FastAPI.

4 Upvotes

Hey everyone 👋

I’m working on a mini Vercel-like deployment platform as a student project and would love some guidance.

What I’m building (high level):

  • A frontend where users upload a project (or repo)

  • FastAPI backend acts as a thin orchestrator (basically just receives config + triggers builds)

  • Cloud provider handles Docker build, pushes image, and deploys

  • The goal is to trigger a cloud build → create a Docker image → deploy → stream logs back to the UI

I’ve attached a diagram for the current architecture.

Current approach:

  • Backend receives configs from frontend

  • It forwards those to a cloud service (Azure initially) to handle Docker build + deploy

  • Backend just tracks status + streams logs (kind of like a control plane)

Where I’m stuck:

  • What’s the best way to handle Docker builds without running them on my backend?

  • ACR seems good but not really “free” for a student

  • Should I:

    • Stick with Azure (ACR Tasks)?

    • Switch to something like GitHub Actions + GHCR?

    • Or self-host builds somehow?

Also wondering:

  • Should I require users to provide a Dockerfile?

  • Or generate one dynamically like Vercel does?

This is just a prototype (no auth yet), so I’m trying to keep things simple but still scalable in design.

Would really appreciate suggestions on:

  • architecture improvements

  • free/cheap build pipelines

  • anything I’m overlooking

Thanks 🙏


r/FastAPI • • Apr 29 '26

Other You Probably Don't Need Celery in Your FastAPI App

32 Upvotes

A lot of FastAPI developers end up with Celery not because they need a distributed task queue, but because BackgroundTasks stopped being enough and Celery was the first thing that came up when they searched for a solution.

This is about that gap, and a library that fills it without the overhead.

What BackgroundTasks does not give you

FastAPI's built-in BackgroundTasks is straightforward. You attach a function to the response and Starlette calls it after the response is sent.

@app.post("/signup")
def signup(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_welcome_email, email)
    return {"ok": True}

That covers fire-and-forget. But in a real application you quickly hit walls:

No retries. If send_welcome_email fails because the SMTP server returned a 503, the task is gone. There is no retry, no backoff, no record of what happened.

No persistence. If the app restarts during a deploy, every queued task disappears. Tasks that were waiting to run simply never run.

No visibility. You cannot see what is running, what has run, what failed, or how long things took. The only way to know a task failed is to catch it in your logs, if you are logging at all.

No scheduling. BackgroundTasks runs things once, after the current request. There is no built-in way to run something on a schedule.

These are not edge cases. They are the baseline requirements for any background job in production.

Why Celery is the wrong answer for most of these

When developers hit these limitations, the standard advice is: add Celery. And Celery does solve all four problems. But it solves them by giving you a distributed task queue, which comes with the full infrastructure that entails.

To use Celery with FastAPI you need:

  • A message broker. Usually Redis or RabbitMQ. A separate service to run, configure, monitor, and back up.

  • A worker process. A separate process that consumes from the broker. Needs to be deployed, restarted on failure, and kept in sync with the app on every deploy.

  • Celery Beat for scheduling. Another separate process.

  • Flower or similar if you want visibility. Yet another service.

Celery was built for teams running tasks on dedicated workers across multiple machines at high volume. If that describes your situation, it is the right tool. But most FastAPI apps sending emails, processing uploads, running nightly reports, and syncing data are not in that category. They just needed BackgroundTasks to grow up a little.

What actually fills the gap

fastapi-taskflow is built specifically for this problem: FastAPI apps that have outgrown BackgroundTasks but do not need a distributed task queue.

It runs inside your FastAPI process. No broker. No separate worker. Tasks execute the same way they do today, after the response, but now with retries, persistence, scheduling, and a live dashboard.

Setup:

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

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

Retries:

@task_manager.task(retries=3, delay=60.0, backoff=2.0)
def send_welcome_email(email: str):
    _send(email)  # raise any exception — the retry handles it

The function stays a plain function. Raise an exception on failure and it retries automatically with exponential backoff.

Your routes stay the same:

@app.post("/signup")
def signup(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_welcome_email, email=email)
    return {"ok": True}

Same annotation. Same calling convention. Nothing changes in your routes.

Persistence across restarts:

requeue_pending=True saves tasks that were queued at shutdown and re-dispatches them on the next startup. Tasks no longer disappear on deploy.

Scheduling:

@task_manager.schedule(cron="0 2 * * *")
def nightly_cleanup():
    _run_cleanup()

No Beat process. No separate service. The scheduler runs inside the app.

Eager dispatch:

BackgroundTasks always runs after the response is sent. If you need a task to start immediately, before the response goes out, set eager=True:

@task_manager.task(retries=3, eager=True)
async def notify_user(user_id: int):
    await push_service.send(user_id, "Your request is processing")

The task starts via asyncio.create_task the moment add_task() is called. It is still tracked, still retried on failure, still visible in the dashboard. You can also set it per call:

background_tasks.add_task(notify_user, user_id, eager=True)

Visibility:

/tasks/dashboard is a live dashboard that shows every task, its current status, duration, logs, and the full stack trace on failure. It updates over SSE in real time. No Flower setup, no external monitoring service.

The honest trade-offs

This is not a Celery replacement. If your tasks are CPU-intensive and need isolation from request handlers, if you need to route different task types to dedicated worker machines, or if you are processing thousands of tasks per minute, you need a proper task queue.

What fastapi-taskflow covers is the case where you reached for Celery because BackgroundTasks gave you nothing, not because you genuinely needed distributed workers.

For a single-host deployment, multiple instances on the same host share a SQLite file. For multiple hosts, swap to Redis or PostgreSQL as the backend and idempotency, requeue claiming, and task history all work across instances without any coordination overhead.

What you skip entirely

No broker to run or monitor. No worker process to deploy or restart. No Celery app instance or separate tasks module. No Beat process for scheduling. No Flower for visibility.

Local development stays at uvicorn app.main:app. New developers on the project do not need to learn a separate system.

The four things that pushed you toward Celery in the first place, retries, persistence, scheduling, and visibility, are covered.


r/FastAPI • • Oct 17 '22

Tutorial Beginners FastAPI - 40 min

Thumbnail
youtu.be
14 Upvotes

r/FastAPI • • Sep 28 '25

Question Rails UI equivalent for FastAPI?

9 Upvotes

I have experience years ago using Grails (Java VM version of Ruby on Rails).

One of the awesome things about it was that you could define your entities, and Grails auto-generates the CRUD user interface for you.

It’s a basic version with forms and not something you likely go into production with, but it is fast and great for prototyping.

Is there anything like this that works on top of Pydantic/SQLAlchemy/FastAPI?


r/FastAPI • • Oct 04 '25

Question FastAPI HTML sanitization

9 Upvotes

I'm building a FastAPI application where users can create flashcards, comments etc. this content then is stored in the db and displayed to other users. So as every good developer i need to sanitize the content to prevent xss atacks, but i am wondering which approach is best.

I have two approaches in mind:

Approach one:

Utilize pydantic to perform bleaching of data, f.e:

from pydantic import BaseModel
from typing import Any
import bleach

 class HTMLString(str):
    # perform bleaching here

class FlashCard(BaseModel):
    front_content: HTMLString
    back_content: HTMLString

Approach two:

Create a sanitization middleware that is going to bleach all content that i get from the users:

class SanitizationMiddleware:
    async def __call__(self, scope, receive, send):
        request = Request(scope, receive)
        body = await request.body()

        # perform bleaching here on all fields that are in the json

        await self.app(scope, receive, send)

So my questions is are there any other approaches to this problem (excluding bleaching right before saving to db) and what is the golden standard?


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 • • Sep 25 '25

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

34 Upvotes

Hey everyone,

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

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

For those who've made this jump:

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

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

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

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

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

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

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

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


r/FastAPI • • Mar 15 '26

Question Built a Production-Ready AI Backend: FastAPI + Neo4j + LangChain in an isolated Docker environment. Need advice on connection pooling!

15 Upvotes

Hey everyone,

I recently built a full stack GraphRAG application to extract complex legal contract relationships into a Knowledge Graph. Since I wanted this to be a production ready SaaS MVP rather than just a local script, I chose FastAPI as the core engine.

The Architecture choices:

  • Used FastAPI's async endpoints to handle heavy LLM inference (Llama-3 via Groq) without blocking the server.

  • Neo4j Python driver integrated for complex graph traversals.

  • Everything is fully isolated using Docker Compose (FastAPI backend, Next.js frontend, Postgres) and deployed on a DigitalOcean VPS.

My Question for the backend veterans: Managing the Neo4j driver lifecycle in FastAPI was a bit tricky. Right now, I initialize the driver on app startup and close it on shutdown. Is this the absolute best practice for a production environment, or should I be doing connection pooling differently to handle concurrent LLM requests?

(If you want to inspect the docker-compose setup and the async routing, the full source code is here: github.com/leventtcaan/graphrag-contract-ai*)*

(Also, Reddit doesn't allow video uploads in text posts, but if you want to see the 50-second UI demo and how fast it traverses the graph, you can check out my launch post on LinkedIn here: https://www.linkedin.com/feed/update/urn:li:activity:7438463942340952064/ | Would love to connect!)


r/FastAPI • • Dec 22 '24

Question Pivot from Flask

10 Upvotes

Hey everyone,

I recently built an app using Flask without realizing it’s a synchronous framework. Because I’m a beginner, I didn’t anticipate the issues I’d face when interacting with multiple external APIs (OpenAI, web crawlers, etc.). Locally, everything worked just fine, but once I deployed to a production server, the asynchronous functions failed since Flask only supports WSGI servers.

Now I need to pivot to a new framework—most likely FastAPI or Next.js. I want to avoid any future blockers and make the right decision for the long term. Which framework would you recommend?

Here are the app’s key features:

  • Integration with Twilio

  • Continuous web crawling, then sending data to an LLM for personalized news

  • Daily asynchronous website crawling

  • Google and Twitter login

  • Access to Twitter and LinkedIn APIs

  • Stripe payments

I’d love to hear your thoughts on which solution (FastAPI or Next.js) offers the best path forward. Thank you in advance!


r/FastAPI • • Apr 12 '25

Question Fastapi bottleneck why?

10 Upvotes

I get no error, server locks up, stress test code says connection terminated.
as you can see just runs /ping /pong.

but I think uvicorn or fastapi cannot handle 1000 concurrent asynchronous requests with even 4 workers. (i have 13980hx 5.4ghz)

With Go, respond incredibly fast (despite the cpu load) without any flaws.

Code:

from fastapi import FastAPI
from fastapi.responses import JSONResponse
import math

app = FastAPI()

u/app.get("/ping")
async def ping():
    return JSONResponse(content={"message": "pong"})

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=8079, workers=4)

Stress Test:

import asyncio
import aiohttp
import time

# Configuration
URLS = {
    "Gin (GO)": "http://localhost:8080/ping",
    "FastAPI (Python)": "http://localhost:8079/ping"
}

NUM_REQUESTS = 5000       # Total number of requests
CONCURRENCY_LIMIT = 1000  # Maximum concurrent requests
REQUEST_TIMEOUT = 30.0    # Timeout in seconds

HEADERS = {
    "accept": "application/json",
    "user-agent": "Mozilla/5.0"
}

async def fetch(session, url):
    """Send a single GET request."""
    try:
        async with session.get(url, headers=HEADERS, timeout=REQUEST_TIMEOUT) as response:
            return await response.text()
    except asyncio.TimeoutError:
        return "Timeout"
    except Exception as e:
        return f"Error: {str(e)}"


async def stress_test(url, num_requests, concurrency_limit):
    """Perform a stress test on the given URL."""
    connector = aiohttp.TCPConnector(limit=concurrency_limit)
    async with aiohttp.ClientSession(connector=connector) as session:
        tasks = [fetch(session, url) for _ in range(num_requests)]
        start_time = time.time()
        responses = await asyncio.gather(*tasks)
        end_time = time.time()
        
        # Count successful vs failed responses
        timeouts = responses.count("Timeout")
        errors = sum(1 for r in responses if r.startswith("Error:"))
        successful = len(responses) - timeouts - errors
        
        return {
            "total": len(responses),
            "successful": successful,
            "timeouts": timeouts,
            "errors": errors,
            "duration": end_time - start_time
        }


async def main():
    """Run stress tests for both servers."""
    for name, url in URLS.items():
        print(f"Starting stress test for {name}...")
        results = await stress_test(url, NUM_REQUESTS, CONCURRENCY_LIMIT)
        print(f"{name} Results:")
        print(f"  Total Requests: {results['total']}")
        print(f"  Successful Responses: {results['successful']}")
        print(f"  Timeouts: {results['timeouts']}")
        print(f"  Errors: {results['errors']}")
        print(f"  Total Time: {results['duration']:.2f} seconds")
        print(f"  Requests per Second: {results['total'] / results['duration']:.2f} RPS")
        print("-" * 40)


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except Exception as e:
        print(f"An error occurred: {e}")

Starting stress test for FastAPI (Python)...

FastAPI (Python) Results:

Total Requests: 5000

Successful Responses: 4542

Timeouts: 458

Errors: 458

Total Time: 30.41 seconds

Requests per Second: 164.44 RPS

----------------------------------------

Second run:
Starting stress test for FastAPI (Python)...

FastAPI (Python) Results:

Total Requests: 5000

Successful Responses: 0

Timeouts: 1000

Errors: 4000

Total Time: 11.16 seconds

Requests per Second: 448.02 RPS

----------------------------------------

the more you stress test it, the more it locks up.

GO side:

package main

import (
    "math"
    "net/http"

    "github.com/gin-gonic/gin"
)

func cpuIntensiveTask() {
    // Perform a CPU-intensive calculation
    for i := 0; i < 1000000; i++ {
        _ = math.Sqrt(float64(i))
    }
}

func main() {
    r := gin.Default()

    r.GET("/ping", func(c *gin.Context) {
        cpuIntensiveTask() // Add CPU load
        c.JSON(http.StatusOK, gin.H{
            "message": "pong",
        })
    })

    r.Run() // listen and serve on 0.0.0.0:8080 (default)
}

Total Requests: 5000

Successful Responses: 5000

Timeouts: 0

Errors: 0

Total Time: 0.63 seconds

Requests per Second: 7926.82 RPS

(with cpu load) thats a lot of difference


r/FastAPI • • Mar 06 '26

Other Open-sourced a FastAPI app that turns Trello boards into autonomous AI agent pipelines

10 Upvotes

Sharing a project that might interest this community — it's a FastAPI application at its core, and it follows patterns I think many of you would recognize (and hopefully critique).

What it does: Trello boards become the message bus between AI agents. You talk to an orchestrator via Telegram, it creates Trello cards, worker agents pick them up and execute autonomously — writing code, reviewing PRs, running research pipelines. Webhooks drive everything, no polling.

The FastAPI side:

- Domain-driven app structure — each bounded context (trello, agent, bot, hook, git_manager) is its own app under app/apps/

- Async everywhere — httpx for Trello/Telegram/GitHub APIs, subprocess for git ops

- Pydantic-settings for config (env + JSON), strict Pydantic models with Annotated types for all inputs/outputs

- Webhook routes for both Trello (HMAC-SHA1 verified) and Telegram (secret path auth)

- Shared httpx clients as singletons with custom rate-limiting transport (sliding window + 429 backoff)

- Lifespan context manager starts agent run loops and registers webhooks on startup

- Health endpoint exposes per-agent status, queue depth, and cost tracking

The agent side:

Workers are composable through config — three axes (repo_access, output_mode, allowed_tools) define what each agent does. Same WorkerAgent class handles coders that open PRs, reviewers that post analysis, and researchers that chain findings through multi-stage pipelines. No subclassing, just config.

A coding board can run: scout → coder → tester → elegance → reviewer. A research board can run: triage → deep → factory → validation → verdict. Different boards, same framework.

Built with Python 3.12+, FastAPI, Claude Agent SDK, httpx. MIT licensed.

GitHub: github.com/Catastropha/karavan

Happy to discuss the architecture choices — especially the "Trello as the only state store" decision and the webhook-driven design. Would do some things differently in hindsight.


r/FastAPI • • Jun 30 '24

Question Dependency declaration is ugly

16 Upvotes

Is it just me who dislikes the way dependencies are declared in FastAPI? Why does dependency injection have to be tied to type definitions?

It feels ironic that the primary reason for moving external dependencies into function arguments is to decouple them, yet declaring dependencies in the function's type signature ends up coupling them again in another way.

Does anyone else find this approach awkward?


r/FastAPI • • Dec 10 '25

Question How can I level up from basic Python API dev to building scalable, production-grade APIs in 6 months?

Thumbnail reddit.com
16 Upvotes

r/FastAPI • • Mar 24 '26

feedback request I built a production-ready FastAPI boilerplate with auth, logging, and scalable structure — feedback welcome

16 Upvotes

I was tired of setting up the same things every time I start a FastAPI project, so I created a reusable boilerplate.

It includes:

  • JWT authentication setup

  • Structured logging

  • Modular folder architecture

  • Environment-based config

  • Ready-to-use Docker setup

The goal was to make something that’s actually usable in production, not just a basic template.

Would love feedback on:

  • Project structure

  • Anything missing for real-world use

  • Improvements for scalability

Repo: https://github.com/yashsinghviwork/fastapi-boilerplate


r/FastAPI • • Apr 17 '25

Question Blog website using FastAPI

5 Upvotes

Has anyone made a blogging site with FastAPI as backend, what was your approach?
Did you use any content management system?
Best hosting for it? As blogs doesn't need to be fetched every time a user visits, that would be costly plus static content ranks on Google, is generating static pages during build time good approach? Rebuild again after updating a blog, only that one not the whole site.
What was your choice for frontend?
Thanks!


r/FastAPI • • Apr 23 '25

feedback request My first vibe coded FastAPI backend

0 Upvotes

Hi there!

I recently worked on fetch hiring challenge and had built APIs using FastAPI. I usually work on Django but recently got excited to use fastapi. Since I’m still new to FastAPI, I ended up vibe coding the backend for this challenge.

Here is the github link to the code: https://github.com/thevyasamit/receipt_processing

I’m looking for the feedback to know if what I vibe coded is correct or not and were you guys able to run it by following the documentation or not?

PS: I got rejected but idc, I wanna build better back ends and open source projects and want feedback to follow the right direction and best practices.

Thanks!


r/FastAPI • • Jun 17 '26

Tutorial I ran my PR security tool on the official FastAPI template and posted the full raw output, false positive included

0 Upvotes

I build Fixor, an LLM-based security reviewer that reads the changed code in a pull request and flags authorization bugs. This was its CLI run against a public repo, and I'm posting the complete output rather than a claim, because the last time someone showed up here with "my AI scanner finds bugs," the right response was "stop talking and show me a real run." So here is one you can reproduce in five minutes.

I scanned the route layer of the official full-stack-fastapi-template (commit cd83fc1), `backend/app/api/routes/` only. Full raw report here:

https://gist.github.com/tornidomaroc-web/d6b3f4d3f2ae53809f087889ebc91c8a

## What it flagged

Two findings, both on the same route, `private.py`:23:

> ### auth_bypass_risk — critical (confidence: high)

> - File: `private.py`:23

> ### admin_check_risk — critical (confidence: high)

> - File: `private.py`:23

And here is the honest part, up front: that is a false positive. The `private` router is mounted only when `ENVIRONMENT == "local"` (`api/main.py`:13), so it does not exist in staging or production. Fixor reads the route file in isolation and cannot see that cross-file conditional mount, so it flags a dev-only route as if it were always live. The two findings are also one route drawing both "no auth" and "no admin gate," not two separate bugs. And "critical / high" is the model's own self-reported confidence, not a measured severity.

So if you opened the gist and saw "critical auth bypass in the FastAPI template," that is the wrong read, and I would rather tell you that myself than have you find it.

## What it cleared (the part I actually care about)

By my count, 22 of the 23 route handlers were cleared, and the clears are the interesting result:

The `items.py` routes (read, update, delete by id) all have the exact IDOR shape, a request-derived id going into `session.get(Item, id)`. A pattern scanner flags every one of those. Fixor cleared them, because it read the inline ownership check (`if not current_user.is_superuser and item.owner_id != current_user.id: raise 403`) sitting in the same file.

The `users.py` admin routes are gated by `dependencies=[Depends(get_current_active_superuser)]` in the decorator, not the signature. It parsed that and did not false-positive them. And the by-design public endpoints, signup, login, password reset, were not flagged either.

## Where it's blind, so you can judge it fairly

The same reason it cleared those item routes is the reason it has a hard limit: it reasons in-file. The ownership check or auth dependency has to be in the file it reads. If your guard lives in a base repository, tenant middleware, or a router-level dependency in another file, Fixor can miss it or false-positive it, exactly like the `private.py` conditional mount it got wrong here. A clean result from it means "no in-file problem found," never "this code is secure."

That is the whole thing, output and blind spot. Clone the template, run it yourself, and tell me where the reasoning breaks. I would rather hear it here than learn it later.


r/FastAPI • • Jun 08 '25

Question Having trouble building a response model

5 Upvotes

I'm struggling a bit building a response model, and so FastAPI is giving me an error. I have a basic top level error wrapper:

class ErrorResponse(BaseModel):
    error: BaseModel

and I want to put this into error

class AuthFailed(BaseModel):
    invalid_user: bool = True

So I thought this would work:

responses={404: {"model": ErrorResponse(error=schemas.AuthFailed())}}

But I get the error, of course, since that's giving an instance, not a model. So I figure I can create another model built from ErrorResponse and have AuthFailed as the value for error, but that would get really verbose, lead to a lot of permutations as I build more errors, as ever error model would need a ErrorResponse model. Plus, naming schemas would become a mess.

Is there an easier way to handle this? Something more modular/constructable? Or do I just have to have multiple near identical models, with just different child models going down the chain? And if so, any suggestions on naming schemas?


r/FastAPI • • Jan 16 '26

Tutorial Как сделать авторизацию в fastapi

0 Upvotes

Мне для олимпиады нужно сделать 2OAuth


r/FastAPI • • Apr 30 '21

Tutorial GET and POST Images FastAPI

Thumbnail
youtu.be
5 Upvotes

r/FastAPI • • Feb 19 '22

Question Limit Fastapi to process only 1 request at a time and after its completion process the next request

5 Upvotes

I'm trying to limit Fastapi to process 1 request at a time. And while that request is being executed, other requests gets response of 503(Server busy).

If anyone can help me with this....


r/FastAPI • • Sep 07 '24

Hosting and deployment FastAPI as a back end for Agent Based Coding Competition

5 Upvotes

👋 Hello, FastAPI Community!

I'm Sanjin, and I've been using FastAPI for two years to build backends for a statewide coding competition in Melbourne, Australia. 🇦🇺 So far, over 5,000 students have used it, and the backend has held up great! 💪

🚀 This Year's Ambitious Setup

We're running an exciting project with these features:

  • 🤖 Students submit code agents that compete in games like Prisoner's Dilemma

  • 🐳 Code runs safely in Docker containers

  • 🗃️ Database is in SQLModel and running smoothly

  • 🔌 Modular game engine design for super easy addition of new game types

  • ⚛️ Front-end is React (not pretty, but functional)

🔗 Check It Out!

You can find the project here: [Agent Games on GitHub](https://github.com/SanjinDedic/agent_games)

🙏 Feedback and Collaboration Welcome

I'd love any feedback on the project! The full-stack app takes just 10 minutes to set up locally. There are usually a dozen issues you can take on if you're interested in collaborating as well as an opportunity to create much cooler games than we came up with so far!