Additional media types for main response using responses parameter
Use the responses parameter to declare different media types for the same main response. For example, you can add image/png as an additional media type alongside the default application/json. When adding alternative media types, you must return the response object directly (such as FileResponse for images).
FastAPI assumes default media type for responses parameter
If you do not explicitly specify a media type in the responses parameter, FastAPI assumes the response has the same media type as the main response class (default is application/json). If a custom response class has None as media type, FastAPI uses application/json for any additional response with an associated model.
Combine response_model, status_code, and responses parameters
You can declare a response_model with the default status code 200 (or custom code), and then add additional information for the same response or other responses in the responses parameter directly in the OpenAPI schema. FastAPI combines the additional information from responses with the JSON schema from the model.
Combine predefined and custom responses using dict unpacking
To reuse predefined responses across multiple path operations while adding custom responses for each operation, use Python dict unpacking syntax: {**predefined_responses_dict, "new_status_code": {"model": ModelName}}. This merges the predefined responses with operation-specific custom responses.
Response dict structure in OpenAPI includes content, description, headers, links
In the responses parameter, each response dict can include properties defined by the OpenAPI Response Object specification, including: description (text describing the response), headers (custom headers), content (media types and schemas), and links. These directly populate the OpenAPI schema.
JSON schema reference placement in OpenAPI responses
When using a model in responses, FastAPI places a schema reference at: responses > [status_code] > content > [media_type] > schema > $ref, referencing global JSON schemas in components/schemas rather than embedding the schema inline. This allows other applications and clients to use the JSON schemas directly and improves code generation tools.
responses parameter declares additional HTTP status codes
The responses parameter passed to path operation decorators accepts a dict where keys are HTTP status codes (like 200, 404) and values are dicts containing information about each response. This parameter adds additional responses to the OpenAPI schema and API documentation.
responses parameter with model key for Pydantic models
Each response dict in the responses parameter can contain a 'model' key with a Pydantic model, similar to response_model. FastAPI takes this model, generates its JSON schema, and includes it at the appropriate location in the OpenAPI schema. The model key itself is not part of OpenAPI; FastAPI extracts the schema from it.
How to declare additional response statuses with the responses parameter
To declare an additional response with a specific status code and Pydantic model, pass a responses parameter to the path operation decorator with a dict like: {404: {"model": Message, "description": "Custom description"}}. You must return a Response object (like JSONResponse) directly with the appropriate status code and content.
Combine response_class with direct Response for OpenAPI documentation
If you want to override the response within the function and also document the media type in OpenAPI, you can use the response_class parameter AND return a Response object. The response_class is used only for documenting the OpenAPI path operation, while your Response is used unchanged.
Response class parameters and behavior
The Response class accepts the following parameters: content (a str or bytes), status_code (an int HTTP status code), headers (a dict of strings), and media_type (a str indicating the media type, e.g. 'text/html'). FastAPI (actually Starlette) automatically adds a Content-Length header, and will insert a Content-Type header based on the media_type, appending a charset for text types.
HTMLResponse returns HTML text or bytes
HTMLResponse takes text or bytes and returns an HTML response.
PlainTextResponse returns plain text
PlainTextResponse takes text or bytes and returns a plain-text response.
JSONResponse returns application/json encoded response
JSONResponse takes some data and returns an application/json-encoded response. This is the default response used in FastAPI.
RedirectResponse returns HTTP redirect
RedirectResponse returns an HTTP redirect. It uses status code 307 (Temporary Redirect) by default. You can return it directly or use it in the response_class parameter.
RedirectResponse with response_class returns URL from path operation
When using RedirectResponse as response_class, you can return the URL directly from your path operation function. The status code used is 307 (the default for RedirectResponse).
StreamingResponse streams response body from generator
StreamingResponse takes an async generator or a normal generator/iterator (a function with yield) and streams the response body.
StreamingResponse requires await for cancellation
An async task can only be cancelled when it reaches an await. If there is no await, the generator cannot be properly cancelled and could continue running even after cancellation is requested. For generators without await statements, add await anyio.sleep(0) to give the event loop a chance to process cancellation.
FileResponse streams file asynchronously
FileResponse streams a file asynchronously as a response. It takes different arguments at instantiation than other Response types: path (the file path to stream), headers (any custom headers to include as a dictionary), media_type (a string indicating the media type; if not set, it is inferred from the filename or path), and filename (if set, it is included in the Content-Disposition of the response). File responses include appropriate Content-Length, Last-Modified, and ETag headers.
FileResponse with response_class returns file path from path operation
You can use FileResponse as response_class. In this case, you can return the file path directly from your path operation function.
Create custom Response class inheriting from Response
You can create your own custom Response class by inheriting from Response and using it. The important thing you must do is create a Response.render(content) method that returns the content as bytes.
FastAPI default response type
By default, FastAPI returns JSON responses.
default_response_class parameter on FastAPI and APIRouter
When creating a FastAPI instance or APIRouter, you can specify which Response class to use by default with the default_response_class parameter. You can still override response_class in individual path operations.
response_class parameter declares custom response type
You can declare the Response class you want to use in the path operation decorator with the response_class parameter. The content returned from your path operation function will be inserted into this Response.
Direct Response return bypasses automatic conversion and documentation
When you return a Response directly (or a subclass like JSONResponse) without declaring response_class in the decorator, the data is not automatically converted even if you declare a response_model, and the documentation is not automatically generated including the specific media type in the HTTP Content-Type header as part of the generated OpenAPI.
Response class without media type omitted from OpenAPI documentation
If you use a Response class without a media type, FastAPI expects that your Response has no content, and therefore does not document the format of the Response in the generated OpenAPI documentation.
response_model with JSONResponse uses jsonable_encoder then JSONResponse
When you declare a response_class with a JSON media type (application/json) like JSONResponse, the data you return is automatically converted with any Pydantic response_model declared in the path operation decorator (and filtered), but the data is not serialized to JSON bytes with Pydantic. Instead, it is converted with jsonable_encoder and then passed to the JSONResponse class, which serializes it to bytes with Python's standard JSON library.
Best performance for JSON responses
For maximum performance with JSON responses, use a response_model and do not declare a response_class in the path operation decorator.
HTMLResponse for returning HTML
To return a response with HTML directly from FastAPI, use HTMLResponse. Import HTMLResponse and pass it as the response_class parameter of your path operation decorator. This sets the HTTP Content-Type header to text/html and documents it in OpenAPI.
response_class parameter sets OpenAPI media type
The response_class parameter is used to define the media type of the response. It sets the HTTP Content-Type header and is documented as such in OpenAPI.
Direct Response not visible in OpenAPI documentation
A Response returned directly from a path operation function is not documented in OpenAPI (for example, the Content-Type is not documented) and is not visible in the automatic interactive documentation.