You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenAPI文档中编写请求头说明及FastAPI对应实现方法

在OpenAPI文档中定义请求头及FastAPI实现方式

一、OpenAPI文档中的请求头定义

你给出的请求头定义方式是正确的,编写完成后,X-Request-ID会在自动生成的OpenAPI文档(如Swagger UI、ReDoc)中正确展示,包含它的类型、格式和必填属性。对应的完整定义代码如下:

paths:
  /ping:
    get:
      summary: Checks if the server is alive
      parameters:
        - in: header
          name: X-Request-ID
          schema:
            type: string
            format: uuid
          required: true

二、FastAPI中的对应实现

在FastAPI中,可以通过Header依赖项声明请求头参数,自动生成符合上述OpenAPI规范的文档。代码示例如下:

from fastapi import FastAPI, Header
from uuid import UUID

app = FastAPI()

@app.get("/ping", summary="Checks if the server is alive")
async def ping(x_request_id: UUID = Header(..., description="Unique request ID in UUID format")):
    return {"message": "Server is alive", "request_id": x_request_id}

关键说明:

  • 使用Header(...)标记参数为请求头,...表示该参数为必填项,对应OpenAPI中的required: true
  • 指定参数类型为UUID,FastAPI会自动校验格式,并在OpenAPI文档中映射为type: string、format: uuid
  • 通过description参数可以添加请求头的说明文本,会同步显示在自动生成的API文档中

内容的提问来源于stack exchange,提问作者Jun Takeshita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 01:01:05