API Documentation¶
Web Service (API) Class¶
- class responder.API(*, debug=False, title=None, version=None, description=None, terms_of_service=None, contact=None, license=None, openapi=None, openapi_route='/schema.yml', static_dir='static', static_route='/static', templates_dir='templates', auto_escape=True, secret_key='NOTASECRET', enable_hsts=False, docs_route=None, cors=False, cors_params={'allow_credentials': False, 'allow_headers': (), 'allow_methods': ('GET',), 'allow_origin_regex': None, 'allow_origins': (), 'expose_headers': (), 'max_age': 600}, allowed_hosts=None, openapi_theme='swagger_ui', lifespan=None, request_id=False)[source]¶
The primary web-service class.
- Parameters:
static_dir – The directory to use for static files. Will be created for you if it doesn’t already exist.
templates_dir – The directory to use for templates. Will be created for you if it doesn’t already exist.
auto_escape – If
True, HTML and XML templates will automatically be escaped.enable_hsts – If
True, send all responses to HTTPS URLs.openapi_theme – OpenAPI documentation theme, must be one of
elements,rapidoc,redoc,swagger_ui
- add_event_handler(event_type, handler)[source]¶
Adds an event handler to the API.
- Parameters:
event_type – A string in (“startup”, “shutdown”)
handler – The function to run. Can be either a function or a coroutine.
- add_route(route=None, endpoint=None, *, default=False, static=True, check_existing=True, websocket=False, before_request=False, methods=None)[source]¶
Adds a route to the API.
- Parameters:
route – A string representation of the route.
endpoint – The endpoint for the route – can be a callable, or a class.
default – If
True, all unknown requests will route to this view.static – If
True, and no endpoint was passed, render “static/index.html”. Also, it will become a default route.methods – Optional list of HTTP methods (e.g.
["GET", "POST"]).
- after_request()[source]¶
Register a function to run after every request.
Usage:
@api.after_request() def add_request_id(req, resp): resp.headers["X-Request-ID"] = str(uuid.uuid4())
- exception_handler(exception_cls)[source]¶
Register a handler for a specific exception type.
Usage:
@api.exception_handler(ValueError) async def handle_value_error(req, resp, exc): resp.status_code = 400 resp.media = {"error": str(exc)}
- graphql(route='/graphql', *, schema)[source]¶
Mount a GraphQL API at the given route.
Usage:
import graphene class Query(graphene.ObjectType): hello = graphene.String(name=graphene.String(default_value="stranger")) def resolve_hello(self, info, name): return f"Hello {name}" api.graphql("/graphql", schema=graphene.Schema(query=Query))
- Parameters:
route – The URL path for the GraphQL endpoint.
schema – A Graphene schema instance.
- group(prefix)[source]¶
Create a route group with a shared URL prefix.
Usage:
v1 = api.group("/v1") @v1.route("/users") def list_users(req, resp): resp.media = [] @v1.route("/users/{id:int}") def get_user(req, resp, *, id): resp.media = {"id": id}
- mount(route, app)[source]¶
Mounts an WSGI / ASGI application at a given route.
- Parameters:
route – String representation of the route to be used (shouldn’t be parameterized).
app – The other WSGI / ASGI app.
- on_event(event_type: str, **args)[source]¶
Decorator for registering functions or coroutines to run at certain events Supported events: startup, shutdown
Usage:
@api.on_event('startup') async def open_database_connection_pool(): ... @api.on_event('shutdown') async def close_database_connection_pool(): ...
- path_matches_route(path)[source]¶
Given a path portion of a URL, tests that it matches against any registered route.
- Parameters:
path – The path portion of a URL, to test all known routes against.
- redirect(resp, location, *, set_text=True, status_code=301)[source]¶
Redirects a given response to a given location.
- Parameters:
resp – The Response to mutate.
location – The location of the redirect.
set_text – If
True, sets the Redirect body content automatically.status_code – an API.status_codes attribute, or an integer, representing the HTTP status code of the redirect.
- property requests¶
A test client connected to the ASGI app. Lazily initialized.
- route(route=None, *, request_model=None, response_model=None, **options)[source]¶
Decorator for creating new routes around function and class definitions.
Usage:
@api.route("/hello") def hello(req, resp): resp.text = "hello, world!"
With Pydantic models for OpenAPI documentation:
from pydantic import BaseModel class ItemIn(BaseModel): name: str price: float class ItemOut(BaseModel): id: int name: str price: float @api.route("/items", methods=["POST"], request_model=ItemIn, response_model=ItemOut) async def create_item(req, resp): data = await req.media() resp.media = {"id": 1, **data}
- schema(name, **options)[source]¶
Decorator for creating new routes around function and class definitions.
Usage:
from marshmallow import Schema, fields @api.schema("Pet") class PetSchema(Schema): name = fields.Str()
- serve(*, address=None, port=None, debug=False, **options)[source]¶
Run the application with uvicorn.
If the
PORTenvironment variable is set, requests will be served on that port automatically to all known hosts.- Parameters:
address – The address to bind to.
port – The port to bind to. If none is provided, one will be selected at random.
debug – Whether to run application in debug mode.
options – Additional keyword arguments to send to
uvicorn.run().
- session(base_url='http://;')[source]¶
Testing HTTP client. Returns a Starlette TestClient instance, able to send HTTP requests to the Responder application.
- Parameters:
base_url – The base URL for the test client.
- template(filename, *args, **kwargs)[source]¶
Render a Jinja2 template file with the provided values.
- Parameters:
filename – The filename of the jinja2 template, in
templates_dir.*args – Data to pass into the template.
**kwargs – Data to pass into the template.
Requests & Responses¶
- class responder.Request(scope, receive, api=None, formats=None)[source]¶
-
- property apparent_encoding¶
The apparent encoding, detected automatically. Must be awaited.
Uses chardet for detection if installed, otherwise falls back to UTF-8.
- property client¶
The client’s address as a (host, port) named tuple, or None.
- property content¶
The Request body, as bytes. Must be awaited.
- property cookies¶
The cookies sent in the Request, as a dictionary.
- property encoding¶
The encoding of the Request’s body. Can be set, manually. Must be awaited.
- property full_url¶
The full URL of the Request, query parameters and all.
- property headers¶
A case-insensitive dictionary, containing all headers sent in the Request.
- property is_json¶
Returns
Trueif the request content type is JSON.
- async media(format: str | Callable = None)[source]¶
Renders incoming json/yaml/form data as Python objects. Must be awaited.
- Parameters:
format – The name of the format being used. Alternatively, accepts a custom callable for the format type.
- property method¶
The incoming HTTP method used for the request, lower-cased.
- property params¶
A dictionary of the parsed query parameters used for the Request.
- property path_params: dict¶
The path parameters extracted from the URL route.
- property session¶
The session data, in dict form, from the Request.
- property state: State¶
Use the state to store additional information.
This can be a very helpful feature, if you want to hand over information from a middelware or a route decorator to the actual route handler.
Usage:
request.state.time_started = time.time()
- property text¶
The Request body, as unicode. Must be awaited.
- property url¶
The parsed URL of the Request.
- class responder.Response(req, *, formats)[source]¶
- content¶
A bytes representation of the response body.
- cookies: SimpleCookie¶
The cookies set in the Response
- file(path, *, content_type=None)[source]¶
Serve a file from disk as the response.
- Parameters:
path – Path to the file to serve.
content_type – Optional MIME type override.
- formats¶
representing the headers of the response.
- headers¶
A Python dictionary of
{key: value},
- media¶
A Python object that will be content-negotiated and
- session¶
The cookie-based session data, in dict form, to add to the Response.
- sse(func, *args, **kwargs)[source]¶
Set up Server-Sent Events streaming.
Usage:
@api.route("/events") async def events(req, resp): @resp.sse async def stream(): for i in range(10): yield {"data": f"message {i}"}
Each yielded dict can have: data, event, id, retry. Yielding a string is treated as data.
- status_code: int | None¶
The HTTP Status Code to use for the Response.