API 模式
Starlette 支持生成 API 模式,例如广泛使用的 OpenAPI 规范。(以前称为“Swagger”。)
模式生成的工作原理是通过 app.routes
检查应用程序上的路由,并使用端点上的文档字符串或其他属性,以确定完整的 API 模式。
Starlette 并不与任何特定的模式生成或验证工具绑定,但包含一个简单的实现,该实现基于文档字符串生成 OpenAPI 模式。
from starlette.applications import Starlette
from starlette.routing import Route
from starlette.schemas import SchemaGenerator
schemas = SchemaGenerator(
{"openapi": "3.0.0", "info": {"title": "Example API", "version": "1.0"}}
)
def list_users(request):
"""
responses:
200:
description: A list of users.
examples:
[{"username": "tom"}, {"username": "lucy"}]
"""
raise NotImplementedError()
def create_user(request):
"""
responses:
200:
description: A user.
examples:
{"username": "tom"}
"""
raise NotImplementedError()
def openapi_schema(request):
return schemas.OpenAPIResponse(request=request)
routes = [
Route("/users", endpoint=list_users, methods=["GET"]),
Route("/users", endpoint=create_user, methods=["POST"]),
Route("/schema", endpoint=openapi_schema, include_in_schema=False)
]
app = Starlette(routes=routes)
我们现在可以在“/schema”端点访问 OpenAPI 模式。
您可以使用 .get_schema(routes)
直接生成 API 模式:
schema = schemas.get_schema(routes=app.routes)
assert schema == {
"openapi": "3.0.0",
"info": {"title": "Example API", "version": "1.0"},
"paths": {
"/users": {
"get": {
"responses": {
200: {
"description": "A list of users.",
"examples": [{"username": "tom"}, {"username": "lucy"}],
}
}
},
"post": {
"responses": {
200: {"description": "A user.", "examples": {"username": "tom"}}
}
},
},
},
}
您可能还希望能够打印出 API 模式,以便您可以使用诸如生成 API 文档之类的工具。
if __name__ == '__main__':
assert sys.argv[-1] in ("run", "schema"), "Usage: example.py [run|schema]"
if sys.argv[-1] == "run":
uvicorn.run("example:app", host='0.0.0.0', port=8000)
elif sys.argv[-1] == "schema":
schema = schemas.get_schema(routes=app.routes)
print(yaml.dump(schema, default_flow_style=False))
第三方软件包
星小体 - API 规范
Starlette 易于集成 APISpec,它支持一些对象序列化库。