r/FastAPI • • Aug 17 '24

feedback request Feedback wanted: Creduse - A FastAPI-powered credit system for apps and games

5 Upvotes

Hey fellow FastAPI devs

I'm a solopreneur who recently built Creduse, a FastAPI-powered API that makes it easy to integrate a credit system into your apps and games. I'd love to get your feedback on it!

Why I built Creduse:

  1. To support the growing demand for pay-as-you-go models

  2. To help founders increase user engagement

  3. To provide a nice way to limit cost-intensive features (particularly relevant for AI applications)

As a developer myself, I built Creduse with a focus on making it as developer-friendly as possible. I'm hoping it can be a useful tool for startups and indie devs in our community.

I've set up a trial so you can test the API and share your thoughts. I'd really appreciate any feedback on:

  • The API design and implementation

  • Documentation clarity (doc.creduse.com)

  • Ease of integration

  • Any features you'd like to see added

You can find more information and start a trial at creduse.com

Thanks in advance for your insights!

Francesco


r/FastAPI • • Sep 25 '24

Tutorial How to change log levels without restarting in FastAPI

Thumbnail
prefab.cloud
5 Upvotes

r/FastAPI • • Sep 13 '24

Tutorial HTTPS redirect does not exist in FastAPI/Starlette or infinite loop

5 Upvotes

To begin with, FastAPI has fastapi.middleware.httpsredirect.HTTPSRedirectMiddleware and this class refers to starlette: starlette.middleware.httpsredirect.HTTPSRedirectMiddleware,

What it does? It checks the protocol and port, if protocol equals to is http than redirect to https if port is 80 than redirect to http.

On this point everything is good. But what will happen if you want to host the FastAPI project somewhere like Heroku? You will have an infinite loop.

Why? Consider Heroku as an proxy, it gets the request with HTTPS and proxies the request to your FastAPI app with HTTP, cause the internal connection can always be considered as trusted, actually because it's in the local heroku network.

So, you configured HTTPSRedirectMiddleware, what will happen? Request goes to Heroku "proxy" with HTTPS -> "proxy" recieves the request and sends HTTP request to your FastAPI app, you app recieves HTTP request and redirects to the first step. The thing is your FastAPI app will never HTTPS request, so it thinks it never secure.

How to fix?

When I was building Futurama API, the code: https://github.com/koldakov/futuramaapi I spent couple of hours understending why https requests go to infinite loop, but Django apps works perfectly fine. the thing is Django supports HTTPS redirects behind the proxies out of the box, how Django handles it? It checks the "host", "X-Forwarded-Proto", "X-Forwarded-Port" in headers and if everything matches the request is considered as trusted, so I've implemented the kind of the same thing for FastAPI. The code you can find here: https://github.com/koldakov/futuramaapi/blob/main/futuramaapi/middlewares/secure.py

Actually because of this reason you can find "a lot of" questions in FastAPI section why url_for shows http instead of https in the templates. If you host your FastAPI project behind the proxy the project always will be under HTTP.


r/FastAPI • • Feb 06 '23

Tutorial I made an in depth video about deploying fastapi to AWS ec2 with all the batteries

5 Upvotes

Hello, long back I created a video about deploying Django to aws. It got much attention and many wanted me to make a video about deploying Fastapi to AWS. Finally, I made one and it's a little over 50 minutes. In the video, I talk about setting up an app locally and deploying to aws ec2 with python3, uvicorn, supervisor and Nginx. Let me know what you guys think, here or on youtube.

https://www.youtube.com/watch?v=E5IhKYT7ecU


r/FastAPI • • Oct 13 '22

Other The Best Python Framework?!

Thumbnail
youtu.be
5 Upvotes

r/FastAPI • • Sep 17 '23

Question Looking for Open source repository built using FastApi

5 Upvotes

Hi guys, I'm a python developer and want to dive into FastApi. I would be greatfull if you could recommend me some opensource projects to contribute to.


r/FastAPI • • Jan 19 '21

Question How to override default 404 route not found

5 Upvotes

Sorry this is probably a very noob question.

So I google and only found very few issues on this. But none of them answers how to catch only route not found. Both of the following links are saying how to catch all errors, if I understand correctly.

https://fastapi.tiangolo.com/tutorial/handling-errors/

https://stackoverflow.com/questions/62986778/fastapi-handling-and-redirecting-404

The doc doesn't even document how to override the default error message {"detail":"Not Found"} . Am I missing something?

I can of course catch all errors then handle them individually but it seems over-complicating things and this is a weird approach to solve this common issue.

I am actually using fastapi to build a small traditional HTML website - none of my route returns JSON.

I know it's of a misuse of the framework but I thought since it supports Template and HTML response so I just give it a try. Or should I just switch back to Flask?


r/FastAPI • • Aug 03 '24

Other open source project for FAST-API

23 Upvotes

Hi, I'm looking for an open source project to contribute some code to, a Python developer with two years of experience, looking for an open source project to strengthen my backend knowledge. I'm looking for a list of projects or something like that.. that you can enter the project easily on the backend side 💻🛠️


r/FastAPI • • Mar 29 '25

Hosting and deployment I created small TODO app in FastAPI, React, Mongodb Atlas, and AWS

11 Upvotes

I am a complete noob when it comes to programming. I don't understand how bug production projects work.

I started doing this project just to learn deployment, I wanted to make something that is accessible on the internet without paying much for it. It should involve both front end and backend. I know little bit of python so I started exploring using chatgpt and kept working on this slowly everyday.

This is a very simple noob project, ignore if you don't like it, no hate please. Any recommendations are welcome. It doesn't have a user functioning or security. Anyone can do anything with the records. The git repo is public.

Am going to shut down the aws environment soon because I can't pay for it but I thought to showcase it once before shutting down. The app is live right now on AWS, below link.

Webapp live link: https://main.d2mce52ael6vvq.amplifyapp.com/

repolink: https://github.com/desh9674/to-do-list-app

Also am welcome who wants to start learning together same as me.


r/FastAPI • • Aug 21 '21

Question Shell for Fast api ?

11 Upvotes

There is shell in django , My teams wants the same for Fast api. I tried with IPython but the problem is I can't use Tortoise orm Queries as it says database has no connection and other stuff. My question : Is there any way to make or install a shell for fast api project.


r/FastAPI • • Nov 05 '21

Tutorial Full FastAPI Course

12 Upvotes

Since using FastAPI I have enjoyed literally everything about it. It has become my go to API framework hands down! So I put together a course that really demonstrates how "Fast" FastAPI really is.

For all my friends who are interested in learning the fastest growing web development framework for Python, I created a ~10 hour course. The course covers JWT (JSON Web Tokens), password bcrypt hashing, authorization, security, routing, database (MySQL) and more! Sales ends Friday (11/19).

Cheers friends!

>>> Udemy - FastAPI Course <<<


r/FastAPI • • Jul 14 '22

Tutorial Using PugSQL and FastAPI

Thumbnail
propelauth.com
12 Upvotes

r/FastAPI • • Apr 22 '25

Question Urgent - No changes on localhost:8000/docs

0 Upvotes

So, I am working on a project, but whatever changes I make in my project, my swagger docs are stuck on only one state, even I add new routes and new changes, those changes are not there, even I delete all code of routes and redo with different route tags and stuff, but still stuck the old version, tried erasing cache of the browser.

What to do? Please guide, it's urgent.


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 • • Oct 08 '26

Other Production-grade Agent Graph Engineering: a FastAPI agent service and blog series, distilled from 5 years

6 Upvotes

Hey everyone. I have been building realtime AI assistants for about five years, and have just put a distilled, working version of the architecture in public with a series explaining each decision.

The reason I am posting here is the agent half of it, which is FastAPI. That service has exactly one job, running the agent graphs and talking to the backend, so I wanted something small that would not bring a worldview with it. It is async-native, which matters when the work is awaiting model calls and pushing tokens back. And the libraries around it are Pydantic-shaped already, so the types line up without adapters in between.

What is inside that service, briefly: LangGraph for the flow with Postgres checkpointing so a run can pause for a human and resume later, Pydantic AI for the agents and their typed outputs, chanx for typed WebSocket messages and the AsyncAPI document it generates clients from, and OpenTelemetry opening a span per graph node. Tests mock the model at the HTTP layer rather than at the framework, so request building, SSE parsing, tool-call assembly and validation all still run for real.

We used to run all of this inside Django with Channels, and the image got big, the process got slow, and scaling the two independently was impossible.

Why I bothered writing it all down. What is online is mostly notebooks and quick chatbot courses. I went looking for one in-depth source on building a production AI assistant, including paid ones, and did not find it.

So, depending on where you are:

  • Running an assistant in production already: a reference for the realtime parts that hurt, dropped sockets and resumed runs in particular.

  • About to bolt an agent onto a service you already have: the calls worth making before they get expensive, starting with whether it belongs in the same process at all.

  • Levelling up: typed WebSocket contracts, generated clients and streaming are the shape the listings keep describing.

  • Taking client work: a base you can adapt and still hand over without apologising for it.

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

Part 0, the story: https://huynguyengl99.github.io/posts/agent-graph-engineering/before-it-had-a-name/

Part 1, the stack and why: https://huynguyengl99.github.io/posts/agent-graph-engineering/the-stack-and-why-each-piece-is-there/

It runs on a scripted model with no API key, so the whole flow is visible before you wire up a provider. The series is early, two parts up and a new one every couple of days, so feedback now genuinely changes the later ones 😄


r/FastAPI • • Feb 06 '26

pip package One-line PSI + KS-test drift detection for your FastAPI endpoints

7 Upvotes

Most ML projects on github have zero drift detection. Which makes sense, setting up Evidently or WhyLabs is a real project, so it keeps getting pushed to "later" or "out of scope".

So I made a FastAPI decorator that gives you PSI + KS-test drift detection in one line:

from checkdrift import check_drift

@app.post("/predict")
@check_drift(baseline="baseline.json")
async def predict(application: LoanApplication):
    return model.predict(application)

That's it. What it does:

  • Keeps a sliding window of recent requests

  • Runs PSI and KS-test every N requests

  • Logs a warning when drift crosses thresholds (or triggers your callback)

  • Uses the usual thresholds by default (PSI > 0.2 = significant drift).

What it's NOT:

  • Not a replacement for proper monitoring (Evidently, WhyLabs, etc)

  • Not for high-throughput production (adds ~1ms in my tests, but still)

  • Not magic - you still need to create a baseline json from your training data (example provided)

What it IS:

  • A 5-minute way to go from "no drift detection" to "PSI + KS-test on every feature"

  • A safety net until you set up the proper thing

  • MIT licensed, based on numpy and scipy

Installation: pip install checkdrift

Repo: https://github.com/valdanylchuk/driftdetect

(Sorry for the naming discrepancy, one name was "too close" on PyPI, the other on github, I noticed too late, decided to live with it for now.)

Would you actually use something like this, or some variation?


r/FastAPI • • Jun 02 '26

Other Bypassing the Python event loop for token-aware rate limiting with a Rust/PyO3

6 Upvotes

Usually when you run high-concurrency rate limiting inside FastAPI, you are usually forcing python's single threaded event loop to spend precious time on network driver I/O just to verify a token before the request even hits the application logic.

I wanted to see how cleanly I could isolate the Redis network layer outside of python, so I built rustgate using PyO3 and a multi-threaded tokio driver.

Disclaimer: This is basically a proof of concept. It's basically tied to another experimental crate I am working on (axum-rate-limiter), and so it's not super configurable or abstracted as of now. Could you use in production? Probably, but why?

That being said, the raw performance under a 100-concurrency flood on a heavy, dynamically rerouted endpoint turned out pretty efficient:

  • Pushed 1,128 req/sec without dropping a connection.

  • Fastest response hit 15.3 ms.

  • Fails closed instantly with immediate 429 rejections to protect downstream application logic.

The cool part: I benched a naked, no-op /health endpoint (literally just returning {"status": "ok"}) on the same machine, and it maxed out at 1,496 req/sec.

The fact that crossing FFI boundaries, handling memory pinning, and doing a multi-threaded Tokio to Redis round-trip only costs ~370 req/s, proves that the Rust integration added almost non existent overhead.

EDIT: Due to benchmarks criticism, I will try to update this tomorrow, run it on linux, using `uvloop`, using 8k connections, and will add a proper baseline.

If you're interested to in checking out the project go to:
https://github.com/MordechaiHadad/rustgate


r/FastAPI • • Jun 17 '26

feedback request I built a convention so AI agents stop scraping HTML meant for human eyes

6 Upvotes

I built AgentML — append `/agents` to any resource URL and instead of HTML, you get a structured workspace in json which helps the ai agents browse the internet very easily without help of screenshots and doms.It aims to provide ai agents and equivalent of HTML which was designed for humans.

Works with FastAPI in 2 lines:

from agentML import AgentML

agent = AgentML(app)

No separate tool server. No rewriting your backend. Your existing OpenAPI spec is enough to get started.

Think of it as MCP but for your existing HTTP API.

GitHub: https://github.com/priyanshu7739410


r/FastAPI • • Dec 02 '23

feedback request Evaluate my FastAPI tech Stack? FastAPI, Redis, Mongo, Celery & Websockets

6 Upvotes

I have a platform that allows users to configure an array of objects, these objects call them "stages".

each stage has instructions for how it will be executed. the output of each stage is passed into the input of the next.

  1. Async Endpoint

    • Function: Grabs an array of objects, referred to as "stages".

  2. Orchestrator Celery Task

    • Role: Iterates through each object in the array.

    • Each stage object contains instructions for its execution.

  3. Execution of Each Stage

    • Method: Every stage object is executed within a child celery task.

  4. Output Handling

    • Each stage's output is sent to a Redis cache.

  5. Data Access

    • Each following execution stage has access to the entire array's data stored in Redis cache.

  6. Output Transmission

    • Every execution sends its output to a websocket.

any gotchas/things to consider? suggesstions for how to deploy? i've been using render.com not totally impressed yet.

btw, if anybody is a pro FastAPI dev would love to get 1:1 advice shoot me a DM. happy to pay for your time.

EDIT: UML diagram: www.plantuml.com/plantuml/png/PP71QiCm44Jl-effxls17agCQdfh80xal9OtjOWZ2UqQuh-lhD22cuiGyzwC3jgBKjRvDfaN7Vd6a4IE9-gDIGLuvnC5nQwH9JYqOKZH1zs114sxLGxPZIoQIME6vOdpWXF9jSe7UzhQTlJJyAJP_zgH1rzYAjDLEDejFtClqLrPAprtnZGjNj_Nz_26pqozW7Ac1V42KVfcCLEC2MsPHBS6y07DgXW0jLZwjlRRExjP-U5LR1_uQ0ljD6R6OTOqQuKb_Qisph48FaW9bvZnnNTztZbtwmw7uNUcNCs-7EL7VW00


r/FastAPI • • Jul 29 '24

Tutorial Highlighting the strength and suitability of FastAPI while building APIs

6 Upvotes

Lately I have been using FastAPI a lot for my API development needs. Several features of FastAPI are highly impressive. These include:

  • Request parsing

  • Input validation

  • Response serialisation

  • Automatic API documentation

I wrote a post highlighting the strengths and suitability of FastAPI for API development and how it compares against Django.

https://levelup.gitconnected.com/why-should-you-switch-to-fastapi-and-how-it-compares-against-django-da6c3d83aefa


r/FastAPI • • Jul 03 '24

Hosting and deployment 403 Returned by backend. However React client shows the error as cors error

6 Upvotes

the issue that I am facing is my react build is hosted on one of my s3 buckets and it is delivered by a CloudFront distribution. the backend is powered by fast api and is hosted on ec2 at port 8506.

however to power it with https, it is also delivered via cloudfront distribution. now the problem is that I have setup jwt authentication with an expiry of 30 minutes.

the backend is succesfully setting and revoking the token within that interval. any api request from the react client is responded with a 403.

however react client shows it as a cors error. cors error missing allow origin header.

On local setup, everything is working fine. Please help.


r/FastAPI • • Feb 25 '23

Question JWT Authentication using Jinja templates

6 Upvotes

I am making a simple blog app to learn fastapi etc. I was following this tutorial to figure out jwt authentication. Securing FastAPI with JWT Token-based Authentication | TestDriven.io

Works great! I can create users, sign in and get a JWT back.

If I was making a separate frontend app, I would save the JWT in local storage and add the authorization header to the request.

Is there a solid way to do this with Jinja templates? How do I use this JWT in my requests? All of the tutorials I've found only show how to pass the token via postman/swagger/frontend app.

@app.get("/posts/create", response_class=HTMLResponse, dependencies=[Depends(JWTBearer())], )
def form_post(request: Request):
    return templates.TemplateResponse('create-post.html', context={'request': request})


@app.post("/posts/create", response_class=HTMLResponse)
def form_post(request: Request, title: str = Form(...), body: str = Form(...), session: Session = Depends(get_session)):
    post = Post(title=title, body=body)
    session.add(post)
    session.commit()
    return templates.TemplateResponse('create-post.html', context={'request': request})

r/FastAPI • • May 05 '23

pip package Created a library for fastapi to make life easier

6 Upvotes