title: FastAPI Cookie 和 Header 参数完全指南:从基础到高级实战 🚀
date: 2025/3/9
updated: 2025/3/9
author: cmdragon

excerpt:
本教程深入探讨 FastAPI 中 Cookie 和 Header 参数的读取与设置,涵盖从基础操作到高级用法。通过详细的代码示例、课后测验和常见错误解决方案,帮助初学者快速掌握 FastAPI 中 Cookie 和 Header 参数的使用技巧。您将学习到如何通过 Cookie 和 Header 传递数据、进行数据校验以及优化 API 接口的安全性,从而构建高效、安全的 Web 应用。

categories:

  • 后端开发
  • FastAPI

tags:

  • FastAPI
  • Cookie
  • Header
  • API设计
  • Web开发
  • 数据校验
  • 安全性

image

image

扫描二维码关注或者微信搜一搜:编程智域 前端至全栈交流与成长

探索数千个预构建的 AI 应用,开启你的下一个伟大创意

第一章:Cookie 参数基础

1.1 什么是 Cookie 参数?

Cookie 是 Web 应用中用于存储用户会话信息的机制。在 FastAPI 中,Cookie 参数可以通过 Cookie 类进行处理。

from fastapi import FastAPI, Cookie

app = FastAPI()


@app.get("/items/")
async def read_items(session_id: str = Cookie(None)):
    return {"session_id": session_id}

1.2 Cookie 参数的使用

通过 Cookie 类,可以轻松读取客户端传递的 Cookie 参数。

@app.get("/user/")
async def read_user(user_id: str = Cookie(None)):
    return {"user_id": user_id}

示例请求

curl -b "session_id=abc123" http://localhost:8000/items/

1.3 Cookie 参数校验

结合 Pydantic 的 Field,可以对 Cookie 参数进行数据校验。

from pydantic import Field


@app.get("/validate-cookie/")
async def validate_cookie(session_id: str = Cookie(..., min_length=3)):
    return {"session_id": session_id}

示例请求

  • 合法:curl -b "session_id=abc123" http://localhost:8000/validate-cookie/{"session_id": "abc123"}
  • 非法:curl -b "session_id=a" http://localhost:8000/validate-cookie/ → 422 错误

1.4 常见错误与解决方案

错误:422 Validation Error
原因:Cookie 参数类型转换失败或校验不通过
解决方案:检查 Cookie 参数的类型定义和校验规则。


第二章:Header 参数基础

2.1 什么是 Header 参数?

Header 是 HTTP 请求中用于传递元数据的机制。在 FastAPI 中,Header 参数可以通过 Header 类进行处理。

from fastapi import FastAPI, Header

app = FastAPI()


@app.get("/items/")
async def read_items(user_agent: str = Header(None)):
    return {"user_agent": user_agent}

2.2 Header 参数的使用

通过 Header 类,可以轻松读取客户端传递的 Header 参数。

@app.get("/user/")
async def read_user(x_token: str = Header(None)):
    return {"x_token": x_token}

示例请求

curl -H "X-Token: abc123" http://localhost:8000/user/

2.3 Header 参数校验

结合 Pydantic 的 Field,可以对 Header 参数进行数据校验。

from pydantic import Field


@app.get("/validate-header/")
async def validate_header(x_token: str = Header(..., min_length=3)):
    return {"x_token": x_token}

示例请求

  • 合法:curl -H "X-Token: abc123" http://localhost:8000/validate-header/{"x_token": "abc123"}
  • 非法:curl -H "X-Token: a" http://localhost:8000/validate-header/ → 422 错误

2.4 常见错误与解决方案

错误:422 Validation Error
原因:Header 参数类型转换失败或校验不通过
解决方案:检查 Header 参数的类型定义和校验规则。


第三章:高级用法与最佳实践

3.1 自定义 Cookie 和 Header 名称

通过 alias 参数,可以自定义 Cookie 和 Header 的名称。

@app.get("/custom-cookie/")
async def custom_cookie(session: str = Cookie(None, alias="session_id")):
    return {"session": session}


@app.get("/custom-header/")
async def custom_header(token: str = Header(None, alias="X-Token")):
    return {"token": token}

3.2 安全性最佳实践

通过 SecureHttpOnly 标志,可以增强 Cookie 的安全性。

from fastapi.responses import JSONResponse


@app.get("/secure-cookie/")
async def secure_cookie():
    response = JSONResponse(content={"message": "Secure cookie set"})
    response.set_cookie(key="session_id", value="abc123", secure=True, httponly=True)
    return response

3.3 性能优化

通过 Headerconvert_underscores 参数,可以优化 Header 参数的兼容性。

@app.get("/optimized-header/")
async def optimized_header(user_agent: str = Header(None, convert_underscores=False)):
    return {"user_agent": user_agent}

3.4 常见错误与解决方案

错误:400 Bad Request
原因:Header 或 Cookie 参数格式不正确
解决方案:检查参数的格式和校验规则。


课后测验

测验 1:Cookie 参数校验

问题:如何定义一个包含校验规则的 Cookie 参数?
答案

from fastapi import Cookie
from pydantic import Field


@app.get("/validate-cookie/")
async def validate_cookie(session_id: str = Cookie(..., min_length=3)):
    return {"session_id": session_id}

测验 2:Header 参数校验

问题:如何定义一个包含校验规则的 Header 参数?
答案

from fastapi import Header
from pydantic import Field


@app.get("/validate-header/")
async def validate_header(x_token: str = Header(..., min_length=3)):
    return {"x_token": x_token}

错误代码应急手册

错误代码典型触发场景解决方案
422类型转换失败/校验不通过检查参数定义的校验规则
400Header 或 Cookie 格式不正确检查参数的格式和校验规则
500未捕获的参数处理异常添加 try/except 包裹敏感操作
401未授权访问检查认证和授权逻辑

常见问题解答

Q:如何设置安全的 Cookie?
A:通过 SecureHttpOnly 标志设置:

from fastapi.responses import JSONResponse


@app.get("/secure-cookie/")
async def secure_cookie():
    response = JSONResponse(content={"message": "Secure cookie set"})
    response.set_cookie(key="session_id", value="abc123", secure=True, httponly=True)
    return response

Q:如何处理自定义 Header 名称?
A:通过 alias 参数设置:

@app.get("/custom-header/")
async def custom_header(token: str = Header(None, alias="X-Token")):
    return {"token": token}

通过本教程的详细讲解和实战项目,您已掌握 FastAPI 中 Cookie 和 Header 参数的核心知识。现在可以通过以下命令测试您的学习成果:

curl -b "session_id=abc123" http://localhost:8000/items/

余下文章内容请点击跳转至 个人博客页面 或者 扫码关注或者微信搜一搜:编程智域 前端至全栈交流与成长,阅读完整的文章:FastAPI Cookie 和 Header 参数完全指南:从基础到高级实战 🚀 | cmdragon's Blog

往期文章归档:


风流倜傥的伤痕
79 声望23 粉丝