Post

FastAPI 공식문서 따라하기[18] - Response Status Code

https://fastapi.tiangolo.com/tutorial/response-status-code/ 공식문서 따라하는 글

☑️ Response Status Code

response model을 선언했던것 처럼 status_code를 사용해서 HTTP 상태값을 반환할 수 있다.

ex)

1
2
3
4
5
6
7
8
9
from fastapi import FastAPI

app = FastAPI()


@app.post("/items/", status_code=201)
async def create_item(name: str):
    return {"name": name}

이렇게 선언하면

  • response객체에 상태값을 리턴할 수 있다.
  • OpenAPI와 같은 문서에도 적용이 된다.

☑️ About HTTP status codes

HTTP 상태값의 의미에 대한 설명인데 알고 있으면 스킵하라고 하길래 나는 스킵 자세한건 공식문서 참조

☑️ Shortcut to remember the names

FastAPI는 편의성을 또 제공한다.

위처럼 status_code = 201이라고 하면 두 번의 생각을 거치게 된다.

  • 201이 뭐더라? 아 Created지.
  • Created가 뭐지? 아 어떤거구나

이 두 번의 생각을 하나의 생각으로 줄이기 위해 fastapi.status를 제공한다.

1
2
3
4
5
6
7
8
9
10
from fastapi import FastAPI,status

app = FastAPI()


@app.get("/items/", status_code=status.HTTP_200_OK)
async def get_item(name: str):
    return {"name": name}


코드의 길이가 조금 늘어났지만, 직관적이게 바뀌었다.

심지어 이는 editor에서는 자동완성 기는을 제공한다.

from starlette import status도 사용할 수 있다. 별반 차이가 없다고한다.

This post is licensed under CC BY 4.0 by the author.