프레임워크/FastAPI

[FastAPI] FastAPI [21] Path Operation Configuration

:) :) 2023. 5. 16. 13:07

https://fastapi.tiangolo.com/tutorial/path-operation-configuration/

 

Path Operation Configuration - FastAPI

Path Operation Configuration There are several parameters that you can pass to your path operation decorator to configure it. Warning Notice that these parameters are passed directly to the path operation decorator, not to your path operation function. Res

fastapi.tiangolo.com

<FastAPI 공식문서 참조>

 

0. Path Operation Configuration

  사용자 정의 경로 연산 데코레이터에 전달할 수 있도록 설정가능한 여러 매개변수들이 존재한다.

이들을 알아보자.

 

1. Response Status Code

  내 경로연산의 response에서 사용될 HTTP status code가 있다.

그 유명한 404 not found의 404가 바로 HTTP status code이다.

 

 이런 각각의 상태코드가 무엇을 의미하는지 까먹었을때 status 라이브러리에서 바로가기 상수를 사용할 수 있다.

다음 코드는 이에 대한 예시이다.

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()


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


@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
    return item

 

 

2. Tags

  경로 연산에 태그를 더할 수 있다. str형의 list로 tags 파라미터를 보낼 수 있다(일반적으로는 str형 자료 1개만 보냄).

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
    tags: set[str] = set()


@app.post("/items/", response_model=Item, tags=["items"])
async def create_item(item: Item):
    return item


@app.get("/items/", tags=["items"])
async def read_items():
    return [{"name": "Foo", "price": 42}]


@app.get("/users/", tags=["users"])
async def read_users():
    return [{"username": "johndoe"}]

 

2-1. Tags with Enums

 사이즈가 큰 응용 프로그램을 가지고 있을 때, 여러 태그를 누적될 수 있다.

또한, 비슷한 종류의 연산에서 동일한 태그를 항상 사용하고 싶을 수도 있다.

 

이러한 종류는 태그를 Enum(열거형 자료형)에 저장하여 구현할 수 있다.

from enum import Enum

from fastapi import FastAPI

app = FastAPI()


class Tags(Enum):
    items = "items"
    users = "users"


@app.get("/items/", tags=[Tags.items])
async def get_items():
    return ["Portal gun", "Plumbus"]


@app.get("/users/", tags=[Tags.users])
async def read_users():
    return ["Rick", "Morty"]

 

3. Summary and description

  요약과 설명을 메타데이터로 추가할 수도 있다.

@app.post(
    "/items/",
    response_model=Item,
    summary="Create an item",
    description="Create an item with all the information, name, description, price, tax and a set of unique tags",
)
async def create_item(item: Item):
    return item

 

4. Description from docstring

 설명이 여러 줄에 걸쳐 길어질 경우 docstring은 이를 지원할 수 있다.

경로 연산 description에 선언하면 FastAPI가 알아서 찾아가서 읽는다.

 

 docstring내부에 Markdown도 쓸 수 있다.

@app.post("/items/", response_model=Item, summary="Create an item")
async def create_item(item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    """
    return item

 

 

5. Response description

 매개변수 response_description을 사용해 응답 설명(response description)을 구체화할 수 있다.

@app.post(
    "/items/",
    response_model=Item,
    summary="Create an item",
    response_description="The created item",
)
async def create_item(item: Item):
    """
    Create an item with all the information:

    - **name**: each item must have a name
    - **description**: a long description
    - **price**: required
    - **tax**: if the item doesn't have tax, you can omit this
    - **tags**: a set of unique tag strings for this item
    """
    return item

response_description은 응답을 구체적으로 설명하고, description은 경로 연산을 일반적으로 설명한다.

 

 

 

6. Deprecate a path operation

  경로 연산을 더이상 사용하지 않는 상태(deprecated)로 표시해야 할 경우(제거는 하지 않으면서) deprecate 매개변수를 사용하자.

@app.get("/elements/", tags=["items"], deprecated=True)
async def read_elements():
    return [{"item_id": "Foo"}]

사용 시 interactive docs에 바로 명확히 나온다.

 

 

 

7. Reference

https://fastapi.tiangolo.com/tutorial/path-operation-configuration/

 

Path Operation Configuration - FastAPI

Path Operation Configuration There are several parameters that you can pass to your path operation decorator to configure it. Warning Notice that these parameters are passed directly to the path operation decorator, not to your path operation function. Res

fastapi.tiangolo.com