从OpenAPI规范创建FastAPI路由
openapi-to-fastapi的Python项目详细描述
推理
FastAPI是一个很棒的框架,它可以 简化了创建API的过程。最令人兴奋的特性之一是 它可以生成开箱即用的OpenAPI规范。但是如果。。你有一个 OpenAPI规范,你需要从中创建一个API吗?在
有一天我们遇到了这个问题——我们不得不从多个OpenAPI中创建一个API 规范,并确保传入请求和传出响应 与规格定义的模型一致。在
⚠️ This library was created to cover only our own needs first. So for now it's not suitable for everyone and has a lot of technical restrictions. Please consider it as experimental stuff
安装
该软件包在PyPi上可用:
pip install openapi-to-fastapi
生成FastAPI路由
这个库的主要目的是从OpenAPI生成FastAPI路由 规格。这是通过:
^{pr2}$上面的代码将创建一个FastAPI路由器,它可以包含在 主路由器,或用作默认路由器。在
假设您有以下规格(为了简洁起见,某些零件被截断):
{"openapi":"3.0.2","paths":{"/Company/BasicInfo":{"post":{"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BasicCompanyInfoRequest","responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/BasicCompanyInfoResponse"}}}}}}}}}},"components":{"schemas":{"BasicCompanyInfoRequest":{"title":"BasicCompanyInfoRequest","required":["companyId"],"type":"object","properties":{"companyId":{"title":"Company Id","type":"string","example":"2464491-9"}}},"BasicCompanyInfoResponse":{"title":"BasicCompanyInfoResponse","required":["name","companyId","companyForm"],"type":"object","properties":{"name":{"title":"Name of the company","type":"string"},"companyId":{"title":"ID of the company","type":"string"},"companyForm":{"title":"The company form of the company","type":"string"}}}}}}}}
FastAPI等效路由可能如下所示:
classBasicCompanyInfoRequest(pydantic.BaseModel):companyId:strclassBasicCompanyInfoResponse(pydantic.BaseModel):name:strcompanyId:strcompanyForm:str@router.post("/Company/BasicInfo",response_model=BasicCompanyInfoResponse)def_route(request:BasicCompanyInfoRequest):return{}
并且openapi-to-fastapi
可以自动创建它。在
自定义路由
在大多数情况下,创建没有任何业务逻辑的API是没有意义的。在
以下是如何定义它:
fromfastapiimportHeader,HTTPExceptionfromopenapi_to_fastapi.routesimportSpecRouterspec_router=SpecRouter("./specs")# Default handler for all POST endpoints found in the spec@spec_router.post()defhello_world(params,x_my_token:str=Header(...)):ifx_my_token!="my_token":raiseHTTPException(status_code=403,detail="Sorry")return{"Hello":"World"}# Specific endpoint for a "/pet" route@spec_router.post("/pet")defcreate_pet(params):pet=db.make_pet(name=params.name)returnpet.to_dict()router=spec_router.to_fastapi_router()
API文档
现在你有了很多路线,你可能想利用另一个伟大的 FastAPI的特性-自动文档。在
已经处理了请求和响应模型。但是为了显示文档 需要为每个端点分配一个fastname。你可以这样做 提供以下名称:
fromopenapi_to_fastapi.routesimportSpecRouterspec_router=SpecRouter("./specs")@spec_router.post("/pet",name="Create a pet",description="Create a pet",response_description="A Pet",tags=["pets"],)defcreate_pet(params):return{}# Or you can set the dynamic name based on API pathdefname_factory(path:str,**kwargs):returnpath.replace("/"," ")@spec_router.post(name_factory=name_factory)defcreate_pet(params):return{}
OpenAPI验证
这个包还提供了一个CLI入口点来验证OpenAPI规范。它是 当您需要定义自己的验证规则集时尤其有用。在
假设您的API规范存储在一个单独的存储库中,由 另一支队伍。您还期望所有OpenAPI规范都只有一个端点 定义(一些内部协议)。在
现在,您可以设置CI检查并在每次推送时验证它们。在
首先使用自定义验证器创建一个文件:
# my_validator.pyfromopenapi_to_fastapi.validatorimportBaseValidator,OpenApiValidationErrorclassCustomError(OpenApiValidationError):pass# important: must be inherited from BaseValidatorclassMyValidator(BaseValidator):# implement this single methoddefvalidate_spec(self,spec:dict):iflen(spec["paths"])!=1:raiseCustomError("Only one endpoint allowed")
然后运行该工具:
openapi-validator --path ./standards -m my_validator.py -v MyValidator
===============================================================================
OpenAPI specs root path: ./standards
Validators: DefaultValidator, MyValidator
===============================================================================
File: ./standards/Current.json
[PASSED]
-------------------------------------------------------------------------------
File: ./standards/Metric.json
[PASSED]
-------------------------------------------------------------------------------
File: ./standards/BasicInfo.json
[PASSED]
-------------------------------------------------------------------------------
===============================================================================
Summary:
Total : 3
Passed: 3
Failed: 0
===============================================================================
在生成路由时,也可以重用此验证器:
router=SpecRouter(specs,validators=[MyValidator])
许可证
此代码是根据BSD 3条款许可发布的。中的详细信息 LICENSE文件。在
- 项目
标签: