Skip to content

경로 동작 설정

경로 작동 데코레이터를 설정하기 위해서 전달할수 있는 몇 가지 매개변수가 있습니다.

경고

아래 매개변수들은 경로 작동 함수가 아닌 경로 작동 데코레이터에 직접 전달된다는 사실을 기억하십시오.

응답 상태 코드

경로 작동의 응답에 사용될 (HTTP) status_code를 정의할수 있습니다.

404와 같은 int형 코드를 직접 전달할수 있습니다.

하지만 각 코드의 의미를 모른다면, status에 있는 단축 상수들을 사용할수 있습니다:

from typing import Set, Union

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[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

각 상태 코드들은 응답에 사용되며, OpenAPI 스키마에 추가됩니다.

기술적 세부사항

다음과 같이 임포트하셔도 좋습니다. from starlette import status.

FastAPI는 개발자 여러분의 편의를 위해서 starlette.status와 동일한 fastapi.status를 제공합니다. 하지만 Starlette에서 직접 온 것입니다.

태그

(보통 단일 str인) str로 구성된 list와 함께 매개변수 tags를 전달하여, 경로 작동에 태그를 추가할 수 있습니다:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[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"}]

전달된 태그들은 OpenAPI의 스키마에 추가되며, 자동 문서 인터페이스에서 사용됩니다:

요약과 기술

summarydescription을 추가할 수 있습니다:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@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

독스트링으로 만든 기술

설명은 보통 길어지고 여러 줄에 걸쳐있기 때문에, 경로 작동 기술을 함수 독스트링 에 선언할 수 있습니다, 이를 FastAPI가 독스트링으로부터 읽습니다.

마크다운 문법으로 독스트링을 작성할 수 있습니다, 작성된 마크다운 형식의 독스트링은 (마크다운의 들여쓰기를 고려하여) 올바르게 화면에 출력됩니다.

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@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

이는 대화형 문서에서 사용됩니다:

응답 기술

response_description 매개변수로 응답에 관한 설명을 명시할 수 있습니다:

from typing import Set, Union

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


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


@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은 일반적인 경로 작동을 지칭합니다.

확인

OpenAPI는 각 경로 작동이 응답에 관한 설명을 요구할 것을 명시합니다.

따라서, 응답에 관한 설명이 없을경우, FastAPI가 자동으로 "성공 응답" 중 하나를 생성합니다.

단일 경로 작동 지원중단

단일 경로 작동을 없애지 않고 지원중단을 해야한다면, deprecated 매개변수를 전달하면 됩니다.

from fastapi import FastAPI

app = FastAPI()


@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"}]


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

대화형 문서에 지원중단이라고 표시됩니다.

지원중단된 경우와 지원중단 되지 않은 경우에 대한 경로 작동이 어떻게 보이는 지 확인하십시오.

정리

경로 작동 데코레이터에 매개변수(들)를 전달함으로 경로 작동을 설정하고 메타데이터를 추가할수 있습니다.