Home >Backend Development >Python Tutorial >How Can I Avoid Double Serialization When Returning JSON Data in FastAPI?

How Can I Avoid Double Serialization When Returning JSON Data in FastAPI?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-28 07:50:12821browse

How Can I Avoid Double Serialization When Returning JSON Data in FastAPI?

How JSON Data is Handled by FastAPI

The Pitfall of Double Serialization

When returning JSON data in FastAPI using json.dumps(), avoid double serialization. FastAPI performs automatic serialization behind the scenes, so invoking json.dumps() manually can lead to garbled output, visible as a string instead of JSON.

Options for Returning JSON Data

Option 1: Automatic Serialization

Simply return data as dictionaries, lists, etc. FastAPI will automatically convert it to JSON-compatible format using its built-in jsonable_encoder and wrap it in a JSONResponse. This approach ensures proper serialization and support for serialization of non-serializable objects like datetimes.

from datetime import date

data = [{"User": "a", "date": date.today(), "count": 1}]

@app.get('/')
async def main():
    return data

Option 2: Custom Serialization

In specific scenarios, manual serialization may be necessary. In that case, consider returning a custom Response object with the media type set to application/json.

import json

@app.get('/')
async def main():
    json_str = json.dumps(data, indent=4, default=str)
    return Response(content=json_str, media_type='application/json')

Additional Considerations

  • Customizing Status Code: Use the Response.status_code attribute to set a custom status code for JSON responses.
  • Alternative JSON Encoders: Consider using faster third-party JSON encoders like Orjson for improved performance.

The above is the detailed content of How Can I Avoid Double Serialization When Returning JSON Data in FastAPI?. 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