如何在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
相关产品推荐
相关产品推荐

