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

如何在FastAPI Redoc文档中为表单输入添加示例响应?

给表单提交的FastAPI接口添加Redoc示例响应

你可以通过在路由装饰器中配置responses参数来定义示例响应,逻辑和Pydantic模型参数的场景一致,和请求参数是表单类型无关。

直接在@app.post里指定200状态码的响应结构,包含示例内容即可:

from fastapi import FastAPI, Form

app = FastAPI()

def get_profile(intro: str, name: str, age: str) -> str:
    return f"Name: {name}, Age: {age}, Intro: {intro}"

@app.post(
    "/api/add_profile",
    description="Add your details here",
    responses={
        200: {
            "description": "Successful response",
            "content": {
                "application/json": {
                    "example": {
                        "content": "Name: John Doe, Age: 30, Intro: I'm a software developer who loves Python"
                    }
                }
            }
        }
    }
)
async def your_profile(
    name: str = Form(description="Enter your full name"),
    intro: str = Form(description="Write a short introduction, this will be displayed to others"),
    age: str = Form()
):
    response = get_profile(intro=intro, name=name, age=age)
    return {"content": response}

关键说明

  • responses字典的键为HTTP状态码(这里用200表示成功响应)
  • 每个状态码对应的配置中,content指定响应的媒体类型(此处为application/json),example字段定义具体的响应示例内容
  • Redoc会自动读取该配置,在文档页面展示对应的示例响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:05:05