지금 현재는 Rest API의 응답은 아마 status code가 200일 것이다.

하지만 이는 HTTP status code와는 약간은 동떨어진 응답 코드이다.

일반적으로 get은 200, post는 201, delete는 204의 응답 코드를 가진다.

그렇다면 fast api에서도 해당 코드를 반환하게 만들어야한다.

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

위와 같이 status_code=201로 선언하여 api 함수가 정상적으로 종료되면 응답 코드로 201을 반환하게 만들 수 있다.

/docs에는 아래와 같이 자동적으로 바뀌게 된다.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/e611282e-6616-48aa-9ea2-31994abc5cad/Untitled.png

Shortcut to remember the names

위의 코드에서는 201과 같이 직접 해당 코드의 숫자를 써주었다. 하지만 이는 201이 무슨 뜻을 가지고 있는지 알아야하고, 다른 사람이 보았을 때 단번에 알 수 없을지도 모른다.

이를 위해 좀 더 직관적인 status code를 선언할 수 있는 방법이 있다.

from fastapi import FastAPI, status

app = FastAPI()

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

fastapi에서 status에서 정의된 HTTP 응답 코드를 사용하면 좀 더 의미를 알아보기 쉽게 작성할 수 있다.

HTTP Response and Meanings

Status codes

The API is designed to return different status codes according to context and action. This way, if a request results in an error, the caller is able to get insight into what went wrong.

The following table gives an overview of how the API functions generally behave.

Request type