Skip to content

์‘๋‹ต ํ—ค๋”

Response ๋งค๊ฐœ๋ณ€์ˆ˜ ์‚ฌ์šฉํ•˜๊ธฐ

๊ฒฝ๋กœ ์—ฐ์‚ฐ ํ•จ์ˆ˜์—์„œ Response ํƒ€์ž…์˜ ๋งค๊ฐœ ๋ณ€์ˆ˜๋ฅผ ์ง€์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. (์‘๋‹ต ์ฟ ํ‚ค์—์„œ ์ฒ˜๋Ÿผ).

๊ทธ๋Ÿฐ ๋‹ค์Œ ์ž„์‹œ ์‘๋‹ต ๊ฐ์ฒด์— ํ—ค๋”๋ฅผ ์„ค์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

from fastapi import FastAPI, Response

app = FastAPI()


@app.get("/headers-and-object/")
def get_headers(response: Response):
    response.headers["X-Cat-Dog"] = "alone in the world"
    return {"message": "Hello World"}

๊ทธ๋Ÿฐ ๋‹ค์Œ ํ‰์†Œ์ฒ˜๋Ÿผ ํ•„์š”ํ•œ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค (dict, ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋ชจ๋ธ, ๊ธฐํƒ€ ๋“ฑ๋“ฑ).

response_model๋ฅผ ์„ ์–ธํ–ˆ๋‹ค๋ฉด, ๋ฐ˜ํ™˜๋  ๊ฐ์ฒด๋ฅผ ํ•„ํ„ฐ๋ง, ๋ณ€ํ™˜ํ•˜๋Š”๋ฐ ์—ฌ์ „ํžˆ ์‚ฌ์šฉ๋ ๊ฒ๋‹ˆ๋‹ค.

FastAPI๋Š” ์ž„์‹œ ์‘๋‹ต ๊ฐ์ฒด๋ฅผ ์ด์šฉํ•ด ํ—ค๋”(๊ทธ๋ฆฌ๊ณ  ์ฟ ํ‚ค, ์‘๋‹ต ์ฝ”๋“œ)๋ฅผ ์ถ”์ถœํ•˜๊ณ , response_model๋กœ ํ•„ํ„ฐ๋ง ๋œ ์ตœ์ข… ๊ฐ’๋“ค์ด ์ตœ์ข… ์‘๋‹ต์— ํฌํ•จ๋  ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๋˜๋Š” Response ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์ข…์†์„ฑ์—์„œ ์„ ์–ธํ•˜๊ณ , ๊ฑฐ๊ธฐ์— ํ—ค๋”(๊ทธ๋ฆฌ๊ณ  ์ฟ ํ‚ค)๋ฅผ ์„ค์ •ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

Response ์ง์ ‘์ ์œผ๋กœ ๋ฐ˜ํ™˜ํ•˜๊ธฐ

Response๋ฅผ ์ง์ ‘์ ์œผ๋กœ ๋ฐ˜ํ™˜ํ•  ๋•Œ ํ—ค๋”๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

์‘๋‹ต ์ง์ ‘ ๋ฐ˜ํ™˜ํ•˜๊ธฐ์— ์„ค๋ช…๋œ ๊ฒƒ ์ฒ˜๋Ÿผ ์‘๋‹ต์„ ๋งŒ๋“ค์–ด ์ถ”๊ฐ€์ ์ธ ๋งค๊ฐœ ๋ณ€์ˆ˜์™€ ํ•จ๊ป˜ ํ—ค๋”๋ฅผ ๋„˜๊ธฐ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

Create a response as described in Return a Response Directly and pass the headers as an additional parameter:

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()


@app.get("/headers/")
def get_headers():
    content = {"message": "Hello World"}
    headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
    return JSONResponse(content=content, headers=headers)

๊ธฐ์ˆ ์  ์„ธ๋ถ€์‚ฌํ•ญ

from starlette.responses import Response ํ˜น์€ from starlette.responses import JSONResponse๋ฅผ ์‚ฌ์šฉํ•˜๋„ ๋ฉ๋‹ˆ๋‹ค.

FastAPI๋Š” starlette.responses๋ฅผ ๊ฐœ๋ฐœ์ž์˜ ํŽธ๋ฆฌํ•จ์„ ์œ„ํ•ด fastapi.responses๋กœ ์ด๋ฆ„์„ ๋ฐ”๊ฟ” ์ œ๊ณตํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. ๋Œ€๋ถ€๋ถ„์˜ ๊ฐ€๋Šฅํ•œ ์‘๋‹ต์€ Starlette์—์„œ ์ง์ ‘ ์ œ๊ณตํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  Response๋Š” ํ—ค๋”์™€ ์ฟ ํ‚ค๋ฅผ ์„ค์ •ํ•˜๋Š” ๋ฐ ์ž์ฃผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, FastAPI๋˜ํ•œ ์ด๊ฑธ fastapi.Response๋กœ ์ œ๊ณตํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

์ปค์Šคํ…€ ํ—ค๋”

'X-' ์ ‘๋‘์‚ฌ๋ฅผ ์ด์šฉํ•ด ์‚ฌ์šฉ์ž ์ •์˜ ๋…์  ํ—ค๋”๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜๋„ ์žˆ์Œ์„ ์—ผ๋‘์— ๋‘์‹ญ์‹œ์˜ค.

ํ•˜์ง€๋งŒ ๋ธŒ๋ผ์šฐ์ €์—์„œ ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋ณผ ์ˆ˜ ์žˆ๋Š” ์ปค์Šคํ…€ ํ—ค๋”๋ฅผ ๊ฐ–๊ฒŒ ํ• ๋ ค๋ฉด CORS ์„ค์ •์—์„œ ์ด๋ฅผ ์ถ”๊ฐ€ํ•ด์•ผ ๋ฉ๋‹ˆ๋‹ค. (CORS (Cross-Origin Resource Sharing)์—์„œ ์ž์„ธํžˆ ์ฝ์–ด๋ณด์„ธ์š”.) Starlette's CORS docs์—์„œ ์„ค๋ช…๋œ expose_headers๋ฅผ ์‚ฌ์šฉํ•˜์„ธ์š”.