본문 바로가기

FastAPI

15. Fast API 응답 코드 설정

728x90

지금 현재는 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에는 아래와 같이 자동적으로 바뀌게 된다.

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 Description
GET Access one or more resources and return the result as JSON.
POST Return 201 Created if the resource is successfully created and return the newly created resource as JSON.
GET / PUT Return 200 OK if the resource is accessed or modified successfully. The (modified) result is returned as JSON.
DELETE Returns 204 No Content if the resource was deleted successfully.

The following table shows the possible return codes for API requests.

Return values Description
200 OK The GET, PUT or DELETE request was successful, the resource(s) itself is returned as JSON.
204 No Content The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
201 Created The POST request was successful and the resource is returned as JSON.
304 Not Modified Indicates that the resource has not been modified since the last request.
400 Bad Request A required attribute of the API request is missing, e.g., the title of an issue is not given.
401 Unauthorized The user is not authenticated, a valid user token is necessary.
403 Forbidden The request is not allowed. For example, the user is not allowed to delete a project.
404 Not Found A resource could not be accessed. For example, an ID for a resource could not be found.
405 Method Not Allowed The request is not supported.
409 Conflict A conflicting resource already exists. For example, creating a project with a name that already exists.
412 Indicates the request was denied. May happen if the If-Unmodified-Since header is provided when trying to delete a resource, which was modified in between.
422 Unprocessable The entity could not be processed.
429 Too Many Requests The user exceeded the application rate limits.
500 Server Error While handling the request, something went wrong server-side.
728x90