본문 바로가기
Fast API/fastapi배우기

Fast API 배우기 8부 - Example Data 넣기

by 붕어사랑 티스토리 2021. 11. 1.
반응형

Example Data 넣기

 

모델에 Confg 클래스를 정의한뒤 schema_extra 에 값을 넣으면 example 데이터를 넣을 수 있다.

from typing import Optional

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = 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
    class Config:
        schema_extra = {
            "example": {
                "name": "Foo",
                "description": "A very nice Item",
                "price": 35.4,
                "tax": 3.2,
            }
        }

 

 

 

 

Field에 example 데이터 추가하기

 

example 키워드를 이용하여 feild에도 example 데이터를 추가할 수 있다.

from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field


app = FastAPI()


class Item(BaseModel):
    name: str = Field(..., example="Foo")
    description: Optional[str] = Field(None, example="A very nice Item")
    price: float = Field(..., example=35.4)
    tax: Optional[float] = Field(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

 

 

 

 

example, examples in OpenAPI

아래 목록은 example과 examples를 쓸 수 있는 api들이다.

 

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

 

아래 예제는 Body에 example을 사용한 모습

from typing import Optional

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


@app.put("/items/{item_id}")
async def update_item(
    item_id: int,
    item: 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

 

 

 

docs에 들어가보면 아래처럼 example이 미리 삽입된 것을 볼 수 있다.

 

 

 

반응형

 

 

examples 사용하기

example을 여러개 사용하고 싶다면 examples를 사용하자.

 

dict형으로 작성을 해야 한다.

 

단일 example을 작성할때와 다르게 examples는 추가적인 데이터를 아래와 같이 담을 수 있다.

 

 

  • summary: example에 대한 간단한 설명이다
  • description: example에 대한 긴 설명. 구두점 . 을 포함 할 수 있다.
  • value: 실제 example 값을 담는곳
  • externalValue: value의 대용으로, example이 있는 url 값을 넣ㅅ습니다. 자주 쓰이지는 않습니다.

 

아래는 대표적인 예제입니다.

from typing import Optional

from fastapi import Body, FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


@app.put("/items/{item_id}")
async def update_item(
    *,
    item_id: int,
    item: 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

 

 

그럼 docs에 아래와 같이 examples에 항목이 생긴다.

 

반응형

댓글