Skip to main content

Overview

While FastAPI typically handles response serialization automatically, you can return a Response object directly when you need full control over the response, including status codes, headers, cookies, and content.

Why Return a Response Directly?

Returning a Response 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 a JSONResponse 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:
For HTML and other common content types, use the specialized response classes like HTMLResponse, PlainTextResponse, etc.

Bypassing Response Validation

When you need to return data that doesn’t match your response model:
Bypassing response validation means you lose the benefits of automatic validation and documentation. Use this sparingly and only when necessary.

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:
See Response Headers for more details on working with headers.

Performance Considerations

Returning a Response 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

  1. Use sparingly: Only return Response directly when you need the extra control
  2. Document manually: Add response documentation when bypassing automatic serialization
  3. Validate data: Even when returning responses directly, validate important data
  4. Use typed responses: Prefer specific response classes (JSONResponse, HTMLResponse) over the generic Response
  5. Consider background tasks: Direct responses work seamlessly with background tasks
  6. Set proper media types: Always specify the correct media_type for your content