如何在FastAPI生成的API规范中定义Long类型变量?
解决方案
要让FastAPI生成的OpenAPI规范将person_id标记为int64类型(对应Java的Long包装类),可以通过自定义Pydantic类型并修改其JSON Schema实现,具体步骤如下:
1. 自定义LongInt类型
继承Pydantic的StrictInt,重写其JSON Schema生成逻辑,添加format: int64标识:
from pydantic import StrictInt from pydantic.json_schema import JsonSchemaValue from typing import Any class LongInt(StrictInt): @classmethod def __get_pydantic_json_schema__(cls, schema: JsonSchemaValue, handler: Any) -> JsonSchemaValue: # 调用父类逻辑生成基础Schema schema = handler(schema) # 添加int64格式标记,让OpenAPI识别为长整型 schema.update({"format": "int64"}) return schema
2. 修改Person类使用自定义类型
将原StrictInt替换为自定义的LongInt:
from pydantic import BaseModel, constr, validator class Person(BaseModel): person_id: LongInt # 替换为自定义长整型 person_name: constr(strip_whitespace=True, strict=True) @validator('person_id') def person_id_validator(cls, val): assert val is not None return val @validator('person_name') def person_name_validator(cls, val): assert val != '' return val
效果说明
- 生成的OpenAPI规范中,
person_id的Schema会包含"format": "int64",Java客户端生成工具(如OpenAPI Generator)会自动将其映射为Long包装类,支持存储大于2147483647的数值。 - 自定义的
LongInt保留了StrictInt的严格校验特性(仅接受整数类型,拒绝字符串转整数等隐式转换),同时Python的原生int类型可以处理任意大的数值,无需依赖第三方库(如numpy/torch)。
内容的提问来源于stack exchange,提问作者Vimugdh Lall
相关产品推荐
相关产品推荐

