Overview
FastAPI provides several response classes for different content types. By default, FastAPI returns responses as JSON, but you can customize this behavior using different response classes.Available Response Classes
FastAPI (via Starlette) provides these response classes:JSONResponse- JSON responses (default)HTMLResponse- HTML contentPlainTextResponse- Plain textRedirectResponse- HTTP redirectsStreamingResponse- Streaming responsesFileResponse- File downloadsResponse- Generic response class
JSONResponse
The default response class for most FastAPI endpoints:You typically don’t need to use
JSONResponse explicitly - FastAPI uses it by default when you return a dict, list, or Pydantic model.HTMLResponse
Return HTML content from your endpoints:Direct HTMLResponse
You can also return anHTMLResponse object directly:
PlainTextResponse
Return plain text content:RedirectResponse
Redirect to another URL:Redirect Status Codes
Control the redirect type with status codes:- Use
307(Temporary Redirect) to preserve the request method - Use
308(Permanent Redirect) for permanent redirects that preserve the method - Use
302(Found) for temporary redirects that may change the method to GET - Use
301(Moved Permanently) for permanent redirects that may change the method
StreamingResponse
Stream large files or generated content:Streaming Files
Stream file content:FileResponse
Serve files efficiently with proper headers:File Download with Custom Headers
Setting Default Response Class
Set a default response class for your entire app or router:Custom Response Classes
Create your own response class:ORJSONResponse (Deprecated)
If you still need orjson for specific use cases:Response Class vs Response Model
Understand the difference:response_model: Defines the data structure/schema for validation and documentationresponse_class: Defines how the response is formatted and sent (HTML, JSON, etc.)
Best Practices
- Use the right class: Choose the response class that matches your content type
- Set at the decorator: Use
response_classparameter in the path decorator for clarity - Default wisely: Set default response classes at the app or router level when appropriate
- Stream large data: Use
StreamingResponsefor large files or generated content - Serve static files properly: Use
FileResponsefor static files, notStreamingResponse - Document custom types: When using custom response classes, document them properly
- Consider performance: Modern FastAPI with Pydantic v2 is very fast - custom JSON serializers are rarely needed