Overview
While FastAPI typically handles response serialization automatically, you can return aResponse object directly when you need full control over the response, including status codes, headers, cookies, and content.
Why Return a Response Directly?
Returning aResponse object directly is useful when you need to:
- Set custom headers or cookies
- Return non-JSON content types
- Have complete control over the response
- Work with data that’s already serialized
- Bypass response validation
Basic Usage
Return aJSONResponse directly:
When you return a
Response object directly, FastAPI won’t perform any data conversion or validation. You’re responsible for ensuring the response is properly formatted.Response with Custom Status Code
Set a custom status code when returning a response:When to Use Direct Response
Already Serialized Data
When your data is already in the correct format:Custom Media Types
Return content with specific media types:Bypassing Response Validation
When you need to return data that doesn’t match your response model:Background Tasks with Direct Response
Combine direct responses with background tasks:Combining Data Return and Direct Response
You can conditionally return either serialized data or a direct response:Setting Headers with Direct Response
Add custom headers when returning a response:Performance Considerations
Returning aResponse directly can be more efficient when:
- Data is already serialized (no need to serialize again)
- You’re returning large amounts of data
- You want to avoid the overhead of response validation
While returning
Response objects directly gives you more control, you lose automatic OpenAPI documentation for the response structure. Consider documenting the response manually using the responses parameter.Best Practices
- Use sparingly: Only return
Responsedirectly when you need the extra control - Document manually: Add response documentation when bypassing automatic serialization
- Validate data: Even when returning responses directly, validate important data
- Use typed responses: Prefer specific response classes (
JSONResponse,HTMLResponse) over the genericResponse - Consider background tasks: Direct responses work seamlessly with background tasks
- Set proper media types: Always specify the correct
media_typefor your content