我们都知道,fastApi给我们提供了接口文档,在我们的实际开发中,我们会有很多的接口,有些接口需要分组,比如我们对于登录注册相关的模块,可以统一放在登录,那么我们如何实现划分呢。
- from fastapi import FastAPI
-
- app = FastAPI()
-
-
- @app.post("/login", tags=["login"])
- def login(username: str, password: str):
- if username == "lc" and password == "123":
- return "success"
- return {"msg": "name or password error"}
-
-
- @app.post("/register", tags=["login"])
- def resgister(username: str, password: str):
- return {"msg": "success"}
我们看下,接口文档
可以看到,我们实现的登录的模块是成功的。
我们来看下,如何对接口增加一个简单的描述(增加description参数)
- from fastapi import FastAPI
-
- app = FastAPI()
-
-
- @app.post("/login", tags=["login"], description="这是登录接口")
- def login(username: str, password: str):
- if username == "lc" and password == "123":
- return "success"
- return {"msg": "name or password error"}
-
-
- @app.post("/register", tags=["login"])
- def resgister(username: str, password: str):
- return {"msg": "success"}
再看下接口
如果我们想要把所有的注释以给读取出来,然后展示在描述中,fastapi也给我们做了很好的封装,我们可以简单的看下代码
- from fastapi import FastAPI
-
- app = FastAPI()
-
-
- @app.post("/login", tags=["login"], summary="这是登录接口")
- def login(username: str, password: str):
- """
- 登录
- :param username: 用户名
- :param password: 密码
- :return: 是否成功
- """
- if username == "lc" and password == "123":
- return "success"
- return {"msg": "name or password error"}
-
-
- @app.post("/register", tags=["login"])
- def resgister(username: str, password: str):
- return {"msg": "success"}
我们看下最后的实现的效果
如果我们要标注接口弃用怎么实现呢?(增加deprecated参数)
- from fastapi import FastAPI
-
- app = FastAPI()
-
-
- @app.post("/login", tags=["login"], summary="这是登录接口")
- def login(username: str, password: str):
- """
- 登录
- :param username: 用户名
- :param password: 密码
- :return: 是否成功
- """
- if username == "lc" and password == "123":
- return "success"
- return {"msg": "name or password error"}
-
-
- @app.post("/register", tags=["login"], deprecated=True)
- def resgister(username: str, password: str):
- return {"msg": "success"}
看下效果