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

如何在FastAPI Swagger UI中隐藏字段但仍支持手动传入值?

在FastAPI Swagger UI中隐藏字段并保留手动传入能力的解决方案

问题原因

你之前的方案中,下划线开头的_difficulty被Pydantic默认视为私有字段,不会参与请求数据的解析流程,所以即使设置了alias='difficulty',传入的difficulty值也无法被映射到_difficulty,只会保留默认值'low'。

解决方案

以下是两种可行的实现方式:

方案一:直接设置字段不纳入OpenAPI Schema

不需要使用下划线命名,通过Field的include_in_schema=False参数让字段在Swagger UI中隐藏,同时保留正常的字段解析能力:

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Subject(BaseModel):
    score: int
    # 设置include_in_schema=False,Swagger UI中不会显示该字段,但可接收传入值
    difficulty: str = Field('low', include_in_schema=False)

@app.post("/submit")
async def submit(subject: Subject):
    return {
        "score": subject.score,
        "difficulty": subject.difficulty  # 可正常获取传入的difficulty值
    }

方案二:保留下划线字段并关闭私有属性限制

如果坚持要使用下划线命名字段,需要在模型配置中关闭underscore_attrs_are_private的默认限制,同时设置include_in_schema=False隐藏Swagger显示:

from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class Subject(BaseModel):
    score: int
    _difficulty: str = Field('low', alias='difficulty', include_in_schema=False)
    
    # 关闭下划线字段的私有属性限制,让Pydantic解析该字段
    model_config = {
        "underscore_attrs_are_private": False
    }

@app.post("/submit")
async def submit(subject: Subject):
    return {
        "score": subject.score,
        "difficulty": subject._difficulty  # 可正确获取别名传入的值
    }

验证效果

  • Swagger UI的请求体示例中只会显示score字段;
  • 手动传入{"score": 70, "difficulty": "high"}时,模型会正确接收difficulty的值,覆盖默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:54:38