Skip to main content
JSONResponse is a response class that serializes data to JSON format. It’s the default response class in FastAPI when you return data from path operations.

Import

Class Signature

Constructor Parameters

Any
default:"None"
The data to be JSON-serialized and returned in the response body. Can be any JSON-serializable type including dicts, lists, Pydantic models, etc.
int
default:"200"
The HTTP status code for the response.
dict | None
default:"None"
Additional HTTP headers to include in the response.
str | None
default:"None"
Override the default media type. If not provided, uses application/json.
BackgroundTask | None
default:"None"
Background task to run after returning the response.

Usage

Automatic JSON Response

FastAPI automatically returns JSONResponse when you return data:

Explicit JSONResponse

Return JSONResponse directly to control status codes and headers:

Custom Status Code

Properties

media_type

The media type for JSON responses:

Methods

render()

Serializes content to JSON bytes:
This method is called internally by Starlette/FastAPI to encode the response content.

Notes

  • FastAPI uses Pydantic for JSON serialization when a return type or response model is set, which is faster than custom response classes
  • The default JSON encoder handles common Python types like datetime, UUID, etc.
  • For Pydantic models, use response models instead of manually creating JSONResponse objects