Home >Backend Development >Python Tutorial >How to Return JSON Data in FastAPI: Automatic vs. Manual Conversion?

How to Return JSON Data in FastAPI: Automatic vs. Manual Conversion?

DDD
DDDOriginal
2024-12-04 12:29:10967browse

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:

  • By default, FastAPI adds a Content-Length and Content-Type header to the response.
  • You can specify a custom status code for the response by setting the status_code attribute of the Response or JSONResponse object.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn