Home >Backend Development >Python Tutorial >How to Return JSON Data in FastAPI: Automatic vs. Manual Conversion?
How to return data in JSON format using FastAPI?
To return data in JSON format using FastAPI, you can use the jsonable_encoder encoder to convert Python data structures into JSON-compatible data. This can be achieved using either of the following options:
Option 1: Using the jsonable_encoder Automatically
Return data as usual, and FastAPI will automatically handle the JSON conversion. FastAPI internally uses the jsonable_encoder to convert the data to JSON-compatible format. The jsonable_encoder ensures that unsupported objects, like datetime objects, are converted to strings. FastAPI then wraps the data in a JSONResponse object with an application/json media type, which the client receives as a JSON response.
from fastapi.encoders import jsonable_encoder from fastapi.responses import JSONResponse def return_dict(): data_dict = {"name": "John Doe", "age": 30} return JSONResponse(content=jsonable_encoder(data_dict))
Option 2: Manual JSON Conversion
If you need to perform custom JSON conversion, you can directly return a Response object with the media_type set to 'application/json' and the content set to the JSON-encoded data. Remember to use the json.dumps() function with the default=str argument to ensure that unsupported objects are converted to strings before being encoded as JSON.
import json from fastapi import Response def return_response(): data_dict = {"name": "John Doe", "age": 30} json_data = json.dumps(data_dict, default=str) return Response(content=json_data, media_type="application/json")
Additional Notes:
The above is the detailed content of How to Return JSON Data in FastAPI: Automatic vs. Manual Conversion?. For more information, please follow other related articles on the PHP Chinese website!