How to Use JSONResponse in FastAPI: Simple Guide
In FastAPI, use
JSONResponse from fastapi.responses to return JSON with custom status codes or headers. Instantiate it with your data as content and return it from your path operation function.Syntax
The JSONResponse class is used to send JSON data with custom options in FastAPI. You create it by passing your data as content. You can also set status_code and headers to customize the HTTP response.
- content: The Python data (like dict or list) to convert to JSON.
- status_code: Optional HTTP status code (default is 200).
- headers: Optional dictionary of HTTP headers.
python
from fastapi.responses import JSONResponse response = JSONResponse(content={"message": "Hello"}, status_code=201, headers={"X-Custom-Header": "value"})
Example
This example shows a FastAPI app returning a JSONResponse with a custom message, status code 201, and a custom header.
python
from fastapi import FastAPI from fastapi.responses import JSONResponse app = FastAPI() @app.get("/custom-response") async def custom_response(): data = {"message": "Item created successfully"} headers = {"X-Process-Time": "0.5s"} return JSONResponse(content=data, status_code=201, headers=headers)
Output
{"message":"Item created successfully"}
Common Pitfalls
Common mistakes when using JSONResponse include:
- Not passing data as
content, which causes errors. - Returning plain dict instead of
JSONResponsewhen custom status or headers are needed. - Forgetting to import
JSONResponsefromfastapi.responses.
Always use JSONResponse(content=your_data) to ensure proper JSON formatting and control.
python
from fastapi import FastAPI app = FastAPI() # Wrong: returning dict when custom status needed @app.get("/wrong") async def wrong(): return {"message": "Hello"} # No custom status or headers possible # Right: use JSONResponse for custom status from fastapi.responses import JSONResponse @app.get("/right") async def right(): return JSONResponse(content={"message": "Hello"}, status_code=202)
Quick Reference
Use this quick guide when working with JSONResponse in FastAPI:
| Feature | Description | Example |
|---|---|---|
| content | Python data to send as JSON | {"message": "Hi"} |
| status_code | HTTP status code (default 200) | status_code=201 |
| headers | Custom HTTP headers | headers={"X-Header": "value"} |
| Usage | Return from path operation to customize response | return JSONResponse(content=data) |
Key Takeaways
Use JSONResponse to send JSON with custom status codes and headers in FastAPI.
Always pass your data as the content argument to JSONResponse.
Import JSONResponse from fastapi.responses before using it.
Returning a plain dict is simpler but does not allow custom status or headers.
JSONResponse ensures your response is properly formatted as JSON.