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)[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.
  • title – The title of the application (OpenAPI Info Object)
  • version – The version of the OpenAPI document (OpenAPI Info Object)
  • description – The description of the OpenAPI document (OpenAPI Info Object)
  • terms_of_service – A URL to the Terms of Service for the API (OpenAPI Info Object)
  • contact – The contact dictionary of the application (OpenAPI Contact Object)
  • license – The license information of the exposed API (OpenAPI License Object)
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=False, check_existing=True, websocket=False, before_request=False)[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”, and it will become a default route.
  • check_existing – If True, an AssertionError will be raised, if the route is already defined.
add_schema(name, schema, check_existing=True)[source]

Adds a mashmallow schema to the API specification.

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, cleanup, shutdown, tick

Usage:

@api.on_event('startup')
async def open_database_connection_pool():
    ...

@api.on_event('tick', seconds=10)
async def do_stuff():
    ...

@api.on_event('cleanup')
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.
requests = None

A Requests session that is connected to the ASGI app.

route(route=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!"
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]

Runs the application with uvicorn. If the PORT environment 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 – Run uvicorn server in debug mode.
  • options – Additional keyword arguments to send to uvicorn.run().
session(base_url='http://;')[source]

Testing HTTP client. Returns a Requests session object, able to send HTTP requests to the Responder application.

Parameters:base_url – The URL to mount the connection adaptor to.
static_url(asset)[source]

Given a static asset, return its URL path.

template(name_, **values)[source]

Renders the given jinja2 template, with provided values supplied.

Note: The current api instance is by default passed into the view. This is set in the dict api.jinja_values_base.

Parameters:
  • name – The filename of the jinja2 template, in templates_dir.
  • values – Data to pass into the template.
template_string(s_, **values)[source]

Renders the given jinja2 template string, with provided values supplied.

Note: The current api instance is by default passed into the view. This is set in the dict api.jinja_values_base.

Parameters:
  • s – The template to use.
  • values – Data to pass into the template.
url_for(endpoint, **params)[source]

Given an endpoint, returns a rendered URL for its route.

Parameters:
  • endpoint – The route endpoint you’re searching for.
  • params – Data to pass into the URL generator (for parameterized URLs).

Requests & Responses

class responder.Request(scope, receive, api=None)[source]
accepts(content_type)[source]

Returns True if the incoming Request accepts the given content_type.

apparent_encoding

The apparent encoding, provided by the chardet library. Must be awaited.

content

The Request body, as bytes. Must be awaited.

cookies

The cookies sent in the Request, as a dictionary.

encoding

The encoding of the Request’s body. Can be set, manually. Must be awaited.

full_url

The full URL of the Request, query parameters and all.

headers

A case-insensitive dictionary, containing all headers sent in the Request.

media(format=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.
method

The incoming HTTP method used for the request, lower-cased.

params

A dictionary of the parsed query parameters used for the Request.

session

The session data, in dict form, from the Request.

text

The Request body, as unicode. Must be awaited.

url

The parsed URL of the Request.

class responder.Response(req, *, formats)[source]
content

A bytes representation of the response body.

cookies

The cookies set in the Response

headers

A Python dictionary of {key: value}, representing the headers of the response.

media

A Python object that will be content-negotiated and sent back to the client. Typically, in JSON formatting.

session

The cookie-based session data, in dict form, to add to the Response.

status_code

The HTTP Status Code to use for the Response.

Utility Functions

responder.API.status_codes.is_100(status_code)
responder.API.status_codes.is_200(status_code)
responder.API.status_codes.is_300(status_code)
responder.API.status_codes.is_400(status_code)
responder.API.status_codes.is_500(status_code)