最近FastAPI项目特别火,以下是我们项目组在用FastAPI开发时的总结的一些最佳实践以及一些代码规范,分享给大家。
通用规范
- 请勿将敏感信息包括但不限于密码信息,客户信息等上传到代码库!
- 代码提交前检查一下有没有调试时的print或者log代码没删除干净;
- 代码风格:用Pycharm的同学,先
Ctrl+Alt+L
应用一下PEP8风格,再用Ctrl+Alt+I
调整一下Import顺序。 用VS Code的请用插件搞定上述需求; - Commit 信息:请贴上需求管理系统相关链接;
- PR:push自己的开发分支到远程,如果commit较多(超过3个)建议本地rebase成一个commit以后再push上来,提交评审后根据评审意见逐条确认,全部修改以后再push一个新的commit。
- 分支合并策略:默认情况下合并分支采用squash方式,且合并后会删除该分支,如需要保存请提前沟通或者备注。
- 提交评审请对照下面的规范👇自检;
FastAPI开发规范
-
router
函数需要添加docs,方便用户了解接口用途, 例如:@router.get("/{callback_id}/records/last", response_model=CallBackRecordResponse) async def get_last_callback_record(callback_id: int, db: Session = Depends(get_db)): """查询最后一次回调记录""" return crud.get_last_callback_record(db, callback_id)
-
body
和response
应该声明为pydentic.BaseModel
的子类,并且使用Field
类声明默认值(如果有),描述信息(必须),举例值(如果必要)等,例如:class CallBackBase(BaseModel): path: Optional[str] = Field( default=None, example="", description="If not specific, it will generate random path") tags: Optional[list] = Field( default=None, description="tags of the custom callback", example=["tag1", "tag2"])
-
如果router函数不能直接推断出返回值类型的话(比如CRUD的结果),应当在router装饰器的resposne_model参数里声明类型,例如:
@router.get("/{callback_id}", response_model=CallBackResponse) async def get_callback(callback_id: int, db: Session = Depends(get_db)): """查询回调URL的定义""" schema_callback = crud.get_callback_by_id(db, callback_id) if not schema_callback: raise HTTPException(status_code=404, detail="Callback does not exists!") return schema_callback
-
schemas里的类名应该使用XXXBase, XXXCreate, XXXResponse等形式,避免跟sqlalchemy的models类名冲突,例如:
# models.callback.py class CallBack(Base): ... # schemas.callback.py class CallBackBase(BaseModel): # 基类 ... class CallBackCreate(CallBackBase): # 创建类 pass class CallBackResponse(CallBackBase): #响应类 ...
原则上所有资源都要添加tags域,方便后续进行资源筛选以及权限控制;
RESTAPI规范
-
参考阮一峰的文档http://www.ruanyifeng.com/blog/2018/10/restful-api-best-practices.html, 提一下需要注意的点
路径使用复数;
注意使用规范的状态码,参考下表:比如POST请求一般成功会返回201,资源不存在返回404等;
-
方法 CRUD 集合操作 个体操作 POST Create 201 (Created), 'Location' header with link to /customers/{id} containing new ID. 404 (Not Found), 409 (Conflict) if resource already exists.. GET Read 200 (OK), list of customers. Use pagination, sorting and filtering to navigate big lists. 200 (OK), single customer. 404 (Not Found), if ID not found or invalid. PUT Update/Replace 405 (Method Not Allowed), unless you want to update/replace every resource in the entire collection. 200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid. PATCH Update/Modify 405 (Method Not Allowed), unless you want to modify the collection itself. 200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid. DELETE Delete 405 (Method Not Allowed), unless you want to delete the whole collection—not often desirable. 200 (OK). 404 (Not Found), if ID not found or invalid.