0Pricing
FastAPI Backend Development Bootcamp · 课时

请求头、Cookie 与自定义响应

读取请求头和 Cookie,将它们设置到响应中,并在 FastAPI 中返回纯文本、HTML、重定向和流式传输等自定义响应类型。

请求头、Cookie 与自定义响应 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 Header and Cookie.
  • Set headers and cookies via the injected Response.
  • Returned plain text, HTML, redirects, and streaming responses.
  • Applied secure cookie flags and custom status codes.

常见问题解答

「请求头、Cookie 与自定义响应」课时是免费的吗?

是的 — 「请求头、Cookie 与自定义响应」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。

「请求头、Cookie 与自定义响应」这节课中我会学到什么?

读取请求头和 Cookie,将它们设置到响应中,并在 FastAPI 中返回纯文本、HTML、重定向和流式传输等自定义响应类型。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 FastAPI Backend Development Bootcamp 需要有经验吗?

无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「请求头、Cookie 与自定义响应」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?

能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 用于请求体的 Pydantic 模型
  2. 响应模型与状态码
  3. 表单数据与文件上传
  4. 请求头、Cookie 与自定义响应
← 返回 FastAPI Backend Development Bootcamp