[WAFFLE] 01-5 HTTP Response

1 minute read

Published:

In this post, basic concepts about HTTP Response is introduced.

HTTP Response

HTTP Response consists of 3 parts - Status Line, Headers, Body. HTTP Response Message is US-ASCII encoded.

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 26

{"message": "Hellow World"}

Response Body

class Item(BaseModel):
    name: str
    price: float
    brand_id: int

@app.get("/item")
def get_item() -> Item:
    return Item(name="iPhone", price=1000, brand_id=1)
  • Request Body가 알아서 역질렬화가 되었듯, Response Body도 자동으로 직렬화가 됨
class Items(BaseModel):
    items: List[Item]

@app.get("/items")
def get_items() -> Items:
    return Items(items=[Items(name="iPhone", price=1000, brand_id=1)])
  • Model을 중첩해서 깊은 구조의 JSON을 반환할 수 있음(Nested Model)

Response Header

  • Request Header와 크게 다르지 않음
from fastapi.responses import JSONResponse

@app.get("/item")
def get_item():
    return JSONResponse(content={"message": "Hellow World"}, headers="X-Custom-Header": "Custom Value")
  • fastapi.responses 모듈을 이용해서 Response Bodey와 Header를 동시에 지정할 수 있음
  • headers는 dict 형태로 전달

Status Code

  • Status Code : Status Line의 두 번째 Token
  • Status Code 뒤에는 Status Message가 붙지만, 실제로는 큰 의미 없음
  • Status Code는 서버의 응답 상태를 나타내며, 첫 번째 숫자에 따라 다음과 같이 구분됨
    • 1xx : Informational
    • 2xx : Successful
    • 3xx : Redirection
    • 4xx : Client Error
    • 5xx : Server Error
    • RFC 7231 또는 MDN 참조
from fastapi improt status

@app.get("/items/{item_id}", status_code=status.HTTP_200_OK)
def read_item(item_id: int):
    return get_item_by_id(item_id)
  • 엔드포인트의 데코레이터에 status_code 지정할 수 있음
  • 정수로 지정할 수도 있지만, fastapi.status를 이용해서 더 명시적으로 지정할 수 있음
  • 기본값은 200 OK
from fastapi improt status
from fastapi.responses import JSONResponse

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return JSONResponse(content=..., status_code=status.HTTP_200_OK)
  • 반환값이 여러 개이고 각각 다른 상태 코드를 지정해야 할 때에는 fastapi.responses 모듈을 이용
  • 하지만 이 방법은 API 문서에 자동으로 반영되지 않음

Redirect

from fastapi.responses import RedirectResponse

@app.get("/redirect")
def redirect():
    return RedirectResponse(url="/items")
  • RedirectResponse를 이용해서 리다이렉트 응답(클라이언트를 다른 URL로 리다이렉트하기 위한 응답 객체)을 보낼 수 있음

Response Object

from fastapi.responses import Response

@app.get("/items/{item_id}")
def read_item(item_id: int):
    response = Response(content="Hello World", status_code=200)
    response.headers["X-Custom-Header"] = "Custom Value"
    return response
  • Response 객체를 이용해서 직접 Response 생성 가능
  • 주입받은 REsponse 객체는 반환을 생략할 수 있음

Leave a Comment