프레임워크/FastAPI

[FastAPI] FastAPI [9] Declare Request Example Data

:) :) 2023. 4. 3. 12:40

https://fastapi.tiangolo.com/tutorial/schema-extra-example/

 

Declare Request Example Data - FastAPI

Declare Request Example Data You can declare examples of the data your app can receive. Here are several ways to do it. You can declare an example for a Pydantic model using Config and schema_extra, as described in Pydantic's docs: Schema customization: Py

fastapi.tiangolo.com

<FastAPI 공식문서 참조>

 

 

1. Declare Request Example Data

 내 app이 받을 데이터의 예시를 미리 만들어줄 수 있다.

아래는 몇 가지 다양한 방법에 대한 서술이다.

 

1-1. Pydantic shcema_extra

 Configschema_extra 를 사용하여, Pydantic model을 위한 example을 선언할 수 있다.

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None

    class Config:
        schema_extra = {
            "example": {
                "name": "Foo",
                "description": "A very nice Item",
                "price": 35.4,
                "tax": 3.2,
            }
        }


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results

 config class가 example의 선언에 대한 예시이다.

 

이 추가정보는 위 모델의 출력 JSON Schema에 그대로 추가되고, API 문서에서도 사용된다.

* 같은 방법으로 JSON스키마를 확장하고 나만의 사용자 정의 추가정보를 삽입할 수 있다(ex. 프론트엔드 UI를 위한 메타데이터 삽입).

 

1-2. Field additional arguments

 Field() 키워드를 사용하고 있을 때, 추가 JSON Schema를 example 키워드를 사용하여 선언할 수 있다.

각각의 field에 example 키워드를 삽입해보자.

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Item(BaseModel):
    name: str = Field(example="Foo")
    description: str | None = Field(default=None, example="A very nice Item")
    price: float = Field(example=35.4)
    tax: float | None = Field(default=None, example=3.2)


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    results = {"item_id": item_id, "item": item}
    return results

 

2.  example   and  examples   in OpenAPI

  • Path()
  • Query()
  • Header()
  • Cookie()
  • Body()
  • Form()
  • File()

위와 같은 type 모두 각각 example을 선언할 수 있다. 혹은, examples의 묶음을 선언할 수 있다. 이 묶음은 OpenAPI에 저장될 추가 정보이다.

 

 

2-1. Body with example

 Body()에 대한 example 삽입 예시이다.

*example 키워드 사용

async def update_item(
    item_id: int,
    item: Annotated[
        Item,
        Body(
            example={
                "name": "Foo",
                "description": "A very nice Item",
                "price": 35.4,
                "tax": 3.2,
            },
        ),
    ],
):
    results = {"item_id": item_id, "item": item}
    return results

 

* example 삽입시 docs에는 아래처럼 Example Value가 추가된다.
* example 삽입시 docs에는 아래처럼 Example Value가 추가된다.

 

2-2. Body with multiple examples

 딕셔너리를 이용해서 다중예시를 전달할 수 있다. 물론 각각의 예시 모두 OpenAPI에 추가된다.

딕셔너리의 키는 각각의 예시가 되고, 그 값은 다른 딕셔너리(예시에 대한 다양한 설명정보를 담음)가 된다.

 

Example dictionary 속 각각의 구체적 예시 딕셔너리는 다음을 포함할 수 있다 :

  •  summary  : 예시에 대한 짧은 설명
  •  description  : Markdown text를 포함할 수 있는 긴 설명
  •  value  : 표시된 실제 예시(딕셔너리)
  •  externalValue  : 위 value를 대체, 예시를 가리키는 URL(많은 tools에서 지원하지 않을 수도 있다.)
from typing import Annotated

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    tax: float | None = None


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: Annotated[
        Item,
        #####################################################################################################
        Body(
            examples={
                "normal": {
                    "summary": "A normal example",
                    "description": "A **normal** item works correctly.",
                    "value": {
                        "name": "Foo",
                        "description": "A very nice Item",
                        "price": 35.4,
                        "tax": 3.2,
                    },
                },
                "converted": {
                    "summary": "An example with converted data",
                    "description": "FastAPI can convert price `strings` to actual `numbers` automatically",
                    "value": {
                        "name": "Bar",
                        "price": "35.4",
                    },
                },
                "invalid": {
                    "summary": "Invalid data is rejected with an error",
                    "value": {
                        "name": "Baz",
                        "price": "thirty five point four",
                    },
                },
            },
        #########################################################################################################
        ),
    ],
):
    results = {"item_id": item_id, "item": item}
    return results

 

Examples에 선택가능한 category가 생긴다.

 

 

 

3. Reference

https://fastapi.tiangolo.com/tutorial/schema-extra-example/