API Reference

class defspec.spec.OpenAPI(*, openapi: str = '3.1.0', info: ~defspec.spec.OpenAPIInfo = <factory>, paths: dict[str, dict[str, ~defspec.spec.OpenAPIRoute]] = <factory>, defs: dict[str, dict] = <factory>)[source]

OpenAPI specification.

Usage:

openapi = OpenAPI() # init with customized info openapi = OpenAPI(info=OpenAPIInfo(title=”My API”, version=”1.2.3”))

register_route(path, method, summary=None, request_type=None, request_content_type=None, response_type=None, response_content_type=None, query_type=None, header_type=None, cookie_type=None, deprecated=False, schema_hook=None)[source]

Register a route to OpenAPI specification.

Parameters:
  • path (str) – path of the route

  • method (Literal['get', 'post', 'put', 'delete', 'head', 'options', 'connect', 'trace', 'patch']) – HTTP method of the route

  • summary (Optional[str]) – summary of the route

  • request_type (Optional[Type]) – type of the request body

  • request_content_type (Optional[str]) – Content-Type of the request body

  • response_type (Optional[Type]) – type of the response body

  • response_content_type (Optional[str]) – Content-Type of the response body

  • query_type (Optional[Type]) – type of the query parameters

  • header_type (Optional[Type]) – type of the header parameters

  • cookie_type (Optional[Type]) – type of the cookie parameters

  • deprecated (bool) – whether the route is deprecated

  • schema_hook (Optional[Callable[[type], dict[str, Any]]]) – a callable that takes a type and returns a dict for custom schema generation

to_json()[source]

Convert to a JSON bytes that is commonly used in HTTP endpoint.

Return type:

bytes

to_dict()[source]

Convert to a dict.

Return type:

dict

serve_as_http_daemon(host='127.0.0.1', port=8080, run_in_background=False)[source]

Serve the OpenAPI specification and UI as a HTTP server.

  • /openapi/spec.json: the OpenAPI specification

  • /openapi/swagger: the Swagger UI

  • /openapi/redoc: the ReDoc UI

  • /openapi/scalar: the Scalar UI

Parameters:
  • host (str) – host to serve

  • port (int) – port to serve

  • run_in_background (bool) – whether to run in a daemon thread