Fast API, 응답 코드 설정

Junha Kim·2021년 1월 23일
1

FastAPI

목록 보기
16/16

지금 현재는 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 typeDescription
GETAccess one or more resources and return the result as JSON.
POSTReturn 201 Created if the resource is successfully created and return the newly created resource as JSON.
GET / PUTReturn 200 OK if the resource is accessed or modified successfully. The (modified) result is returned as JSON.
DELETEReturns 204 No Content if the resource was deleted successfully.

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

Return valuesDescription
200 OKThe GET, PUT or DELETE request was successful, the resource(s) itself is returned as JSON.
204 No ContentThe server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
201 CreatedThe POST request was successful and the resource is returned as JSON.
304 Not ModifiedIndicates that the resource has not been modified since the last request.
400 Bad RequestA required attribute of the API request is missing, e.g., the title of an issue is not given.
401 UnauthorizedThe user is not authenticated, a valid user token is necessary.
403 ForbiddenThe request is not allowed. For example, the user is not allowed to delete a project.
404 Not FoundA resource could not be accessed. For example, an ID for a resource could not be found.
405 Method Not AllowedThe request is not supported.
409 ConflictA conflicting resource already exists. For example, creating a project with a name that already exists.
412Indicates 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 UnprocessableThe entity could not be processed.
429 Too Many RequestsThe user exceeded the application rate limits.
500 Server ErrorWhile handling the request, something went wrong server-side.

0개의 댓글