Movatterモバイル変換


[0]ホーム

URL:


Skip to content
❤️ Support Starlette viasponsors! 📚 Do you like the new docs?Let us know!

Schemas

Starlette supports generating API schemas, such as the widely usedOpenAPIspecification. (Formerly known as "Swagger".)

Schema generation works by inspecting the routes on the application throughapp.routes, and using the docstrings or other attributes on the endpointsin order to determine a complete API schema.

Starlette is not tied to any particular schema generation or validation tooling,but includes a simple implementation that generates OpenAPI schemas based onthe docstrings.

fromstarlette.applicationsimportStarlettefromstarlette.routingimportRoutefromstarlette.schemasimportSchemaGeneratorschemas=SchemaGenerator({"openapi":"3.0.0","info":{"title":"Example API","version":"1.0"}})deflist_users(request):"""    responses:      200:        description: A list of users.        examples:          [{"username": "tom"}, {"username": "lucy"}]    """raiseNotImplementedError()defcreate_user(request):"""    responses:      200:        description: A user.        examples:          {"username": "tom"}    """raiseNotImplementedError()defopenapi_schema(request):returnschemas.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)

We can now access an OpenAPI schema at the "/schema" endpoint.

You can generate the API Schema directly with.get_schema(routes):

schema=schemas.get_schema(routes=app.routes)assertschema=={"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"}}}},},},}

You might also want to be able to print out the API schema, so that you canuse tooling such as generating API documentation.

if__name__=='__main__':assertsys.argv[-1]in("run","schema"),"Usage: example.py [run|schema]"ifsys.argv[-1]=="run":uvicorn.run("example:app",host='0.0.0.0',port=8000)elifsys.argv[-1]=="schema":schema=schemas.get_schema(routes=app.routes)print(yaml.dump(schema,default_flow_style=False))

Third party packages

starlette-apispec

Easy APISpec integration for Starlette, which supports some object serialization libraries.


[8]ページ先頭

©2009-2026 Movatter.jp