r/FastAPI • • Nov 03 '24

Question Dependency overrides for unit tests with FastAPI?

8 Upvotes

Hi there, I'm struggling to override my Settings when running tests with pytest.

I'm using Pydantic settings and have a get_settings method:

from pydantic_settings import BaseSettings
class Settings(BaseSettings):
  # ...

  model_config = SettingsConfigDict(env_file=BASE_DIR / ".env")


@lru_cache
def get_settings() -> Settings:
    return Settings()

Then, I have a conftest.py file at the root of my projet, to create a client as a fixture:

@pytest.fixture(scope="module")
def client() -> TestClient:
    """Custom client with specific settings for testing"""

    def get_settings_override() -> Settings:
        new_fields = dict(DEBUG=False, USE_LOGFIRE=False)
        return get_settings().model_copy(update=new_fields)

    app.dependency_overrides[get_settings] = get_settings_override
    return TestClient(app, raise_server_exceptions=False)

However, I soon as I run a test, I can see that the dependency overrides has no effect:

from fastapi.testclient import TestClient

def test_div_by_zero(client: TestClient):
    route = "/debug/div-by-zero"

    DEBUG = get_settings().DEBUG  # expected to be False, is True actually

    @app.get(route)
    def _():
        return 1 / 0

    response = client.get(route)

What I am doing wrong?

At first, I thought it could be related to caching, but removing @lru_cache does not change anything.

Besides, I think this whole system of overriding a little clunky. Is there any cleaner alternative? Like having another .env.test file that could be loaded for my unit tests?

Thanks.


r/FastAPI • • Apr 09 '26

Hosting and deployment Who will host the application client server with FASTAPI Cloud?

8 Upvotes

I just got the invite to FASTAPI Cloud, however after reviewing the documentation I’m still not sure who will be responsible for hosting the front-end client server that runs on localhost:3000. From the documentation, my understanding is that FASTAPI Cloud will host the python back-end server that runs the REST API, but it does not mention anything about a JavaScript client server hosting. How and where should I deploy the client server to have a production like application hosting?


r/FastAPI • • May 06 '26

Question System Design and Security in Transaction Software

8 Upvotes

Well, yes, how can I build the backend for a transaction system? I need to build something like this, but what recommendations should I follow in terms of design and security?

Here’s my idea:

  1. A user requests a transaction, at which point a six-character alphanumeric code is generated.

  2. This code is shown to a second user, who must then confirm the transaction from their own frontend.

  3. The second user does not use the same frontend as the first (this isn’t important, but it’s worth noting that the first user can only initiate transactions, while the second can only confirm them).

  4. The transaction remains available for a maximum of three minutes; after this time, if the second user has not confirmed it, it enters an "EXPIRED" status.

  5. Once it has expired, a new code is generated with the counter reset, creating a new transaction.

  6. The backend must include a user manager login system so that system operations can be monitored and support provided, in addition to providing access to an audit log (to view the history of transactions being processed).

  7. I have a month and a half to complete all of this.


r/FastAPI • • Nov 04 '22

Tutorial Using FastAPI Inside Docker Containers

Thumbnail
blog.logrocket.com
16 Upvotes

r/FastAPI • • Mar 10 '26

feedback request Self-hosted social media scheduler with FastAPI, APScheduler and Beanie - dashboard, auth, file uploads and more

Thumbnail
gallery
16 Upvotes

Hello everyone!

After seeing some tutorials on FastAPI, it was time to finally create something useful from it. Been building Post4U over the past few weeks, an open source self-hosted scheduler that cross-posts to X, Telegram and Discord from a single REST API call. Just hit a point where the project feels substantial enough to share here.

What it does: One API call with your content, a list of platforms and an optional scheduled time. It handles delivery, tracks per-platform success and failure, persists jobs across container restarts and retries only the platforms that failed.

Stack decisions worth discussing: APScheduler with a MongoDB job store instead of Celery + Redis. MongoDB was already there for post history so using it as the job store too meant zero extra infrastructure and jobs survive restarts automatically. Genuinely curious if anyone here has hit issues with APScheduler in production because that is the decision I keep second guessing.

Beanie + Motor for async MongoDB ODM. Pairs really cleanly with FastAPI's async nature and the TimestampMixin pattern for automatic createdAt on documents saved a lot of repetition.

Security: After some good feedback from the community, added API key auth on all routes via X-API-Key header, validated using secrets.compare_digest to prevent timing attacks. File uploads go through python-magic to verify actual MIME type against an AllowList rather than just trusting content_type, size limit enforced in chunks before anything hits disk.

Dashboard: Built the frontend in Reflex, pure Python, compiles down to a React + Vite bundle. You can compose and schedule posts, post directly, view history, unschedule pending posts and attach media files, all without touching curl or API docs.

What is missing: Reddit integration is pending their manual API approval process. Will try Bluesky and Mastodon integrations after that.

Would love genuine feedback, comments, suggestions to improve on the APScheduler choice specifically or anything in general about the codebase.

GitHub: https://github.com/ShadowSlayer03/Post4U-Schedule-Social-Media-Posts


r/FastAPI • • Feb 19 '25

Other A SuperCharged FastAPI based framework for AI Development. Looking for collaborators

Thumbnail
github.com
34 Upvotes

Love fastapi and it’s pretty de-facto for building microservices in the AI space (agents, rag, backends)

But after building dozens of AI microservice and re-doing the routes every single time, I wanted to really standardize this.

So I came up with

https://github.com/epuerta9/whisk

The idea is to enhance Fastapi and automatically make it OpenAI endpoint compatible so AI engineers can have a standard way of building microservices and agents and can use the same client for all services I.e OpenAI sdk

Would love to find other collaborators and people who would be interested in building something like this

One cool thing you can do is make your Jupyter notebooks OpenAI compatible so you can chat with your notebooks WHILE you’re experimenting! Makes the process feel more natural

I made a demo video around it

https://www.loom.com/share/92fc161d5b2248df8875e29c874b2aac


r/FastAPI • • Jan 27 '26

Other Fast APIs Internal Architecture

Thumbnail
gallery
34 Upvotes

Explanation of the visuals:

First Image:

You can see a visual of the official GitHub repo of Fast API.

Each of these dots is a Python file.

The red ones are the most complex whilst green means low complexity.

Each line represents a connection between the files (usually an import).

Second image:

Shows the AST of one of the main testing files

Complexity again highlighted in red.

The graph at the very bottom is the complexity index per line of code.

The very visual spike of complexity toward the end of the file is caused by test_openapi_schema(): which contains a huge dictionary.

Other Images:

Different impressions throughout the codebase.

How is complexity Measured:

Cyclomatic complexity (McCabe) is being used to assign each file/section a complexity score between 0 and infinity. This score represents the number linearly independent paths in a program. TLDR: Big number = more complex because more possible paths

Personal thoughts:

This medium level of complexity is interesting because it highlights that FastAPI is focused on a lightweight approach (as opposed to battery included frameworks like Django).

There are very few truly complex files. The hardest part about understanding this codebase is its sheer size which is almost inevitable for a framework like this.

Most of the files are either helpers or intended for tests... this means the actual code you will be running on a day to day Fast ApI project is much more compact than the 100s of files you see here.

Kudos to all maintainers!


r/FastAPI • • Apr 11 '23

pip package The new release of FastKafka improves testability

17 Upvotes

We were searching for something like FastAPI for Kafka-based service we were developing, but couldn’t find anything similar. So we shamelessly made one by reusing beloved paradigms from FastAPI and we shamelessly named it FastKafka. The point was to set the expectations right - you get pretty much what you would expect: function decorators for consumers and producers with type hints specifying Pydantic classes for JSON encoding/decoding, automatic message routing to Kafka brokers and documentation generation.

https://github.com/airtai/fastkafka

The new release adds in-memory Kafka broker that can be used for testing without the need to install Java and start a broker. It allows you to write a simple-to-understand tests such as this one:

from fastkafka.testing import Tester

msg = IrisInputData(
    sepal_length=0.1,
    sepal_width=0.2,
    petal_length=0.3,
    petal_width=0.4,
)

# Start Tester app and create InMemory Kafka broker for testing
async with Tester(kafka_app) as tester:
    # Send IrisInputData message to input_data topic
    await tester.to_input_data(msg)

    # Assert that the kafka_app responded with IrisPrediction in predictions topic
    await tester.awaited_mocks.on_predictions.assert_awaited_with(
        IrisPrediction(species="setosa"), timeout=2
    )

r/FastAPI • • Jan 02 '22

feedback request URL shortener using FASTAPI

Thumbnail
github.com
17 Upvotes

r/FastAPI • • Jul 26 '25

Question Multithreading in FastAPI?

17 Upvotes

Hello,

I am currently writing an Ollama wrapper in FastAPI. The problem is, I have no idea how to handle multithreading in FastAPI, and as such, if one process is running (e.g. generating a chat completion), no other processes can run until the first one is done. How can I implement multithreading?


r/FastAPI • • Jul 14 '25

Tutorial Fun Demo

9 Upvotes

Hey all,

For fun, and to prove out TTS/STT, custom voice, and some other technologies, I decided to recreate Monty Python's Argument Sketch Clinic using simple Agentic AI and FastAPI. In just a few commands, you can argue with AI.

Overview here: https://www.linkedin.com/feed/update/urn:li:activity:7348742459297886208/

Code here: https://github.com/inchoate/argument-clinic

Enjoy.


r/FastAPI • • Jan 26 '24

Question Your must have VSCode extensions?

9 Upvotes

Hi there, new to python and fastapi, just getting started, setting up environment and such.

When it comes to vscode, anything in particular you can't live without?


r/FastAPI • • Apr 24 '22

Question Full stack app with FastAPI vs Django

9 Upvotes

Hello Community... It’s nice to be here 😄

So I have a question. Would it be production stable to develop a full stack application with FastAPI, just like Django?

fastapi #django


r/FastAPI • • Jan 24 '22

feedback request Loving FastAPI so far!

9 Upvotes

Used it to build my personal portfolio! Easy to connect my SQL databases and Headless CMS.

I'm new to the design aspect of web development, so I'd appreciate any and all feedback.
www.aj91.online : let me know what y'all think!

Thanks :)


r/FastAPI • • Mar 14 '22

Other How to update table structure without deleting the database?

9 Upvotes

Hi. I have already scanned in a lot of links but I cannot seem to find the solution to this problem.

I am currently enrolled in a fastapi course in udemy.

There is this part where he added a new field to a table but he needed to delete the table in the database in order to reflect the change.

Is there a work around for this part? I don't want to delete the table everytime I make changes in the table structure especially when the system is already in production.


r/FastAPI • • Dec 05 '24

Question Looking for reference SQLAlchemy 2 example

9 Upvotes

Now that the website is pushing SQLModel everywhere, I have trouble finding an up-to-date, reference example project for pure FastAPI + SQLAlchemy 2.0 integration, without using SQLModel.

Can you point me to one? Also blog posts, documentation about how to best do it would be helpful.

I'm looking for information especially about integrating session handling / async specific best practices with SQLAlchemy 2.0.


r/FastAPI • • Mar 10 '26

Question How to intelligently route to multiple routers?

9 Upvotes

We have a monorepo FastAPI app. It has several services as routers which correspond to different data sources, other APIs, etc. Following the separation of concerns, each service is grouped into routers, has its own pydantic input and response models, individual routes etc. An example is "service1 search" has a route calling an external API search function using specific parameters to that API. While "service2 search" has a route that is a SQL query against a database.

Recently, the stakeholders have asked that we implement an "abstract layer." The idea is, a "search" function can use any search service, meaning it can call a passthrough search API call to one data source, it can execute a SQL query to a separate database, etc. These calls would return a unified/adapted response model independent of the raw response data.

Trying to implement this in FastAPI seems quite difficult. I could create new "everything" routes that iteratively query the appropriate service/data one-by-one, aggregate the responses, and adapt those to the unified data model. However, I was told this is unacceptable; that FastAPI needs to just "know" which source to query. I also can't just have a user specify what source they need, because we don't expect users to know where the data lives.

I thought about an agent/LLM being able to do this, keeping our routes clean and allowing us to try to determine the routing logic at the agent level, allowing the LLM to choose the correct route, then taking the raw response and adapting it via structured outputs. This also seems to be rejected.

At this point I'm out of ideas on how to implement this abstract layer idea while still keeping the code maintainable, pythonic, adhering to FastAPI principles, and having separation of concerns and clear routing logic.


r/FastAPI • • Oct 04 '25

Question Ideas to boost server performance with the current setup?

9 Upvotes

Hi guys, currently I have a FuturamaAPI server hosted on Heroku, it provides max 20 DB connections,

I managed to handle any amount of requests without looses and QPS is about 120

Do you have any ideas how I can boost the performance without increasing the connections amount? Cause I can see that's a bottleneck
Shall I use some sort of caching or something

Appreciate your help

The code is here: https://github.com/koldakov/futuramaapi
The site is here: https://futuramaapi.com


r/FastAPI • • Jan 27 '26

Question Road map and resources to start learning FastAPI for AI/ML and GenAI.

9 Upvotes

Hi so I'm 1year working in industry. I'm currently working in .NET and Angular. But I want to switch to python. I have self studied basics of GenAI and created 2-3 projects using Ollama and RAG. I wanted to learn APIs in python to implement them in my GenAI workflow. I have learned the basic of FastAPI and Pydantic and Postgres from Youtube and also build a basic CRUD project. Want to learn more and want to integrate with my GenAI workflow. Please suggest some good resources that will help me learn FastAPI with proper industry standards and good GenAI projects with FastAPI.


r/FastAPI • • Mar 29 '25

Question How do you handle Tensorflow GPU usage?

2 Upvotes

I have FastAPI application, using 5 uvicorn workers. and somewhere in my code, I have just 3 lines that do rely on Tensorflow GPU ccuda version. I have NVIDIA GPU cuda 1GB. I have another queing system that uses a cronjob, not fastapi, and that also relies on those 3 lines of tensotflow.

Today I was testing the application as part of maintenance, 0 users just me, I tested the fastapi flow, everything worked. I tested the cronjob flow, same file, same everything, still 0 users, just me, the cronjob flow failed. Tensorflow complained about the lack of GPU memory.

According to chatgpt, each uvicorn worker will create a new instance of tensorflow so 5 instance and each instance will reserve for itself between 200 or 250mb of GPU VRAM, even if it's not in use. leaving the cronjob flow with no VRAM to work with and then chatgpt recommended 3 solutions

  • Run the cronjob Tensorflow instance on CPU only

  • Add a CPU fallback if GPU is out of VRAM

  • Add this code to stop tensorflow from holding on to VRAM

os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"

I added the last solution temporarily but I don't trust any LLM for anything I don't already know the answer to; it's just a typing machine.

So tell me, is anything chatgpt said correct? should I move the tensorflow code out and use some sort of celery to trigger it? that way VRAM is not being spit up betwen workers?


r/FastAPI • • Oct 29 '25

Question React Server Actions with FastAPI?

2 Upvotes

I would like to make use of server actions benefits, like submit without JavaScript, React state management integrated with useActionState, etc. I keep auth token in HttpOnly cookie to avoid client localStorage and use auth in server components.

In this way server actions serve just as a proxy for FastAPI endpoints with few limitations. Im reusing the same input and output types for both, I get Typescript types with hey-api. Response class is not seriazable so I have to omit that prop from the server action return object. Another big limitation are proxying headers and cookies, in action -> FastAPI direction need to use credentials: include, and in FastAPI -> action direction need to set cookies manually with Next.js cookies().set().

Is there a way to make fully transparent, generic proxy or middleware for all actions and avoid manual rewrite for each individual action? Has any of you managed to get normal server actions setup with non-Next.js backend? Is this even worth it or its better idea to jest call FastAPI endpoints directly from server and client components with Next.js fetch?


r/FastAPI • • Oct 10 '24

Question Zip file and a json object within the same response endpoint

2 Upvotes

Is it possible to return a zip file and a json object within the same response endpoint?
Thanks in advance :)


r/FastAPI • • Jun 18 '24

Hosting and deployment Render doesn’t support HTTP/2

2 Upvotes

Was looking for a hosting for fastapi + hypercorn, something cheap and easy, with http/2 support.

Found render.com, they proud they support http/2 and http/3 by default, but than I noticed that’s not exactly true, the connection between renders proxy and my service is under http/1

Do you think we can consider render supports http/2 or not?

For me, as it’s critical, I still convinced I can’t say render supports http/2 🧐

Proofs: Question in the community: https://community.render.com/t/http-2-support-with-hypercorn/17580

Task created after conversation with support:

https://feedback.render.com/features/p/connection-between-render-proxy-and-user-service-supports-http2

6 people only upvoted for this task with main functionality that’s doesn’t work, against 250+ who want a new dark mode design 🫡