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
The data to be JSON-serialized and returned in the response body. Can be any JSON-serializable type including dicts, lists, Pydantic models, etc.
The HTTP status code for the response.
Additional HTTP headers to include in the response.
Override the default media type. If not provided, uses
application/json.Background task to run after returning the response.
Usage
Automatic JSON Response
FastAPI automatically returnsJSONResponse when you return data:
Explicit JSONResponse
ReturnJSONResponse 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: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
JSONResponseobjects
Related
- HTMLResponse - For returning HTML content
- StreamingResponse - For streaming data
- Response Models - Type-safe response handling