프레임워크/FastAPI

[FastAPI] FastAPI [22] JSON Compatible Encoder

:) :) 2023. 5. 23. 11:02

 

 

JSON Compatible Encoder - FastAPI

JSON Compatible Encoder There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a dict, list, etc). For example, if you need to store it in a database. For that, FastAPI provides a js

fastapi.tiangolo.com

<FastAPI 공식문서 참조>

 

 

0. JSON Compatible Encoder

 Pydantic model과 같은 데이터 자료형을 JSON과 비교가능한 어떠한 것(dict, list, etc)으로 변환해야하는 경우가 있다.

 

예를 들어, 이것들을 데이터베이스에 저장한다고 해보자.

그때 jsonable_encoder() 라는 함수를 FastAPI가 쓰라고 제공해준다.

 

1. Using the jsonable_encoder

 JSON과 비교가능한 데이터만을 받을 수 있는 fake_db 데이터베이스를 가지고 있다고 가정해보자.

(이 데이터베이스는 datetime 자료 객체를 받을 수 없다, JSON과 비교불가능해서.)

datetime 자료를 ISO 형식의 데이터를 포함하고 있는 str 자료형으로 변경해야만 한다.

 

같은 방법으로, 위 데이터베이스에 dict 자료형을 제외한 Pydantic model은 받을 수 없으나

jsonable_encoder를 사용하면 가능하다.

 

이 인코더는 객체를 받고, JSON과 비교가능한 것을 return 해준다.

from datetime import datetime

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

fake_db = {}


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: str | None = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    fake_db[id] = json_compatible_item_data

 이 예시에서, 인코더는 Pydantic model을 dict 자료형으로 변환하고, datetime 자료형을 str 자료로 변환한다.

이 호출의 결과는 파이썬 표준 json.dumps()로 인코딩 될 수 있다는 것이다.

 

 단순히 큰 str(string 형태로서 JSON 형식의 데이터들을 포함하는)을 return 하는 것이 아니다.

JSON과 비교가능한 파이썬 표준 자료형(딕셔너리와 같은)을 return한다.

 

 

 

2. Reference

https://fastapi.tiangolo.com/tutorial/encoder/

 

JSON Compatible Encoder - FastAPI

JSON Compatible Encoder There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like a dict, list, etc). For example, if you need to store it in a database. For that, FastAPI provides a js

fastapi.tiangolo.com