r/FastAPI • • Jul 22 '24

Question Any production level request stats vs flask ( docker ) on aws fargate or ecz

2 Upvotes

Has anyone deployed fastapi on docker with workers ( uvicorn ).

How does it scale .

Assume minimal processing and db querying.


r/FastAPI • • Sep 13 '24

Question An equivalent of django-positions with FastAPI?

2 Upvotes

Hi there!

I'm looking for an equivalent of https://github.com/jpwatts/django-positions package, to use with FastAPI and SQLModel. Or if it's not a package, maybe a code snippet somewhere?

PS: as I'm starting fastAPI, I do not feel skilled enough to build it by myself for now.
Thanks for your help.


r/FastAPI • • Aug 18 '24

Question Guys when I am doing multiple curl request my whole fastapi server is going down

2 Upvotes

What am doing wrong..?
I was using request before, so it was waiting for each request to complete, and then I read fastapi docs on async await and that any third app calls should be awaited, it improved locally but on server where am deploying through docker uvicorn, when am doing multiple curl request at same time, it stops, docker logs doesnt show anything curl gives me 502, also it should'nt be timeout issue since one request on avg I get within 30sec

@app.post("/v1/chat/completions")
async def create_chat_completion(
    request: dict,
    stream: bool = False,
):
    url = os.getenv("EXTERNAL_URL")
    if url is None:
        raise HTTPException(status_code=500, detail="EXTERNAL_URL is not set")

    try:
        print(request)
        summary = await async_client.summarize_chat_history(request=request)
        print(summary)

        async with httpx.AsyncClient() as client:
            response = await client.post(
                url + "/documents/retrieve",
                headers={
                    "accept": "application/json",
                    "Content-Type": "application/json",
                },
                json={"prompt": summary.text, "k": 3},
            )
            retrieved_docs = response.json()

        formatted_docs = "\n\n".join(doc["page_content"] for doc in retrieved_docs)
        request["context"] = request.get("context", "") + formatted_docs
        print(request["context"])
        
        if stream:
            return StreamingResponse(stream_response(request), media_type="text/plain")

        ai_response = await async_client.generate_answer(request=request)

    except Exception as e:
        raise HTTPException(status_code=500, detail="Failed to generate answer") from e

    return {
        "id": f"chatcmpl-{os.urandom(4).hex()}",
        "object": "chat.completion",
        "created": int(time.time()),
        "model": request.get("model", "default_model"),
        "choices": [
            {
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": ai_response.text,
                },
                "finish_reason": "stop",
            },
        ],
        "usage": {
            "prompt_tokens": len(str(request["messages"])),
            "completion_tokens": len(ai_response.text),
            "total_tokens": len(str(request["messages"])) + len(ai_response.text),
        },
    }

r/FastAPI • • Jan 19 '24

Question Forever having trouble in VS Code

2 Upvotes

No matter how many times I verify it, I always get the Module not found error. I've confirmed fastapi install and version with pip freeze. I have 0.109.0 installed. The interpretter is the same as the python/python3 --version. I've checked all the which python/python3 and they lead to same path. Any help is greatly appreciated. TIA.


r/FastAPI • • Apr 06 '24

Question Need some points in the right direction for webhooks.

2 Upvotes

Current project is a simple password manager, im working through the docs, but im curious if anyone has good resources for grasping webhooks. Based on my limited research i think i understand webhooks but i would like to expanded on and get better clarity on how to use them with fastapi


r/FastAPI • • Oct 11 '24

Question Error loading ASGI app

2 Upvotes

I am having problems running the main py script from this GitHub https://github.com/ZeroMeOut/SkeletonSAM2. From my little understanding, the format of the folders, the directory, and the file names are correct for it to run. But I keep getting the error in the title. I believe I am missing something somewhere, and I would like someone to help me.


r/FastAPI • • Aug 20 '24

Question The server doesn't refresh

0 Upvotes

Hi everyone, i'm new using fastApi, I think it's a Nice way to build apis however what it really pissed me off is when the server doesn't refresh on time I mean it has some delays for example I erased the whole code and it stills showing the last code version, I turn off the server, close pycharm Window and still showing the last code version although I Made changes before, do You know why does this happen to me? :( is this a hardware issue or My settings project?


r/FastAPI • • Aug 19 '24

Hosting and deployment Vercel deployment with aiohttp client

2 Upvotes

I've been struggling with deploying a fastapi app that has an aiohttp client. The minimal app without the client worked fine. Once I've included the client it seems that it fails to start the ClientSession. I've tried using both lifespan, and startup / shutdown events of FastAPI https://fastapi.tiangolo.com/advanced/events/, but it seems none of them get executed on vercel. Locally everything works fine. There is also an unanswered, similar issue on the repo: https://github.com/orgs/vercel/discussions/4637 Does anyone have an idea how to solve this? Or should I look for a different hosting platform?


r/FastAPI • • Jun 01 '24

Question Pydantic Validation error on Mongo Db documents with Beanie

2 Upvotes

I am trying to fetch my all document with Beane ODM of mongo db with fastapi but I am getting error saying

Field required [type=missing, input_value={'_id': ObjectId('6653533..., 4), 'type': 'Expense'}, input_type=dict]

Document Scheme

from beanie import Document

from uuid import UUID
from bson import ObjectId as _ObjectId
from typing import Optional, Union



class Transactions(Document):
    _id : Optional[_ObjectId] = None
    created_at: str
    amount: int
    category: str
    notes:str
    date: str
    user_id: UUID
    type: str


    class Settings:
        name = "transactions"

And the endpoint which fetching all the documents.

@@app.get('/get_all_transactions')
async def get_all_transactions():
    transactions = await Transactions.find_all().to_list()
    return transactions


app.get('/get_all_transactions')
async def get_all_transactions():
    transactions = await Transactions.find_all().to_list()
    return transactions

r/FastAPI • • Aug 04 '24

Hosting and deployment Illegal instruction (core dumped) fastapi run app/main.py --port 8000

2 Upvotes

I need Help with Docker on M2 ARM to AWS Elastic Container Service. This was once working for many months. Then AWS updated to docker 25 and I don't know where or when it happened but it's broken. I created a script to run the fastapi an I am getting this error. I have isolated it to main.py failing . I am loading setting config but it's not even getting to that point. This all works fine locally and I have no issues locally. This is a hard cookie to crack. I have isolated the problem by having a startup script run the command and wait 3 minutes before bailing out and during that time I am getting a log output.

This is the main.py

```

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

which does work but adding anything causes that error. I tried to revert back to older releases that have worked but none of them work any more. I have already tried in docker to add platform as arm and even remove Rosetta from the settings, but nothing seems to work. Here is the typical error I get

2024-08-04T06:56:52.334Z INFO Importing module app.main

2024-08-04T06:57:05.808Z ./start_server.sh: line 27: 9 Illegal instruction (core dumped) fastapi run app/main.py --port 8000

2024-08-04T06:57:05.808Z Error occurred in script at line: 27

2024-08-04T06:57:05.808Z Exit status of last command: 132

2024-08-04T06:57:05.808Z Bash error message: fastapi run app/main.py --port 8000

I will try to build x86 and make it for arm64 but it's very frustrating. Any help or tips are welcome. Not sure if how to show more debugging. Nothing seems to work.


r/FastAPI • • Sep 10 '24

feedback request Review and suggest ideas for my RAG chatbot

Thumbnail reddit.com
2 Upvotes

r/FastAPI • • Aug 29 '24

Question Getting extra param *Args and **kwargs

2 Upvotes

Hii i made this api and i have given 3 param that is page, pagesize, search.
Why this two param are coming as required and why is it even coming?
how to solve this?


r/FastAPI • • Oct 13 '24

Question Not able to access FastAPI service hosted in my laptop from my mobile

2 Upvotes

I have hosted a FastAPI server in my laptop in http mode.

The hostname I used in the configuration is: 0.0.0.0 and the port is 8000.

My laptop and my mobile are connected to my WiFi router.

I try to access the service from my mobile's browser with the below address:

http://192.168.1.25:8000 (192.168.1.25 is my laptop IP address in the local network)

The browser says that 'The site can't be reached'.

Not sure what could be the issue. Can I have some suggestions pls.


r/FastAPI • • Aug 06 '26

pip package fastapi-resumable-stream: SSE that survives a page refresh

3 Upvotes

Common problem with LLM streaming endpoints: client refreshes or the connection drops mid-response, and the whole stream is gone. Client has to start over, and you've already burned the tokens for nothing.

Built a small Redis-backed library for this. The producer runs as a background task, independent of the request, and buffers chunks so a client can reconnect and ask for everything after chunk N.

@app.post("/chat/{conversation_id}/stream")
async def start_stream(conversation_id: str, prompt: str):
    return await start_conversation_stream(
        stream, registry, stop, conversation_id, stream_id,
        producer=lambda: call_llm(prompt),
    )

Also has an explicit stop that's separate from disconnect (closes the producer's generator, so it actually cancels whatever's underneath, not just the client-facing stream), and thin adapters for LangChain and CrewAI plus encoders for the AG-UI and Vercel AI SDK wire protocols if you're feeding a useChat frontend.

pip install fastapi-resumable-stream[fastapi] https://github.com/ofershap/fastapi-resumable-stream

It's new (0.2.1), feedback welcome.


r/FastAPI • • Oct 12 '26

feedback request Built my first real FastAPI project a few months ago, it finally has a proper frontend now

Thumbnail
gallery
33 Upvotes

Some of you might recognize the repo. I posted an earlier version here it was basically just a FastAPI backend and Swagger docs. A few people gave it really useful feedback then the market-data part stopped working, so I deleted the post instead of pretending it was fine.

It’s working again now, and it has an actual frontend.

It’s a stock research/watchlist app I use myself. I'm from finanace background, I trade, and I wanted somewhere to track stocks and write research notes that save the price I was looking at when I wrote them. It tracks 14 market indices and supports stock watchlists, quotes, news, and notes.

The stack is FastAPI, async SQLAlchemy, Postgres, JWT auth, Docker, and a small HTML/CSS/JS frontend.

The most annoying bug was that Yahoo Finance worked locally but started returning '401 Invalid Crumb' errors from Render. I changed the quote path to fall back to Yahoo’s chart/history data, and added RSS sources for news when the main news path fails. It took longer than I expected to get local and deployed behavior lined up.

Note: This isn’t a trading platform, and it’s definitely not finished. I’m posting it again because it’s now more than API docs, and because the last round of feedback was genuinely helpful. If you spot something badly designed, confusing, or fragile, I’d rather hear it.

Repo: https://github.com/ah4ddd/first-order

I’m leaving the live Render URL out of the post; it’s linked from the repo for anyone who wants to try it.


r/FastAPI • • Jul 10 '26

Hosting and deployment Best place to host fast api applications

12 Upvotes

I have simple fast api app it recieves requests and either writes data to the sqlite dB or fetches data from it what would be the best place to host it preferably for free since its a small hobby project but would scale up successful


r/FastAPI • • Jul 22 '26

Question Where to learn FastAPI?

35 Upvotes

I have a good Python experience. I did basic backend dev with PHP and Flask before, so the beginner concepts won't be that much challenging. What I'm looking for is a single well-organized course to learn FastAPI deeply. I've checked out the official documentation, which is absolutely great and lovely, and I will use that as a reference.

It doesn't matter if the course is certified or not. I focus on the skills I'll gain. It's more preferred to be a free course though (but don't hesitate to share paid courses too if they are really worth paying for).


r/FastAPI • • Oct 12 '26

Other What I moved into a FastAPI service, and the testing problem that made me do it

5 Upvotes

Hey everyone. I run a FastAPI service whose only job is executing AI agent graphs. No business logic and no user model. It does not publish a port either: a Django app is its only caller, over a typed WebSocket.

It used to live inside that Django app. I assumed the thing that would eventually drive it out was performance. It was testing.

Inside the monolith, the decision I cared about, which message routes to which capability, sat deep inside a WebSocket handler that had already authenticated a user and written a row. Asserting one routing decision meant opening a connection and seeding a conversation first. Worse, the model was reached through that object rather than across a boundary, so there was no single place to stub it and the fakes multiplied with the call graph instead of with the number of seams.

In its own service the same decision is a function from state to state. A test builds the state it wants, runs the graph, and asserts on what came back. Nothing to connect to and nobody to log in, and the only thing faked is the model's HTTP response.

Why FastAPI specifically, since the service could have been anything. It brings almost no opinions, which is what you want when there is exactly one job. It is async native, and this work is almost entirely awaiting model calls and pushing tokens back. And everything around it is Pydantic shaped already, so the types line up without adapters: LangGraph for the flow, Pydantic AI for the agents, chanx for typed WebSocket messages and the AsyncAPI document the caller generates its client from.

Where the line goes, which is the part worth stealing even if you never touch an agent. Not by layer or by framework, but by which kind of state each side owns. The business service owns the record, anything a page reload has to find. This service owns working state, a graph checkpoint in my case, which is an odd category: not a business record, but not rebuildable either. So if losing it means losing data it belongs in the record, and if it only costs speed or fidelity this side can keep it.

That is a rule for what can move out, not for breaking a monolith into domains, where each service owns records of its own and the argument is different.

Written up in full, as part of a series on building agent systems as declared, typed graphs, with a working three-service repo:

https://huynguyengl99.github.io/posts/agent-graph-engineering/split-the-services/

https://github.com/huynguyengl99/agent-graph-engineering

Hope it is useful, and if the repo helps you a star would be appreciated 😄


r/FastAPI • • Dec 21 '25 Bravo

pip package Open-source FastAPI full-stack template for AI/LLM apps: Production-ready generator with Next.js frontend, PydanticAI, and 20+ integrations

80 Upvotes

Hey r/FastAPI,

I've created an open-source project generator built around FastAPI for quickly setting up production-ready full-stack AI/LLM applications. If you're working with FastAPI and need to skip the boilerplate for things like auth, databases, background tasks, and AI integrations, this might be useful.

Repo: https://github.com/vstorm-co/full-stack-fastapi-nextjs-llm-template
(Install via pip install fastapi-fullstack, then generate with fastapi-fullstack new – interactive CLI for selecting features)

FastAPI-centric features:

  • High-performance async API with Pydantic v2 for type-safe schemas and validation

  • Clean architecture: Versioned routes, dependency injection, middleware for security (CORS, CSRF, rate limiting with slowapi)

  • Authentication: JWT with refresh tokens, API keys, OAuth2 (Google) – all integrated seamlessly

  • Databases: Async support for PostgreSQL (SQLAlchemy), MongoDB, or SQLite, with Alembic migrations

  • Background tasks: Plug-and-play with Celery, Taskiq, or ARQ for distributed queues

  • AI/LLM integration: PydanticAI agents with tool calling, WebSocket streaming, and persistence – built on FastAPI's async strengths

  • Observability: Logfire instrumentation for tracing requests, queries, and agent runs; plus Sentry/Prometheus

  • Django-style CLI: Custom management commands with auto-discovery for FastAPI apps (e.g., my_app db migrate, my_app user create)

Optional Next.js 15 frontend (React 19, Tailwind) with real-time chat UI, but you can generate backend-only if preferred. Over 20 configurable integrations to mix and match.

Inspired by tiangolo's full-stack-fastapi-template, but extended for AI focus, modern stacks, and more flexibility.

Screenshots, demo GIFs, architecture diagrams, and docs in the README.

Feedback from the FastAPI community would be awesome:

  • How does this compare to your go-to setups for larger FastAPI projects?

  • Any FastAPI-specific pain points it misses (e.g., more advanced deps or middleware)?

  • Ideas for new integrations or improvements?

Contributions welcome – let's make FastAPI even better for AI apps! 🚀

Thanks!


r/FastAPI • • Feb 20 '26

Other Why I'm using SQLite as the only database for a production SaaS (and the tradeoffs I've hit so far)

103 Upvotes

I've been building a discovery engine for solo-built software — think of it as intent-based search where users type a problem ("I need to send invoices") and get matched to tools, instead of browsing by product name or upvotes.

The stack is FastAPI + SQLite. No Postgres. No Redis. No managed database service. Just a single .db file.

I wanted to share what I've learned after a few weeks in case it helps anyone evaluating the same choice.

Why SQLite

  • Zero operational overhead. No connection pooling, no database server to monitor, no Docker Compose dependency. The app and the data live together.

  • Reads are absurdly fast. My use case is read-heavy (search queries) with infrequent writes (new tool submissions, maybe 10-20/day). SQLite handles this without breaking a sweat.

  • Backups are cp. I rsync the .db file nightly. That's the entire backup strategy. It works.

  • Deployment is simple. One process, one file, one VPS. I deploy with a git pull and a systemd restart. The calm tech dream.

The tradeoffs I've hit

  • Write concurrency. SQLite uses a file-level lock for writes. With WAL mode enabled, concurrent reads are fine, but if you have multiple processes writing simultaneously, you'll hit SQLITE_BUSY. My solution: a single FastAPI worker handles all writes via a background task queue. If you're running Gunicorn with multiple workers, this is something you have to think about.

  • Full-text search. SQLite's built-in FTS5 is surprisingly capable. I'm using it for intent-based search with custom tokenizers. It's not Elasticsearch, but for a catalog of a few thousand items, it's more than enough. The main limitation: no fuzzy matching out of the box. I handle typo tolerance at the application layer.

  • No native JSON operators (sort of). SQLite has json_extract() and friends, but they're not as ergonomic as Postgres's -> and ->> operators. I store structured metadata as JSON blobs and parse in Python when needed. Minor annoyance, not a blocker.

  • Schema migrations. There's no ALTER COLUMN in SQLite. If you need to change a column type, you're rebuilding the table. I use alembic with the batch mode for this, which wraps the create-copy-drop-rename dance. Works fine, just feels clunky.

Where the line is

I think SQLite stops being the right choice when:

  • You need concurrent writes from multiple services (microservices, multiple API servers)

  • Your dataset exceeds ~50GB and you need complex analytical queries

  • You need real-time replication to a read replica

For a solo-built SaaS serving hundreds or even low thousands of users with a read-heavy workload? SQLite is underrated. The operational simplicity alone is worth it.

Happy to answer questions about the setup. I'm using Python 3.12, FastAPI with async endpoints, and SQLAlchemy 2.0 with the synchronous SQLite driver (async SQLite drivers exist but add complexity I don't need).


r/FastAPI • • Nov 26 '25

feedback request To much handy work ? i switched from django to fast api

34 Upvotes

Hi, I was working on a project with Django, but then I thought of switching to FastAPI because I want a real-time app along with GraphQL.

Man, I’m frustrated there’s too much manual work. Every file I need to create myself, and keeping track of all these layers is exhausting.

I’m using Pydantic for the database with Strawberry for GraphQL, and I have separate layers for DTOs, services, CRUD, REST APIs, and GraphQL.

Am I doing something wrong, or what is the best approach? I can’t seem to find a way to generate simple CRUD operations automatically like in Django.

Edit:
so hello guys again after last night and after i saw many of your comments i felt like i was a damn little girl who is crying over why unicorn do not exist so i took my shit together and i m doing it the hard way the right way and i m happy and i m moving forward in very good way thank you


r/FastAPI • • May 18 '26

pip package Better-Auth integration with FastAPI

6 Upvotes

Hey there I just published the Better Auth integration with FastAPI.

https://github.com/lukonik/fastapi-betterauth

Basically it validates the token coming from Authorization header and fetches the user via JWKS from the Better Auth

It uses pyjwt under the hood to handle caching and security for you. Hope you like it 🔥


r/FastAPI • • Jan 14 '25

Tutorial Best books to learn FastAPI

58 Upvotes

Hi guys,
I am an experienced Java developer, and recently I got a great opportunity to join a new team in my company. They are planning to build a platform from scratch using FastAPI, and I want to learn it.

I generally prefer learning through books. While I have worked with Python and Flask earlier in my career, that was a few years ago, so I need to brush up.

Could you guys please suggest some great books to get started with FastAPI?


r/FastAPI • • Mar 21 '26

Question good tutorial for fast api, cant find a new good one

24 Upvotes

all the tutorials i see are 2 or 4 years old, is there a modern one i can use