r/FastAPI • • Oct 02 '21

Question How to validate request body in FastAPI?

2 Upvotes

I understand that if the incoming request body misses certain required keys, FastAPI will automatically raise 422 unserviceable entity error. However, is there a way to check the incoming request body by myself in the code and raise a 400 bad request if if misses required names?

For example, let's say I have this model and schema:

class Student(Base):
    __tablename__ = "student"

    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    email = Column(String(100), unique=True, nullable=False)
    gpa = Column(Float, unique=False, nullable=False)
class StudentBase(BaseModel):
    name: str
    email: str
    gpa: float

The POST endpoint to create a new row is:

@app.post("/student", dependencies=[Depends(check_request_header)],
          response_model=schemas.Student, status_code=200)
def create_student(student: schemas.StudentCreate, db: Session = Depends(get_db)):
    db_student = crud.get_student(db, student=student)
    if db_student:
        raise HTTPException(status_code=400, detail="This student has already been created.")
    return crud.create_student(db=db, student=student)

The expected request body should be something like this:


{
"name": "johndoe",
"email": "[email protected]",
"gpa": 5.0
}

is there a way to check the request body for the above endpoint? For example, raise a bad request exception when the request body misses a name:


{
"name": "johndoe",
"email": "[email protected]",
}

r/FastAPI • • May 31 '26

Question how would you structure a FastAPI service for scoped user preferences?

2 Upvotes

i’m thinking through a FastAPI service for user preferences, and the hard part is keeping the API narrow.

tried a generic user profile endpoint. too broad. tried app-scoped preferences. cleaner, but reuse across apps gets awkward. tried event-derived context, but cold start is still brutal.

what i want is something like: app requests a specific context scope, user consent is checked, response only includes what that app needs.

but then you need revocation, audit logs, schemas, and a way to avoid random clients dumping everything into “metadata.”

how would you structure this so it stays useful without becoming a privacy mess?


r/FastAPI • • Jan 25 '26

Other PromptChart - generate charts with prompts

Thumbnail
github.com
0 Upvotes

I built an Open Source end to end system that uses FastAPI for generating charts via llm prompts.

The exact code for FastAPI can be found here:
https://github.com/OvidijusParsiunas/PromptChart/tree/main/examples/python/fastapi


r/FastAPI • • May 03 '26

Hosting and deployment IRAS autonomous incident response agent built with FastAPI, LangGraph, and Pydantic AI

2 Upvotes

Built an open-source autonomous incident response agent and wanted to share it here since it's a fairly involved real-world Python project.

What it does: When a production alert fires, IRAS triages severity, gathers logs/metrics/recent deployments, runs root-cause analysis, generates a remediation plan with rollback commands, pauses for a human to approve, applies the fix, and writes a post-mortem. All automatically, in under 2 minutes.

Stack:

  • FastAPI webhook ingestion + approval REST API

  • LangGraph 9-node state machine with durable execution via PostgreSQL checkpointing

  • Pydantic AI one typed agent per stage; every LLM output is a validated Pydantic model (TriageResult, RootCauseHypothesis, RemediationPlan, PostMortem). No raw strings anywhere.

  • Claude Haiku for fast triage and context-gathering, Claude Sonnet for RCA, remediation planning, and post-mortems

  • AsyncPostgresSaver for durable graph state the agent can be interrupted mid-execution, survive a server restart, and resume exactly where it left off

One thing I'm proud of typed agent outputs with Pydantic AI: Every agent stage produces a strongly-typed model, not a raw string. This means the rest of the graph code is just Python no prompt output parsing, no regex, no json.loads() on LLM responses.

python

class RootCauseHypothesis(BaseModel):
    primary_cause: str
    contributing_factors: list[str]
    evidence: list[str]       # specific log lines
    confidence: float         # 0.0 – 1.0

rca_agent = Agent(
    model="claude-sonnet-4-5",
    result_type=RootCauseHypothesis,
    system_prompt="..."
)

result = await rca_agent.run(context_bundle)
hypothesis: RootCauseHypothesis = result.data  # fully validated

Testing: 292 tests, 99% coverage. The stress suite includes adversarial scenarios model lies about risk_level, returns empty rollback commands, all context tools fail simultaneously, 20 concurrent incidents with zero state contamination.

Running it: Only needs ANTHROPIC_API_KEY + Docker for Postgres. All integrations (Slack, PagerDuty, Prometheus, Elasticsearch) fall back to mock clients automatically.

Repo: https://github.com/krishnashakula/IRAS

Open to feedback on the architecture, the Pydantic AI usage, or anything else.


r/FastAPI • • Mar 11 '26

Question Cheapest Web Based AI (Beating Perplexity) for Developers (tips on improvements?)

Thumbnail reddit.com
2 Upvotes

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 • • Jul 22 '25

Question new to APIs

9 Upvotes

Hey everyone, im currently learning to code API and wanted to get some hands-on experience by building and publishing a few APIs, i have just started sharing them on RapidAPI, and I'd really appreciate if anyone here could give them a try, here is my profil: https://rapidapi.com/user/mohamedmouminchk

These are some small personal projects to help me improve. If you have a moment to test them out and let me know if something's broken, unclear, or just badly designed, I'd be super grateful!!

I’m still new to all this, so any feedback, good or bad, will help me grow and improve. Thanks in advance!


r/FastAPI • • May 09 '23

Hosting and deployment Made a FastAPI+React starter template (setup in a single command)

9 Upvotes

I made this super easy to use FastAPI+Reactjs template that saves you lot of time and effort connecting and setting your project up.

All you need to do to run it,

  • git clone the repository

  • run the batch file

Your project is now deployment ready 😁

Link: https://github.com/salwinat0r/FastReact


r/FastAPI • • Apr 02 '24

Other 10 reasons I stick to Django rather than FastAPI

Thumbnail
david-dahan.com
0 Upvotes

r/FastAPI • • Jul 30 '25

Other I built a ♂️ Gachimuchi API♂️

Thumbnail gachimuchi-api.vercel.app
9 Upvotes

Hey my ♂️fellow brothers♂️,

I just finished building an API as a pet project dedicated to the glorious world of Gachimuchi. It’s live, it’s free, and it’s dripping in power.

✨ Features: • 🔍 Search characters by name, surname or nickname • 🎧 Explore and filter the juiciest audio clips • 📤 Upload your own sounds (support for .mp3) • ➕ Add and delete characters & quotes (yes, even Billy)

Example quotes like:

“Fucking salves get your ass back here…” “Fuck you...”

💪 Built with FastAPI + Supabase


r/FastAPI • • May 03 '22

feedback request FastAPI ETL server - getting ready for production

Post image
13 Upvotes

r/FastAPI • • May 22 '25

Other Awesome boilerplate for FastAPI

72 Upvotes

Hey devs! 👋

I recently put together a FastAPI boilerplate that brings structure and scalability to backend projects — and I think you’ll find it handy, especially if you’re tired of messy service imports and unorganized codebases.

  • Unified Service Manager (Acquire): All your models, schemas, utilities, libraries, and services are automatically registered and ready to use — no more manual imports when jumping between services. Super helpful for keeping things DRY.

  • Directory-based routing: A clear and modular structure that keeps routes clean and maintainable.

  • Version toggles for libraries: Easily switch or lock library versions — helpful when managing different environments or legacy support.

  • …and more!

🔗 Check it out here:

https://github.com/definableai/definable.backend

We’re also looking for solid contributors who are passionate about clean architecture and want to help build this into something bigger. If that’s you, feel free to DM me — happy to give you a quick walkthrough and onboard you!

Let me know what you think 🙌


r/FastAPI • • Nov 25 '25

Other How accurate do you think this image is?

Post image
117 Upvotes

*was created by ai


r/FastAPI • • Jun 06 '23

Question Help wanted: support for PR

6 Upvotes

Hey guys! Can you support my PR fixing nested lifespans ignoring to merge it faster?

Example: the following code doesn't works

from contextlib import asynccontextmanager
from fastapi import FastAPI, APIRouter

@asynccontextmanager
async def router_lifespan(app):
    print('router start')
    yield
    print('router shutdown')

router = APIRouter(lifespan=router_lifespan)
app = FastAPI()
app.include_router(router)

It is a unconsistence behavior cuz on_startup and on_shutdown deprecated events are includes to parent router and application.

Also it is important for my own Propan package implementing some custom routers.


r/FastAPI • • Dec 23 '25

pip package fastapi-fullstack v0.1.7 released – Add Support For AGENT.md and CLAUDE.md. Production Docker with optional Traefik reverse proxy

6 Upvotes

Hey r/FastAPI,

Quick update for those following the project (or new here): fastapi-fullstack is a CLI generator (pip install fastapi-fullstack) that creates production-ready full-stack AI/LLM apps with FastAPI backend + optional Next.js 15 frontend.

Repo: https://github.com/vstorm-co/full-stack-fastapi-nextjs-llm-template
Changelog: https://github.com/vstorm-co/full-stack-fastapi-nextjs-llm-template/blob/main/docs/CHANGELOG.md

v0.1.7 just dropped with focus on real production deploys:

Added:

  • Optional Traefik reverse proxy in production Docker setup:

    • traefik_included (full Traefik in docker-compose.prod.yml – default)

    • traefik_external (just labels for shared Traefik)

    • none (direct port exposure)

  • .env.prod.example with conditional sections + required variable validation (${VAR:?error})

  • Unique Traefik router names using project slug – perfect for running multiple apps on one server

  • Better docs for AI-assisted development (AGENTS.md, progressive disclosure guides: architecture, adding features, testing, patterns)

  • Updated README with "AI-Agent Friendly" section

Security & changes:

  • No more hardcoded/insecure defaults in production compose

  • .env.prod added to .gitignore

  • Cleaner CLAUDE.md (down to ~80 lines) + refactored production compose

If you're deploying FastAPI apps to real servers, this should make life much easier. Feedback welcome – especially on the Traefik setup! 🚀


r/FastAPI • • Dec 30 '23

Question Can I Build a Modern Web App with FastAPI, HTML, and CSS Alone? 🚀

10 Upvotes

Hey FastAPI fam!

Curious if anyone has explored creating a sleek web app using only FastAPI, HTML, and CSS—no JavaScript. 🤔

Question: Any success stories or advice on using FastAPI for both backend and frontend without dipping into JavaScript? Tips, challenges, or examples welcome!

Also, if you've come across any videos or posts about this, please share! 📹📚

Excited to hear your insights! 🌐💻


r/FastAPI • • Dec 24 '25

Question FastAPI in 2025: Are Async & Type Hints Now Mandatory?

52 Upvotes

Building LLM backends, real-time dashboards, or AI agent APIs? Just moved a Flask/Celery setup to FastAPI. The result? One service. No Celery. 3x more WebSocket connections. Prototypes done in an afternoon. With everything moving async, is choosing a sync-first framework in 2024 just creating future tech debt?

Hot take: For new Python APIs, FastAPI should be the default. Change my mind.

  • Flask/Django folks: Overrated for most CRUD?

  • Anyone who bounced off: What was the dealbreaker?

  • Killer feature? (Pydantic + auto-docs for me).


r/FastAPI • • Oct 08 '24

Hosting and deployment HTTPS with FastAPI - could idea this work?

15 Upvotes

I am reorganizing our app with now FastAPI as backend. I have it running in a container on our server, currently only in HTTP mode, port 8000.

I need to enable HTTPS for it.

My idea. I am using the same production server as for our old version and will keep it running until it is phased out. The old version has HTTP and HTTPS running through a Apache instance. Now I am thinking to create a `https://fastapi.myapp.com` subdomain that routes to Apache 443. Apache in turn forwards that subdomain to the new fastapi container running on port 8000.

Valid solution here? Double checking the idea before I commit to it.

Are there more elegant / better approaches how to implement HTTPS with FastAPI? I do not like having Apache running forever since it eats up resources + is another process that needs maintenance, upgrades, possible security risk.
Thanks!


r/FastAPI • • Aug 15 '22

Tutorial FastAPI GraphQL Sqlalchemy Complete Tutorial | Strawberry | Docker |...

Thumbnail
youtube.com
11 Upvotes

r/FastAPI • • Apr 13 '23

Hosting and deployment Any FastAPI and UI CRUD framework: eg filters, modals, drop-downs, pagination etc?

3 Upvotes

hi

I had quite a detailed search to find if there is any framework for FastAPI with ability to create a CRUD with functionalities of filters, modals, drop-downs, pagination etc, but couldn't find any.

Looking for something like a framework which encompasses

- reactjs/Angular components

- https://datatables.net

- lightweight database

- with fastAPI doing the logic

Have you come across any such ready-made framework? If not, is there a way someone can develop and we can compensate that?


r/FastAPI • • Jul 25 '24

Question Hello I need some help to set up API.

0 Upvotes

I can't understand how to integrate with other websites through api, can anyone help ? Like where I am getting api documentation with a lot of examples but I can't understand where to place them. Where I need to place codes? Where I will get codes and also where to get postback url and where I need to place postback url? How to display other websites in my website?


r/FastAPI • • Sep 12 '24

Question automatically update database table

3 Upvotes

I'm building a backend using fastAPI and PostgreSQL where I'm storing opportunities with a boolean "is_live" and a datetime "deadline" and I want opportunities "is_live" to be setted as False automatically when the current date is superior to the "deadline".

what's the best approach to do this ? and Thank your in advance.

EDIT: I want to be able to mark the opportunity as not live sometimes before the deadline, that's why I have a seperate "is_live" column with the deadline


r/FastAPI • • Dec 08 '21

Question How to get a length of List[] in schema...?//A beginner asking help!

3 Upvotes

in schemas.py from fastapi tutorials.

-----

class Item(ItemBase):
id: int
    owner_id: int
class Config:
        orm_mode = True
class User(UserBase):
id: int
    is_active: bool
    items: List[Item]=[]
class Config:
        orm_mode = True
-----

you guys might see this basic tutorial code,

and I am asking to let me know to who knows this.

I just want to get a "number of Items" not a full of Items' list.
(cause, the proj I am working on, needs that attribute. it's like 5000 items. when i do the test)

is there any reference to get the idea of what i asking?
thanks in advance.


r/FastAPI • • May 12 '21

Question Can I block and user that requires frequency

3 Upvotes

Or should I do this on my system level like a firewall