https://fastapi.tiangolo.com/tutorial/extra-data-types/
Extra Data Types - FastAPI
Up to now, you have been using common data types, like: But you can also use more complex data types. And you will still have the same features as seen up to now: Great editor support. Data conversion from incoming requests. Data conversion for response da
fastapi.tiangolo.com
<FastAPI 공식문서 참조>
1. Extra Data Types
FastAPI가 지원하는 강력한 기능과 함께, 더 복잡한 자료형을 사용할 수 있다.
1-1. Other data types
다음은 사용자가 사용할 수 있는 부가적 자료형이다.
- UUID
- University Unique Identifier이라는 표준이다. 많은 시스템 및 데이터베이스에서 표준으로 사용된다.
- 요청과 응답은 str형으로 표현된다.
- datetime.datetime
- 파이썬 datetime.datetime 이다.
- 요청과 응답은 ISO 8601형식의 str형으로 표현되며, 다음과 같은 형태를 띈다.
- 2008-09-15T15:53:00+05:00
- datetime.date
- 파이썬 datetime.date 이다.
- 요청과 응답은 ISO 8601형식의 str형으로 표현되며, 다음과 같은 형태를 띈다.
- 2008-09-15
- datetime.timedelta
- 파이썬 datetime.timedelta 이다.
- 요청과 응답은 전체 시간(초)의 float 형(부동 소수점 형)으로 표현된다.
- Pydantic은 이것을 "ISO 8601 time diff encoding"로 표현하게 해주기도 한다.
- frozenset
- 요청과 응답은 set 자료형과 같게 취급된다.
- 요청에서, 읽혀진 list 는 중복이 제거되고 set 으로 변환된다.
- 응답에서, set은 list로 변환된다.
- 생성된 스키마는 set 값이 고유하다는 것을 지정한다.
- 요청과 응답은 set 자료형과 같게 취급된다.
- bytes
- 표준 Python bytes 이다.
- 요처오가 응답은 str로 다뤄진다.
- 생성된 스키마는 이것을 binary "format"을 가진 str 형으로 지정한다.
- Decimal
- 표준 Python Decimal 이다.
- 요청과 응답은 float와 같게 취급된다.
- 모든 Pydantic data type을 다음에서 확인할 수 있다 : Pydantic data types
1-2. Example
1-1에서 상기한 여러 자료형을 가지고 만든 path operation 예제이다.
from datetime import datetime, time, timedelta
from typing import Annotated
from uuid import UUID
from fastapi import Body, FastAPI
app = FastAPI()
@app.put("/items/{item_id}")
async def read_items(
item_id: UUID,
start_datetime: Annotated[datetime | None, Body()] = None,
end_datetime: Annotated[datetime | None, Body()] = None,
repeat_at: Annotated[time | None, Body()] = None,
process_after: Annotated[timedelta | None, Body()] = None,
):
start_process = start_datetime + process_after
duration = end_datetime - start_process
return {
"item_id": item_id,
"start_datetime": start_datetime,
"end_datetime": end_datetime,
"repeat_at": repeat_at,
"process_after": process_after,
"start_process": start_process,
"duration": duration,
start_datetime, end_datetime, repeat_at, process_after 추가적 자료형을 사용하여 선언하였다.
이들은 모두 그들 본래의 자료형을 가지고 있기 때문에, 일반적 날짜 조작(계산 등)을 실행할 수 있다.
start_process = start_datetime + process_after
duration = end_datetime - start_process
2. Reference
'프레임워크 > FastAPI' 카테고리의 다른 글
[FastAPI] FastAPI [12] Header Parameters (0) | 2023.04.04 |
---|---|
[FastAPI] FastAPI [11] Cookie Parameters (0) | 2023.04.04 |
[FastAPI] FastAPI [9] Declare Request Example Data (0) | 2023.04.03 |
[FastAPI] FastAPI [8] Body - Nested Models (0) | 2023.03.28 |
[FastAPI] FastAPI [7] Body - Fields (0) | 2023.03.27 |