헤더, 쿠키 및 사용자 지정 응답
요청 헤더와 쿠키를 읽고 응답에 설정하며, FastAPI에서 일반 텍스트, HTML, 리디렉션, 스트리밍과 같은 사용자 지정 응답 유형을 반환합니다.
헤더, 쿠키 및 사용자 지정 응답은(는) CoddyKit의 무료 FastAPI Backend Development Bootcamp 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 FastAPI Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Beyond the JSON Body
Request and response handling involves more than the JSON body. Headers and cookies carry metadata like auth tokens, content negotiation, and sessions. FastAPI gives you typed access to both.
Reading a Header
Declare a parameter with Header to read an incoming header. FastAPI auto-converts user_agent to the User-Agent header name.
from fastapi import FastAPI, Header
app = FastAPI()
@app.get('/info')
async def info(user_agent: str = Header(default=None)):
return {'ua': user_agent}Reading Cookies
Use Cookie to read a named cookie, just like headers and query params.
from fastapi import Cookie
@app.get('/session')
async def session(session_id: str = Cookie(default=None)):
return {'session': session_id}Setting Headers on a Response
Inject a Response object to set headers while still returning normal data.
from fastapi import Response
@app.get('/items')
async def items(response: Response):
response.headers['X-Total-Count'] = '42'
return ['a', 'b']Setting Cookies
Call response.set_cookie to send a cookie back to the client. Add flags like httponly and secure for safety.
@app.post('/login')
async def login(response: Response):
response.set_cookie('session_id', 'abc123', httponly=True, secure=True)
return {'ok': True}Plain Text and HTML Responses
Return non-JSON content with specialized response classes.
from fastapi.responses import PlainTextResponse, HTMLResponse
@app.get('/text', response_class=PlainTextResponse)
async def text():
return 'hello'
@app.get('/page', response_class=HTMLResponse)
async def page():
return '<h1>Hi</h1>'Redirects
Send the client elsewhere with RedirectResponse. Choose the status code for permanent vs temporary redirects.
from fastapi.responses import RedirectResponse
@app.get('/old')
async def old():
return RedirectResponse(url='/new', status_code=301)Header Name Conversion
FastAPI converts underscores in parameter names to hyphens for headers. This pure example shows the same idea.
def to_header_name(param):
return '-'.join(w.capitalize() for w in param.split('_'))
print(to_header_name('user_agent'))
print(to_header_name('x_api_key'))Streaming Responses
For large or generated data, stream it with StreamingResponse so you do not buffer everything in memory.
from fastapi.responses import StreamingResponse
def rows():
for i in range(3):
yield f'row {i}\n'
@app.get('/export')
async def export():
return StreamingResponse(rows(), media_type='text/plain')Custom Status Codes
Set a default status for an operation with the status_code argument, or override per request via the injected Response.
from fastapi import status
@app.post('/items', status_code=status.HTTP_201_CREATED)
async def create():
return {'created': True}Security Notes
When setting auth cookies, prefer httponly=True (blocks JS access), secure=True (HTTPS only), and samesite to mitigate CSRF.
Quick Check
You declare x_api_key: str = Header(). Which incoming HTTP header does FastAPI map this to?
Recap
You handled the full request/response surface:
- Read headers and cookies with
HeaderandCookie. - Set headers and cookies via the injected
Response. - Returned plain text, HTML, redirects, and streaming responses.
- Applied secure cookie flags and custom status codes.
자주 묻는 질문
“헤더, 쿠키 및 사용자 지정 응답” 강의는 무료인가요?
네 — “헤더, 쿠키 및 사용자 지정 응답” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 FastAPI Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. FastAPI Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“헤더, 쿠키 및 사용자 지정 응답”에서 뭘 배우나요?
요청 헤더와 쿠키를 읽고 응답에 설정하며, FastAPI에서 일반 텍스트, HTML, 리디렉션, 스트리밍과 같은 사용자 지정 응답 유형을 반환합니다. 브라우저에서 직접 실행하는 실습 코드로 FastAPI Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
FastAPI Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 FastAPI Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“헤더, 쿠키 및 사용자 지정 응답” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 FastAPI Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 FastAPI Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 요청 본문을 위한 Pydantic 모델
- 응답 모델 및 상태 코드
- 폼 데이터 및 파일 업로드
- 헤더, 쿠키 및 사용자 지정 응답