简介
给你的Sanic API一个UI和OpenAPI文档,使用swagger标准。
安装
sh
pip install sanic-openapi
添加OpenAPI和Swagger UI:
python
from sanic_openapi import swagger_blueprint, openapi_blueprint
app.blueprint(openapi_blueprint)
app.blueprint(swagger_blueprint)
现在你可以有一个Swagger UI at the URL /swagger
. 你的routes
会被他们的blueprints
自动分类。
用法
使用简单的decorator来记录路由:
python
from sanic_openapi import doc
@app.get("/user/<user_id:int>")
@doc.summary("Fetches a user by ID")
@doc.produces({ "user": { "name": str, "id": int } })
async def get_user(request, user_id):
...
@app.post("/user")
@doc.summary("Creates a user")
@doc.consumes({"user": { "name": str }}, location="body")
async def create_user(request):
...
你的输入/输出 Model
python
class Car:
make = str
model = str
year = int
class Garage:
spaces = int
cars = [Car]
@app.get("/garage")
@doc.summary("Gets the whole garage")
@doc.produces(Garage)
async def get_garage(request):
return json({
"spaces": 2,
"cars": [{"make": "Nissan", "model": "370Z"}]
})
得到更多的描述
python
class Car:
make = doc.String("Who made the car")
model = doc.String("Type of car. This will vary by make")
year = doc.Integer("4-digit year of the car", required=False)
class Garage:
spaces = doc.Integer("How many cars can fit in the garage")
cars = doc.List(Car, description="All cars in the garage")
Configure all the things
python
app.config.API_VERSION = '1.0.0'
app.config.API_TITLE = 'Car API'
app.config.API_DESCRIPTION = 'Car API'
app.config.API_TERMS_OF_SERVICE = 'Use with caution!'
app.config.API_PRODUCES_CONTENT_TYPES = ['application/json']
app.config.API_CONTACT_EMAIL = '[email protected]'