Skip to main content

One post tagged with "async"

async tag description

View All Tags

FastAPI Internal Requests, Depends, and Accessing the Request Object

· 7 min read
Serhii Hrekov
Senior Software Engineer & System Architect specializing in Python, Web Systems, Cloud Infrastructure & Automation

Reliable way to make an internal HTTP request from one FastAPI route handler to another within the same application, specifically to handle a POST request with a request body.

The best and most idiomatic way to handle this in FastAPI (which is built on Starlette) is by using the TestClient from the starlette.testclient module. This allows you to treat your application as an independent service and make internal requests without incurring any actual network overhead, which is crucial for testing and internal service calls.

When working with FastAPI, the correct method to call one route from another is not by importing the handler function directly, but by using the TestClient class. This simulates a genuine HTTP request, ensuring all middleware, dependencies, and validation logic run exactly as they would for an external client.