代码拉取完成,页面将自动刷新
APIMAN provide a easy way to integrate api manual/document for your web project
pip install -U apiman
Let's see a Starlette example app:
"""OpenAPI2(Swagger) with Starlette
"""
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.endpoints import HTTPEndpoint
from uvicorn import run
from openapi_spec_validator import validate_v2_spec
from starlette.testclient import TestClient
from apiman.starlette import Extension
app = Starlette()
openapi = Extension(template="./examples/docs/cat_template.yml")
openapi.init_app(app)
# define data
CATS = {
1: {"id": 1, "name": "DangDang", "age": 2},
2: {"id": 2, "name": "DingDing", "age": 1},
}
# add schema definition
openapi.add_schema(
"Cat",
{
"properties": {
"id": {"description": "global unique", "type": "integer"},
"name": {"type": "string"},
"age": {"type": "integer"},
},
"type": "object",
},
)
# define routes and schema(in doc string)
@app.route("/cat/")
class Cat(HTTPEndpoint):
"""
Declare multi method
---
get:
summary: Get single cat
tags:
- cat
parameters:
- name: id
type: integer
in: path
required: True
responses:
"200":
description: OK
schema:
$ref: '#/definitions/Cat'
"404":
description: Not found
"""
def get(self, req: Request):
return JSONResponse(CATS[int(req.path_params["id"])])
def delete(self, req: Request):
"""
Declare single method
---
summary: Delete single cat
tags:
- cat
parameters:
- name: id
type: integer
in: path
required: True
responses:
"204":
description: OK
schema:
$ref: '#/definitions/Cat'
"404":
description: Not found
"""
cat = CATS.pop(int(req.path_params["id"]))
return JSONResponse(cat)
# define doc by yaml or json file
@app.route("/cats/", methods=["GET"])
@openapi.from_file("./examples/docs/cats_get.yml")
def list_cats(req: Request):
return JSONResponse(list(CATS.values()))
@app.route("/cats/", methods=["POST"])
@openapi.from_file("./examples/docs/cats_post.json")
async def list_cats(req: Request):
cat = await req.json()
CATS[cat["id"]] = cat
return JSONResponse(cat)
if __name__ == "__main__":
run(app)
Then we can get swagger web page at http://localhost:8000/apiman/swagger/:
See examples/ for more examples
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。