How to Return JSON Response in FastAPI: Simple Guide
In FastAPI, you return a JSON response by simply returning a Python dictionary or Pydantic model from your path operation function. FastAPI automatically converts it to JSON using
JSONResponse behind the scenes.Syntax
In FastAPI, you define a function for a route and return a Python dictionary or a Pydantic model instance. FastAPI converts this return value into a JSON response automatically.
@app.get("/path"): Decorator to define a GET route.- Function returns a
dictorBaseModelinstance. - FastAPI uses
JSONResponseinternally to send JSON.
python
from fastapi import FastAPI app = FastAPI() @app.get("/example") def example(): return {"key": "value"}
Example
This example shows a FastAPI app with a GET endpoint that returns a JSON response containing a message and a number. When you visit /json, you get a JSON object automatically.
python
from fastapi import FastAPI app = FastAPI() @app.get("/json") def get_json(): return {"message": "Hello, FastAPI!", "number": 123}
Output
{"message":"Hello, FastAPI!","number":123}
Common Pitfalls
Some common mistakes when returning JSON in FastAPI include:
- Returning non-serializable objects like sets or custom classes without Pydantic models.
- Forgetting to return a dictionary or Pydantic model, which causes errors.
- Trying to manually create JSON strings instead of returning Python objects.
FastAPI handles conversion, so just return Python data structures.
python
from fastapi import FastAPI app = FastAPI() # Wrong: returning a set (not JSON serializable) @app.get("/wrong") def wrong(): return {1, 2, 3} # This will cause an error # Right: return a list or dict @app.get("/right") def right(): return [1, 2, 3]
Quick Reference
Tips for returning JSON in FastAPI:
- Return
dict,list, or Pydantic models. - Use Pydantic models for validation and documentation.
- FastAPI auto-converts return values to JSON responses.
- Use
from fastapi.responses import JSONResponseonly for custom JSON responses.
Key Takeaways
Return Python dicts or Pydantic models from your FastAPI route functions to get JSON responses.
FastAPI automatically converts returned data to JSON using JSONResponse.
Avoid returning non-serializable types like sets or custom objects without Pydantic.
Use Pydantic models for better validation and clear API docs.
Manual JSON string returns are unnecessary and error-prone in FastAPI.