r/FastAPI • • Mar 19 '24

Question Is it possi to turn off the internal debugger / exception handler?

1 Upvotes

Hey, I just wanted to ask if it's possible to turn off the internal debugger or exception handler.

My reason for this is, so that my pycharm debugger can stop on an unhandled exception and I can check the current state and variable.

In flask this was possible with

app.run( debug=True, passthrough_errors=True, use_debugger=False, use_reloader=False )


r/FastAPI • • Mar 21 '24

Question How to prevent fields that are not set in the model to appear in the API response?

0 Upvotes

I have a router.get() in which I am passing a dictionary to the model.

The API model has some default values set to attributes and they appear in the response even though they are not present in the dictionary passed to the API model.

How do I prevent the fields to appear in my response?


r/FastAPI • • Apr 23 '24

Question Inline templating engines

1 Upvotes

I was wondering if anyone has come across anything like https://github.com/a-h/templ or https://hono.dev/guides/jsx, but for python. For context, I am familiar with jinja2, mako, etc. but find them to be unintuitive due to the loose coupling of logic (ex: database calls) and templating (ex: generating a list from the database results). Therefore, I am looking for a "inline" templating solution.


r/FastAPI • • Apr 17 '20

Question CamelCase Models with FastAPI and Pydantic

1 Upvotes

if you need to keep your models in snake_case but your REST API request/reponse bodies need to be in camelCase. I have created this package for you :), enjoy
https://ahmednafies.github.io/fastapi_camelcase/


r/FastAPI • • Apr 03 '21

Question Docker deployment not reloading, what am I doing wrong?

1 Upvotes

Trying to deploy a simple FastAPI web app with Docker but running into an issue when deployed through Docker where my scripts either aren't being called or the endpoint just isn't updating, not sure which.

Aside from the essential imports & instantiation of FastAPI object, my main.py looks like this:

@app.get('/status')
async def status():
    available = checkAvailable() # imported method, calls an external API
    
    if available:
        return {"status" : "free"}
    else:
        return {"status" : "busy"}
if __name__ == '__main__:
    uvicorn.run('app.main:app', port=80, host='0.0.0.0', reload=True)

When I deploy uvicorn locally everything works as expected. Changing availability in the external API & then refreshing the FastAPI properly changes the status.

When deployed via Docker though, the status at the point of the docker image being created is maintained no matter any refresh. My Dockerfile is as follows:

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8
ENV PYTHONDONTWRITEBYTECODE=1 
ENV PYTHONUNBUFFERED=1
WORKDIR /app/

COPY requirements.txt . 
RUN pip3 --no-cache-dir install -r requirements.txt
COPY . /app/
CMD ["python3", "./app/main.py"]

I've google around and couldn't find anyone talking about having this issue and I really just don't understand if my error is my understanding of FastAPI or Docker, or both.

Any and all help is appreciated. I know there's lots to improve with the app but I'm just starting to learn and want to have a successful deployment of a simple app before digging deeper.


r/FastAPI • • Jan 30 '21

Question Websocket streaming {"detail":"Not Found"}

1 Upvotes

Hi everyone! I'm trying to create a websocket to stream data using this example: https://stribny.name/blog/2020/07/real-time-data-streaming-using-fastapi-and-websockets/ and I have also tried implementing the top example from here: https://fastapi.tiangolo.com/advanced/websockets/

When I do uvicorn main:app --reload all I get back from http://localhost:8000/ws is {"detail":"Not Found"}.

In the terminal after it says "application startup complete" all I get back is " 127.0.0.1:65000 - "?[1mGET /ws HTTP/1.1?[0m" ?[31m404 Not Found?[0m".

How do I debug this (I'm in debug mode but it doesn't seem to be doing anything)? Or does anyone know what the problem is? I'm on windows btw

Edit: I just tried to change uvicorn to uvicorn[standard] and pip install websockets, because I was getting "Unsupported upgrade request." but neither of those things solved my issue.


r/FastAPI • • Nov 18 '20

Hosting and deployment How to deploy my app to test my api

2 Upvotes

Hi everyone,

I am a very beginner in FastAPI and I am trying to deploy my api on my computer, but not locally.

I succeeded deploying it locally with the default address and port (127.0.0.1:8000), but I would like the api to be public and not only local. I did not manage to do this and cannot find any help online.

How could I do it with uvicorn?

I need this in order to access my api from a mobile app I am developing.

Thanks in advance for your help!


r/FastAPI • • Mar 07 '22

Question (HELP)Sending embed text mail within HTML mail using fastapi-mail

1 Upvotes

Hi, I need some help with email. I'm attempting to send an email through fastapi-mail (which works flawlessly). However, I also want to embed a plaintext version of the email in case certain devices dont support the HTML in my email. How do I go about doing this on FastAPI?

My current code :

async def send_email(email: list, instance: User):
    payload = {
        "email": instance.email,
    }


    message = MessageSchema(
        subject="Test mail",
        recipients=email,
        template_body={
            "test": "test"}
    )

    fm = FastMail(conf)
    await fm.send_message(message, template_name="email.html")

and the email.html file is a regular html file containing body and some <p> tags.


r/FastAPI • • Apr 21 '21

Tutorial Part 2 of FastAPI and Web scraping

Thumbnail
youtu.be
1 Upvotes

r/FastAPI • • May 20 '22

Question Database class in Fastapi

0 Upvotes

if a table already exixts do we need a class that represents the table which extends automap_base() or declaritive_base()


r/FastAPI • • Apr 24 '21

Question GET requests show Request Body in Swagger UI

1 Upvotes
  • Python: 3.6.8

  • FastAPI: 0.63.0

  • Pydantic: 1.8.1

  • Starlette: 0.13.6

I have gone through the documentation and built a multi-file app. All of my requests work fine via curl, requests, etc., but when I view them in the Swagger UI, all of the GETs have a Request Body included, which defaults to:

[
    "string"
]

In order to successfully send any requests via the Swagger UI, you need to first clear the Request Body text box before clicking Execute.

Is there a way to remove the Request Body from GET requests in the Swagger UI?

EDIT: This was caused by a bad type hint (see here).


r/FastAPI • • Sep 17 '21

Question what does ssl_mode = 'prefer' mean in the context of fastAPI?

1 Upvotes

i'm connecting my fastApi app to a postgres db:

host_server = '172.13.27.151' #wsl ip
db_server_port = '5431' #wsl port to container
database_name = 'publish'
db_username = 'db1'
db_password = 'hi'
ssl_mode = 'prefer'
DATABASE_URL = 'postgresql://{}:{}@{}:{}/{}?sslmode={}'.format(db_username, db_password, host_server, db_server_port, database_name, ssl_mode)

this obviously works, but i have no idea what that variable entails. i have fastAPI in a container making this call to a postgres db in another container.

and in my production environment i have the main app behind an nginx server. so i'm just wondering if this is something i need, and why

thanks!


r/FastAPI • • May 27 '26

Other Built a /advisor command for Claude Code — Opus directs parallel Sonnet runners that actually read your files

Thumbnail
reddit.com
1 Upvotes

r/FastAPI • • Oct 24 '25

Question Launching a route automatically again when it should be finished when request is too long

0 Upvotes

Hello, I have a little problem
I'm doing an API with FastAPI on a jupyter notebook server
I'm using a route to get informations of all patients,

What my code does:

It takes a list of patients from calling the router get_patients_disponibles

then, it makes a loop for every patient in that list that:

call the router get_patient_complet

Here is the code:

from Services.redcap_service import redcap_service

from Routers.set_patient import get_patients_disponibles

from Routers.patient_complet import get_patient_complet

router = APIRouter(prefix="/all-patient-complet", tags=["All Patient Complet"])

u/router.get("")

async def get_all_patient_complet():

try:

result = await get_patients_disponibles()

patients_list = result["patients_disponibles"]

patients_list = patients_list[:25]

except Exception as e:

print(f"❌ Erreur récupération patients: {e}")

patients_list = redcap_service.get_patients_inclus()

if not patients_list:

return {"message": "Aucun patient à traiter"}

print(f"🚀 LANCEMENT - {len(patients_list)} patients")

print(f"📋 Liste des patients: {patients_list}")

for patient_num in patients_list:

print(f"➡️ {patient_num}")

patient_actuel = await get_patient_complet(patient_num) #await

print("✅ TERMINÉ")

return {"message": "Terminé", "patients": len(patients_list), "Patient actuel": patient_actuel}

So I'm using a swagger
The problem is that, you see the "patients_list = patients_list[:25]", when I just take the 20 first (= patients_list[:20], the operation takes about 1min and half, and it works perfectly on my swagger
But when I take the 25 first like in the example, it does the operation for every patient, but when it does for the last, I get a 200 code, but the whole router get_all_patient_complet gets called again as I have my list of patients again and on my swagger, it turns indefinitely
You have pictures of this


r/FastAPI • • Feb 21 '26

pip package Gdansk: Generate React front ends for Python MCP servers

1 Upvotes

Hi r/FastAPI,

What My Project Does

Gdansk makes it easy to put a React frontend on top of a Python MCP server.

You write your application logic in a Python MCP server. Gdansk generates a React frontend that connects to it out of the box, so you can ship a usable UI without standing up and wiring a separate frontend manually.

As OpenAI and Claude app stores gain traction, apps are becoming the primary interface to external tools. Many of us build serious backend logic in Python, but the UI layer is often the bottleneck. Gdansk is designed to close that gap.

Repo: https://github.com/mplemay/gdansk

Target Audience

  • Python developers building MCP servers

  • Developers experimenting with AI app stores

  • Teams that want to prototype quickly

  • Builders who prefer Python for backend logic but want a modern reactive UI

It works well for prototypes and internal tools today, with the intent of supporting production use cases as it matures.

Comparison

  • Versus building a React frontend manually for MCP:
    You still use React, but you do not need to scaffold, wire, and maintain the integration layer yourself. Gdansk handles the connection between the MCP server and the React app, reducing setup and glue code.

  • Versus rendering templates with Jinja (or similar):
    Jinja-based apps typically render server-side HTML with limited interactivity unless you add significant JavaScript. Gdansk generates a fully reactive React frontend, giving you client-side state management and richer interactions by default.

Feedback is welcome.


r/FastAPI • • May 03 '26

Question How to read documentation

Thumbnail reddit.com
1 Upvotes

what is your opinion on this?


r/FastAPI • • May 25 '26

Hosting and deployment FastAPI in Snowflake's SPCS (Container Services)

1 Upvotes

Hi!
Deploy FastaAPI to Snowflake

  • Fully declarative — infrastructure defined in snowflake.yml and spec.yml, deployed with the snow CLI

https://github.com/MiguelElGallo/FastAPI-in-Snowflake

Enjoy :)


r/FastAPI • • Mar 01 '26

pip package A New PyPI Package: FastAPI-powered API to Manage Dokku Server

Thumbnail
reddit.com
1 Upvotes

r/FastAPI • • Oct 28 '25

Question Problem with FastAPI and VSCODE

1 Upvotes

Hi everyone, im trying to learn FastAPI in school but when I try using "import FastAPI from fastapi" in the beggining of the code, it gives me an error as if I didnt have it downloaded. Can someone help? I already have all this extensions downloaded and im using a WSL terminal on Visual Studio Code.

annotated-doc==0.0.3

annotated-types==0.7.0

anyio==4.11.0

certifi==2025.10.5

click==8.3.0

dnspython==2.8.0

email-validator==2.3.0

fastapi==0.120.1

h11==0.16.0

httpcore==1.0.9

httptools==0.7.1

idna==3.11

Jinja2==3.1.6

markdown-it-py==4.0.0

MarkupSafe==3.0.3

mdurl==0.1.2

numpy==2.3.4

pyarrow==22.0.0

pydantic==2.12.3

pydantic_core==2.41.4

Pygments==2.19.2

pylance==0.38.3

python-dotenv==1.2.1

python-multipart==0.0.20

PyYAML==6.0.3

rignore==0.7.1

sentry-sdk==2.42.1

shellingham==1.5.4

sniffio==1.3.1

starlette==0.49.0

typing-inspection==0.4.2

typing_extensions==4.15.0

urllib3==2.5.0

uvicorn==0.38.0

uvloop==0.22.1

watchfiles==1.1.1

websockets==15.0.1


r/FastAPI • • Jan 13 '26

pip package Rabbit Manager – Python Utility for RabbitMQ Queues

Thumbnail reddit.com
1 Upvotes

r/FastAPI • • Apr 26 '26

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

1 Upvotes

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

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

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

Current approach:

  • There are 10–15 document types that I send directly to OpenAI.

  • For images (JPG, PNG, JPEG): I download them, base64 encode them, and send them to OpenAI.

  • For PDFs: I download them, upload them via OpenAI’s file API, and then send the file ID for processing.

  • All of this is done in parallel using semaphores:

    • OPENAI_SEMAPHORE = 30

    • DOWNLOAD_SEMAPHORE = 15

Problem:

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

Questions:

  • How can I reduce memory usage in this workflow?

  • Is there a better architectural approach to handle this kind of workload?

  • How can I avoid having too many documents in memory at once while still maintaining performance constraints?

async def _stream_download_file(url: str, ext: str) -> str:
    """
    Stream-download a file to disk in 64KB chunks.
    Never holds the full file in memory — writes directly to disk.
    Returns the path to the temp file.
    """
    async with DOWNLOAD_SEMAPHORE:
        temp_path = None
        try:
            temp = tempfile.NamedTemporaryFile(delete=False, suffix=ext or ".tmp")
            temp_path = temp.name
            temp.close()


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


            return temp_path


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

r/FastAPI • • Sep 04 '25

Other Would you settle for FastAPI or Django in the long run?

45 Upvotes

Would you settle for FastAPI or Django in the long run as per a single framework for all your task or would django be it the one ?

What are your views because django(betteries included) has its own benifits and fastapi(simplicity) as its own and also some packages that give fastapi some batteries already that’s already being used in industry.

What are your thoughts on choosing one over other and will you settle down for one?


r/FastAPI • • Dec 23 '25

Question How much did FastAPI’s "Bus Factor" actually matter in your production choice?

21 Upvotes

Hi everyone,

I'm currently in the middle of a framework debate for a new project at work. We love FastAPI, but the "Bus Factor" (the project being heavily tied to a single maintainer) is the #1 point of pushback from our senior architects.

For those of you running FastAPI in enterprise/production environments:

  • Was the governance model a dealbreaker for your team? If so, how did you get past it?

  • Do you view the "Bus Factor" as a real risk in 2025, or do you feel the underlying stability of Starlette/Pydantic makes it a non-issue?

  • Did anyone choose Litestar specifically because of its community-governed model? Any regrets or "grass is greener" moments?

I'm less interested in the technical features and more in the institutional trust side. How do you justify building a long-term company asset on a project that still feels very centralized?

Curious to hear if this was a "real world" problem for you or just a theoretical one that managers worry about.


r/FastAPI • • Sep 17 '24

Tutorial Beta Acid open sourced its FastAPI reference architecture

Thumbnail
github.com
21 Upvotes