FastAPI를 배워보자 7일차 - Cookie parameter, Header parameter

0

fastapi

목록 보기
7/13

Cookie parameter, Header parameter

https://fastapi.tiangolo.com/tutorial/cookie-params/

fastapi 모듈을 통해 Cookie를 import할 수 있다.

from typing import Union, Annotated

from fastapi import FastAPI, Cookie

app = FastAPI()

@app.get("/items/")
async def read_items(ads_id: Annotated[Union[str, None], Cookie()] = None):
    return {"ads_id": ads_id}

CookiePath, Query와 마찬가지로 Param class을 상속받는다. 따라서 사용법도 일맥상통하다. 다만, cookie를 사용할 때는 반드시 Cookie를 import해서 써주어야 하는데, 안써주면 fastapi에서 기본적으로 query parameter로 생각하기 때문이다.

Cookie는 또한, fastapu 0.95이상은 Annotated와 같이 쓰는 것이 좋지만 0.95미만은 대입문인 =으로 써야한다.

from typing import Union

from fastapi import FastAPI, Cookie

app = FastAPI()

@app.get("/items/")
async def read_items(ads_id: Union[str, None] = Cookie(default=None)):
    return {"ads_id": ads_id}

fastapi version만 높다면 Annotated와 함께 사용하는 것이 좋다.

이제 요청을 보내보도록 하자.

curl --cookie "ads_id=hello" -H "Content-Type: application/json"  "localhost:8888/items/"

{"ads_id":"hello"}

성공적으로 응답이 온 것을 볼 수 있다.

https://fastapi.tiangolo.com/tutorial/header-params/

header값 역시도 handler를 통해서 받아올 수 있다. cookie와 마찬가지로 handler에 Header로 type을 써주어야 한다. 단, 한가지 명심해야할 것은 fastapi가 header를 가져올 때 자동으로 변환하는 것들이 몇 개 있다.

  1. 모든 string은 소문자한다.
  2. python에서 -_로 치환되기 때문에 -_로 바꾼다.

따라서, User-Agent라면 1번에 의해 소문자화되어 user-agent가 되고, 2번에 의해 user_agent가 된다. 아래의 예제를 보도록 하자.

from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/items/")
async def read_items(user_agent: Annotated[Union[str, None], Header()] = None):
    return {"User-Agent": user_agent}

User-Agent header를 user_agent로 받아내는 것을 볼 수 있다. 이렇게 변환이 이루어지는 이유는 python의 표기법에 맞추기 위해서이다. 실제로 코드 상으로만 보면 전혀 어색하거나 python의 코드 규율을 어기는 부분이 없다. 만약 underscore로 자동변환하는 것을 원치않다면 Header(convert_underscores=False)으로 설정하면 된다. 단, 추천하진 않는다.

Header 역시도 Path, Query, Cookie의 자매격이며 Param class을 상속한다. Header를 반드시 써주어야하는데, Header를 안써주면 handler에서 query parameter로 간주하기 때문이다.

마찬가지로 fastapi 0.95이전에는 Annotated문법이 적용되지 않기 때문에 다음과 같이 사용할 수 있다. fastapi 0.95이상은 위의 코드와 같이 Annotated를 사용하면 된다.

from typing import Union

from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/items/")
async def read_items(user_agent: Union[str, None] = Header(default=None)):
    return {"User-Agent": user_agent}

이제 코드를 실행하여 요청을 보내보도록 하자.

curl -H "Content-Type: application/json"  "localhost:8888/items/"

{"User-Agent":"curl/7.68.0"}

User-Agent를 성공적으로 handelr에서 받아온 것을 볼 수 있다.

Duplicate headers

fastapi는 header에 list를 쓰도록 하여 duplicate header를 받아낼 수 있다. 즉, 한 번의 요청에 똑같은 header key로 여러 개의 value를 갖는다고 해도 list로 받아낼 수 있다는 것이다.

from typing import Annotated, Optional

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(x_token: Annotated[Optional[list[str]], Header()] = None):
    return {"X-Token values": x_token}

x_token header를 받아내는 것을 볼 수 있다. header로 X-Token을 여러 번 보내보도록 하자.

curl -H "Content-Type: application/json" -H "X-Token: hello" -H "X-Token: bye"  "localhost:8888/items/"

{"X-Token values":["hello","bye"]}

하나의 요청에 X-Token hedaer를 두개 정의하였다. 하나는 value가 hello이고 하는 bye이다. 이 모든 header값을 list로 받아내는 것을 볼 수 있다.

0개의 댓글

관련 채용 정보