Skip to main content
FastAPI provides several response classes for returning different types of content. These classes are built on top of Starlette’s response classes and allow you to customize the response sent to the client.

Importing

Response Classes

Response

The base response class. Use this for custom responses or when you need full control.Constructor Parameters:
bytes | str
default:"b''"
The response body content.
int
default:"200"
HTTP status code.
dict[str, str] | None
default:"None"
HTTP headers.
str | None
default:"None"
Media type (Content-Type).
BackgroundTask | None
default:"None"
Background task to run after sending the response.
Attributes:
int
The HTTP status code.
MutableHeaders
Response headers.
bytes
The response body.
str | None
The media type (Content-Type).
BackgroundTask | None
Background task to execute after response.
Methods:
  • set_cookie() - Set a cookie
  • delete_cookie() - Delete a cookie

JSONResponse

Returns a JSON response. This is the default response class in FastAPI.
Note: When using JSONResponse directly, the content must be JSON-serializable. FastAPI’s automatic response serialization using Pydantic models is often more convenient:

HTMLResponse

Returns an HTML response.

PlainTextResponse

Returns a plain text response.

RedirectResponse

Returns an HTTP redirect response.Constructor Parameters:
str
required
The URL to redirect to.
int
default:"307"
HTTP status code (307 for temporary redirect, 308 for permanent).
dict[str, str] | None
default:"None"
Additional headers.

StreamingResponse

Streams response content. Useful for large files, real-time data, or generated content.Constructor Parameters:
Iterator[bytes] | AsyncIterator[bytes]
required
An iterator or async iterator that yields bytes.
int
default:"200"
HTTP status code.
dict[str, str] | None
default:"None"
HTTP headers.
str | None
default:"None"
Media type (Content-Type).

FileResponse

Returns a file as the response. Automatically handles file streaming and sets appropriate headers.Constructor Parameters:
str | Path
required
Path to the file.
int
default:"200"
HTTP status code.
dict[str, str] | None
default:"None"
Additional headers.
str | None
default:"None"
Media type. If not set, it will be guessed from the file extension.
str | None
default:"None"
Filename for the Content-Disposition header.

EventSourceResponse

Returns Server-Sent Events (SSE) for real-time streaming. This is FastAPI-specific and allows streaming events from async generators.

Using Response Classes

Setting Default Response Class

You can set a default response class for the entire application or for specific routers:

Declaring Response Class in Path Operation

Returning Response Directly

Setting Cookies

Custom Response Headers

Background Tasks

Common Response Patterns

Success with Custom Status

Error Response

Custom Error Response