The API Reference

This part of the documentation covers req’s Python interfaces.

Endpoints

Use Endpoints and Methods to declare how to get to your data.

class req.Endpoint[source]

The base class for an endpoint.

The following properties can be set during Endpoint definition:

name

The name of this Endpoint. Defaults to the lower-cased class name.

Type:str
description

The publishable description for this endpoint. Defaults to the empty string.

Type:str
path

The relative path of this Endpoint. Defaults to the lower-cased class name.

Type:str
envs

The environments in which this Endpoint must be available. Defaults to ().

Type:str tuple
handler

The path to this Endpoint’s handler. Defaults to None.

Type:str
order

The sort order for this endpoint’s children. By default the ordering is nondeterministic.

Type:Endpoint list
reverse

Whether or not the above-mentioned order should be applied in reverse. Defaults to false.

Type:bool

The following properties are generated automatically and should be considered read-only:

parent

A reference to this Endpoint’s parent. None for top-level Endpoints.

Type:Endpoint
children

A list of this Endpoint’s children.

Type:Endpoint list
handler_class

The handler for this Endpoint.

Type:object
full_uri

The parsed URI for the given path.

Type:URI
parameters

The parameters that this Endpoint expects.

Type:URIParameter list

Examples

>>> from req import Endpoint, Method, schema
>>> class V1(Endpoint):
...   path = "/an-api/v1"
...
...   class Users(Endpoint):
...     class User(Endpoint):
...       path = "/{uid}"
...       handler = "path.to.UserHandler"
...
...       class GET(Method):
...         Response = schema.UserResponse
...
...       class PUT(Method):
...         Request = schema.UpdateUserRequest
...         Response = schema.UserResponse
>>> V1.name
"v1"
>>> V1.Users.name
"users"
>>> V1.Users.User.build_uri("1")
"/an-api/v1/users/1"
>>> V1.Users.handler_class
None
>>> V1.Users.User.handler_class
<class 'path.to.Userhandler'>
>>> V1.Users.User.parameters
[{uid}]
>>> V1.Users.User.full_uri
"/an-api/v1/users/{uid}"
>>> V1.Users.User.uri
"/{uid}"
class req.Method[source]

The base class for a method.

The following properties can be set during Method definition:

description

The publishable description for this method. Defaults to the empty string.

Type:str
QueryString

The schema to use when validating the query string.

Type:Schema
Request

The schema to use when validating the request body.

Type:Schema
RequestHeaders

The schema to use when validating the request headers.

Type:Schema
Response

The schema of the response body.

Type:Schema
ResponseHeaders

The schema of the response headers.

Type:Schema

Examples

>>> from req import Method, schema
>>> class POST(Method):
...   class Request(schema.Schema):
...     name = schema.String()

Adapters

class req.adapter.EndpointAdapter[source]

Base class for defining endpoint.Endpoint adapters. Endpoint adapters translate endpoint definitions from code to any other representation.

build(endpoint)[source]

Build the target representation given an endpoint.

Parameters:endpoint (Endpoint) – The Endpoint to represent.
Returns:The new representation.
Return type:object
class req.adapter.DictionaryAdapter(schema_adapter)[source]

Adapts an endpoint.Endpoint to a dict.

Parameters:schema_adapter (Adapter) – The Adapter to apply to schemas.
build(endpoint, deep=True, whitelist=None)[source]

Build a dictionary representing the spec for endpoint.

Parameters:
  • endpoint (Endpoint) –
  • deep (bool) – Whether or not to adapt the Endpoint’s children as well. Defaults to True.
  • whitelist (method list) – The set of methods to adapt. If None, all methods will be included.
Returns:

The new representation.

Return type:

dict

class req.adapter.SwaggerAdapter(host, base_path, title, description, version, schemes=('https', ), security_definitions=None, security=None)[source]

Adapts an endpoint.Endpoint to a Swagger 2.0 specification.

Parameters:
  • host (str) – The host serving the API. This may include a port but must not include a scheme or a base path.
  • base_path (str) – The base path on which the API is served, this is relative to host.
  • title (str) – The title of the application.
  • description (str) – The description of the application. Markdown syntax can be used for rich text representation.
  • version (str) – The version of the application API.
  • schemes (str tuple) – The list of supported transfer protocols.
  • security_definitions (None|dict) – The security definitions. This is included as is so the caller must ensure that it is a valid Swagger Security Defintions object.
  • security (None|dict) – The security requirement object. Like security_definitions, this is included as is and applies to the entire API.
build(endpoint)[source]

Build a dictionary representing the Swagger spec for endpoint.

Parameters:endpoint (Endpoint) –
Returns:The Swagger representation of endpoint.
Return type:dict

Schema

Use Schemas to declare the shape of your data.

class req.schema.SchemaLike(_name=None, _description=None, _optional=None)[source]

Base class for objects that describe the structure of data.

Parameters:
  • _name (str) – This represents the object’s serialized name. If this is provided then this string will be used during attribute lookups.
  • _description (str) – This represents the object’s description when it gets adapted to some output format such as JSONSchema.
  • _optional (bool) – When embedded as a property in a Schema this attribute determines whether or not that property is optional. This applies to any SchemaLike instance.
materialize(sparse=False)[source]

Return the concrete value for this instance.

update(value)[source]

Update this instance’s value.

Note

If you want to both validate and update a SchemaLike based on some data then you should use this method directly as it validates the input data before updating the instance.

Raises:ValidationError
Parameters:value (object) – The object that will replace this instance’s underlying value. This value will be validated prior to assignment.
Returns:On success.
Return type:None
validate(data)[source]

Validate data against this instance.

Parameters:value (object) – The object to validate.
Returns:On success.
Return type:None
class req.schema.Schema(_optional=False, _description=None, **properties)[source]

Bases: req.schema.schema.SchemaLike

Schema describe the structure of data. Schema instances can be treated like models in an ORM.

Parameters:
  • _name (str) – This represents the object’s serialized name. If this is provided then this string will be used during attribute lookups.
  • _description (str) – This represents the object’s description when it gets adapted to some output format such as JSONSchema.
  • _optional (bool) – When embedded as a property in a Schema this attribute determines whether or not that property is optional. This applies to any SchemaLike instance.

Examples

>>> from schema import *
>>> class Meta(Schema):
...   id = String()
>>> class Resource(Schema):
...   _meta = Meta()
>>> class User(Resource):
...   name = String()
>>> m = Meta(id="a-user")
<#Meta properties={'id': <.String value='a-user'>}>
>>> u = User(_meta=m, name="A User")
<#User properties={'_meta': <#Meta properties={'id': <.String value='a-user'}, 'name': <.String value='A User'}>
>>> m.materialize()
{'id': 'a-user'}
>>> u.materialize()
{'_meta': {'id': 'a-user"}, 'name': 'A User'}
>>> u.validate({})
Traceback (most recent call last):
  ...
ValidationError: ['_meta: missing', 'name: missing']
>>> u.validate({"_meta": {"id": 42}})
Traceback (most recent call last):
  ...
ValidationError: ['_meta.id: invalid string', 'name: missing']
>>> u.validate({"_meta": {"id": "a-user"}, "name": "A user"})
>>> u.meta.id
'a-user'
>>> u.name
'A user'
materialize(sparse=False)[source]

Materializes this Schema into a dictionary recursively.

Parameters:sparse (bool) – Controls whether or not null properties should be included in the result.
Returns:The dictionary representation of this instance.
Return type:dict
update(data)[source]

Validate data against this Schema and set its properties to the appropriate values from the data dictionary on succcess.

Raises:ValidationError – If data fails to Schema.validate().
Parameters:data (dict) –
Returns:On success.
Return type:None
validate(data)[source]

Validate data against this Schema.

Raises:ValidationError – When the dictionary fails to validate.
Parameters:data (dict) –
Returns:On success.
Return type:None
class req.schema.Property(_name=None, _description=None, _optional=None)[source]

Bases: req.schema.schema.SchemaLike

Base class for Properties.

Parameters:
  • _name (str) – This represents the object’s serialized name. If this is provided then this string will be used during attribute lookups.
  • _description (str) – This represents the object’s description when it gets adapted to some output format such as JSONSchema.
  • _optional (bool) – When embedded as a property in a Schema this attribute determines whether or not that property is optional. This applies to any SchemaLike instance.
_validate(data)[source]

All Property subclasses must implement this method.

materialize(sparse=False)[source]

Return the concrete value for this instance.

update(value)[source]

Update this instance’s value.

Note

If you want to both validate and update a SchemaLike based on some data then you should use this method directly as it validates the input data before updating the instance.

Raises:ValidationError
Parameters:value (object) – The object that will replace this instance’s underlying value. This value will be validated prior to assignment.
Returns:On success.
Return type:None
validate(data)[source]

Validate data against this instance.

Parameters:value (object) – The object to validate.
Returns:On success.
Return type:None
req.schema.Alternative(*schemas)[source]

Unifies a list of Schema subclasses into one, selecting the most appropriate one on each call to SchemaLike.validate().

See the examples for more information.

Note

You may not specify additional properties on an Alternative and it is your responsibility to ensure that the schemas you provide it with upon creation are not ambiguous when validated against each other’s data.

Examples

>>> from schema import *
>>> class ResetPasswordRequest(Schema):
...   password = String()
...   reset_token = String(_name="token")
>>> class UpdateUsernameRequest(Schema):
...   username = String()
>>> class PatchUserRequest(Alternative(
...     UpdateUsernameRequest,
...     ResetPasswordRequest
... )):
...   pass
>>> r = PatchUserRequest()
>>> request = r.validate({"username": "new-username"})
>>> r.validate({"password": "a-password", "token": "foo"})
ResetPasswordRequest(...)
>>> r.validate({"username": "new-username"})
UpdateUsernameRequest(...)
>>> r.update({"username": "new-username"})
>>> r.username
"new-username"
>>> r.materialize()
{"username": "new-username"}
>>> isinstance(r._schema, UpdateUsernameRequest)
True
>>> isinstance(r._schema, ResetPasswordRequest)
False
Parameters:schemas (Schema list) – A list of Schema classes.
Returns:A Schema representing the disjoint union of the input Schema.
Return type:Schema

Properties

class req.schema.Boolean(_name=None, _description=None, _optional=None)[source]

A property for booleans.

Examples

>>> from req.schema import Boolean
>>> b = Boolean()
>>> b.validate(False)
>>> b.validate(True)
>>> b.validate(1)
Traceback (most recent call last):
  ...
ValidationError: ['invalid boolean']
class req.schema.Number(_minimum=None, _maximum=None, _multiple_of=None, **options)[source]

A property for numbers.

Examples

>>> from req.schema import Number
>>> n = Number()
>>> n.validate(1)
>>> n.validate(1.25)
>>> n.validate("a")
Traceback (most recent call last):
  ...
ValidationError: ['invalid number']
Parameters:
  • _minimum (int|float) – The minimum value the number can have.
  • _maximum (int|float) – The maximum value the number can have.
  • _multiple_of (int|float) – A value the number must be a multiple of.
class req.schema.Integer(_minimum=None, _maximum=None, _multiple_of=None, **options)[source]

Like Number but specifically for integers.

Examples

>>> from req.schema import Integer
>>> i = Integer()
>>> i.validate(1)
>>> i.validate(1.0)
Traceback (most recent call last):
  ...
ValidationError: ['invalid integer']
class req.schema.String(_min_length=None, _max_length=None, _choices=None, **options)[source]

A property for strings.

Examples

>>> from req.schema import String
>>> s = String()
>>> s.validate("hello")
>>> s.validate(1)
Traceback (most recent call last):
  ...
ValidationError: ['invalid string']
>>> s = String(_choices=("a", "b", "c"))
>>> s.validate("a")
>>> s.validate("d")
Traceback (most recent call last):
  ...
ValidationError: ['must be one of ("a", "b", "c")']
Parameters:
  • _min_length (int) – The minimum length of the string.
  • _max_length (int) – The maximum length of the string.
  • _choices (str list) – A constraint for the possible string values of this property.
class req.schema.DateTime(_format=None, **options)[source]

A property for date time strings.

Examples

>>> from req.schema import DateTime
>>> d = DateTime()
>>> d.validate("2015-01-01T00:00Z")
>>> d.validate("2015-01-01T00:00")
Traceback (most recent call last):
  ...
ValidationError: ['datetimes must include timezone']
>>> d = DateTime(_format="%Y")
>>> d.update("2015-01-01T12:35Z")
>>> d.materialize()
"2015"
Parameters:_format (str) – The datetime compatible format to use when rendering this property.
class req.schema.Email(_name=None, _description=None, _optional=None)[source]

Like String but constrained to values that are valid e-mail addresses.

Examples

>>> from req.schema import Email
>>> e = Email()
>>> e.validate("foo@example.com")
>>> e.validate("foo")
Traceback (most recent call last):
  ...
ValidationError: ['invalid e-mail "foo"']
class req.schema.URI(_name=None, _description=None, _optional=None)[source]

Like String but constained to values that are valid URIs.

Examples

>>> from req.schema import URI
>>> u = URI()
>>> u.validate("http://google.com")
>>> u.validate("ftp://example.com")
>>> u.validate("//example.com")
Traceback (most recent call last):
  ...
ValidationError: ['invalid URI "//example.com"']
class req.schema.Regexp(_expression, **options)[source]

A property for regular expressions.

Examples

>>> from req.schema import Regexp
>>> r = Regexp(r"\d+")
>>> r.validate("123")
>>> r.validate("a")
Traceback (most recent call last):
  ...
ValidationError: ['must match regexp "\\d+"']
Parameters:expression (str) – The regular expression to validate values against.
class req.schema.IPv4(_name=None, _description=None, _optional=None)[source]

Like String but constained to values that are valid IPv4 addresses.

Examples

>>> from req.schema import IPv4
>>> i = IPv4()
>>> i.validate("127.0.0.1")
>>> i.validate("10.1.1.5")
>>> i.validate("255.255.255.256")
Traceback (most recent call last):
  ...
ValidationError: ['invalid ipv4 address "255.255.255.256"']
class req.schema.IPv6(_name=None, _description=None, _optional=None)[source]

Like IPv4 but for IPv6 addresses.

Examples

>>> from req.schema import IPv6
>>> i = IPv6()
>>> i.validate("::")
>>> i.validate("2001:db8::1")
>>> i.validate("2001:db8::z1")
Traceback (most recent call last):
  ...
ValidationError: ['invalid ipv6 address "2001:db8::z1"']
class req.schema.List(_item_property=None, _min_items=None, _max_items=None, _unique_items=None, **options)[source]

A property for lists.

Examples

>>> from req.schema import List, Integer
>>> l = List()
>>> l.validate([])
>>> l.validate(["a", 1, [2, 3]])
>>> l = List(Integer())
>>> l.validate([])
>>> l.validate([1, 2, 3])
>>> l.validate(["a", 1])
Traceback (most recent call last):
  ..
ValidationError: ['0: invalid integer']
Parameters:
  • _item_property (SchemaLike) – If provided, then every element in the list will be expected to validate against that Schema. If omitted, this will accept any list.
  • _min_items (int) – The minimum number of items the list can contain.
  • _max_items (int) – The maximum number of items the list can contain.
  • _unique_items (bool) – Whether or not every item in the list must be unique.
class req.schema.Tuple(*properties, **options)[source]

A property for fixed length containers.

Examples

>>> from req.schema import Tuple, String, Number
>>> t = Tuple(String(), String(), Number())
>>> t.validate(["a", "b", 1])
>>> t.validate([1, "b", 1])
Traceback (most recent call last):
  ...
ValidationError: ['invalid string at index 0']
>>> t.validate(["a", "b", 1, 2])
Traceback (most recent call last):
  ...
ValidationError: ['bad tuple size, expected 3 items']
Parameters:*properties (SchemaLike list) – A list of Schema representing the elements of the tuple.
class req.schema.Dictionary(_name=None, _description=None, _optional=None, **properties)[source]

A Dictionary property.

Examples

>>> from req.schema import Dictionary, String, Number
>>> d = Dictionary(a=String(), b=Number())
>>> d.validate({"a": "hello", "b": 42})
>>> d.validate({"a": 24, "b": 42})
Traceback (most recent call last):
  ...
ValidationError: ['a: invalid string']
Parameters:**properties (dict) – A dictionary representing each key and its schema in the input data. If omitted, arbitrary dictionaries will be accepted.
class req.schema.ValueDictionary(_item_property=None, _name=None, _description=None, _optional=None)[source]

A Dictionary variant that validates all values against the specified SchemaLike.

Examples

>>> from req.schema import Number, ValueDictionary
>>> v = ValueDictionary(Number())
>>> v.validate({"a": 1, "b": 2})
>>> v.validate({"a": "hello"})
Traceback (most recent call last):
  ...
ValidationError: ['a: invalid number']
Parameters:_item_property (SchemaLike) – A SchemaLike representing what shape each value in the dictionary must have.
class req.schema.Or(*validations, **options)[source]

A property for values that can have multiple shapes.

Examples

>>> from req.schema import Or, String, Integer
>>> o = Or(String(), Integer())
>>> o.validate("a")
>>> o.validate(1)
>>> o.validate(1.5)
Traceback (most recent call last):
  ...
ValidationError: [['invalid string for String schema'], ['invalid integer for Integer schema']]
Parameters:*validations (SchemaLike list) – A list of acceptable types. Values are validated against each one in order until one succeeds or all of them fail.
req.schema.Lazy(schema)[source]

Lazily refrence a schema using either its fully qualified name or its name within the module Lazy is called in. Doing either of these things will ensure that the schema is instantiated lazily.

Note

Because of the way these schemas are lazy loaded you cannot reference dynamically-generated schemas.

Note

You must ensure you don’t shadow the definition of schema within your module.

Note

Un-qualified names rely on the Python implementation you’re running req on to have stack frame support.

Examples

>>> class Nil(Schema):
...     def validate(self, data):
...         if data:
...             raise ValidationError("Nil must be empty")
>>> class Cons(Schema):
...     car = Integer()
...     cdr = Or(Lazy("Cons"), Nil())
>>> class ConsQualified(Schema):
...     car = Integer()
...     cdr = Or(Lazy("tests.test_lazy.ConsQualified"), Nil())
>>> l = Cons()
>>> l.validate({"car": 1, "cdr": {"car": 2, "cdr": {}}})
>>> l.update({"car": 1, "cdr": {"car": 2, "cdr": {}}})
>>> l.validate({"car": 1, "cdr": {"car": "2", "cdr": {}}})
Traceback (most recent call last):
  ...
ValidationError: ['cdr.car: invalid integer for Cons schema']
Raises:
  • RuntimeError – When the object referenced by schema cannot be found at runtime.
  • TypeError – When the object referenced by schema is not a subclass of SchemaLike. This error is raised at runtime.
Parameters:

schema (str) – The name of a Schema.

Returns:

A proxy that will lazily instantiate the referenced schema on its first use.

Return type:

Schema

Exceptions

exception req.schema.ValidationError(message)[source]

Raised by SchemaLikes whenever some data fails to validate.

message

One or more error messages.

Type:str|str list

Adapters

class req.schema.adapter.SchemaAdapter[source]

Base class for defining Schema adapters. Schema adapters are instances which given an input Schema class return that schema in a different format.

build(schema)[source]

Build the target schema from the source schema.

Parameters:schema (Schema) – The source schema.
Returns:The adapted schema.
Return type:object
class req.schema.adapter.JSONSchemaAdapter(path=None, parent=None)[source]

An adapter for JSONSchema.

build(input_schema, schema_uri=None, path=None)[source]

Convert input_schema to JSONSchema.

Parameters:schema (Schema) – The source schema.
Returns:The JSONSchema as a dict.
Return type:dict

Falcon Integration

req.falcon.register(app, endpoint, logger=None)[source]

Register endpoint and all its children with the given Falcon application.

Raises:

TypeError – When app is not a falcon.API instance.

Parameters:
  • app (falcon.API) – The application with which to register the endpoints.
  • endpoint (Endpoint) – The root endpoint to register.
  • logger (Logger) – An optional logger instance to use when displaying debugging information.

Examples

>>> import example_app.endpoints
>>> import falcon
>>> import req.helpers.falcon
>>> app = falcon.API()
>>> req.helpers.falcon.register(app, example_app.endpoints.V1)

Decorators

req.falcon.decorators.exposespec(handler)[source]

Monkey-patches an on_options handler method onto the given request handler that returns the handler’s spec in JSON format.

This decorator expects the given handler to have a __spec__ attribute that points to its Endpoint. This is usually injected during handler instantiation.

Examples

>>> from req import Endpoint
>>> @exposespec
... class SomeHandler(object):
...   pass
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
>>> for endpoint in SomeEndpoint.flatten():
...   if endpoint.handler is not None:
...     path = repr(endpoint.full_uri)
...     handler = endpoint.handler_class()
...     handler.__spec__ = endpoint
...     app.add_route(path, handler)
$ curl -XOPTIONS "http://api/some-endpoint"
{"spec": {...}}
Parameters:handler (class) – The handler class to decorate.
Returns:The decorated class.
Return type:class
req.falcon.decorators.jsonrequest(method)[source]

Wraps method in a function that handles input validation based on its handler’s spec. On success, it injects two keys into the request object’s context:

  • json represents the parsed json object.
  • request represents an instance of the Schema that was populated with the request data.

This should be used in conjunction with jsonresponse().

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(object):
...   @jsonresponse
...   @jsonrequest
...   def on_post(self, req, resp):
...     request_data = req.context["request"]
...     return {"x": request_data.n}
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/"
...   handler = SomeHandler
...
...   class POST(Method):
...     class Request(schema.Schema):
...       n = schema.Number()
...
...     class Response(schema.Schema):
...       x = schema.Number()
$ curl -XPOST \
    -H"Content-type: application/json" \
    -d"{\"n\": 42}" \
    "http://api/some-handler/"
{"x": 42}
Raises:HTTPError – When a validation error is encountered.
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.falcon.decorators.jsonresponse(method)[source]

Wraps method in a function that will convert the value that method returns to a JSON response. Wrapped handlers are free to raise HTTPErrors, those are captured and a standard error response format is generated and written to the response.

Examples

>>> from falcon import HTTPError, HTTP_404
>>> class SomeHandler(object):
...   @jsonresponse
...   def on_get(self, req, resp):
...     return {"n": 42}
>>> class FailingHandler(object):
...   @jsonresponse
...   def on_get(self, req, resp):
...     raise HTTPError(HTTP_404, description="not found")
$ curl -XGET "http://api/some-handler/"
{"n": 42}

$ curl -XGET "http://api/failing-handler/"
{"errors": ["not found"]}
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.falcon.decorators.jsonhandler(method)[source]

A convenience decorator that combines jsonrequest() and jsonresponse().

This:

>>> class SomeHandler(object):
...   @jsonhandler
...   def on_post(self, req, resp):
...     return {}

Is equivalent to:

>>> class SomeHandler(object):
...   @jsonresponse
...   @jsonrequest
...   def on_post(self, req, resp):
...     return {}
Parameters:method (callable) – The method to decorate.
Returns:The decorated method.
Return type:callable
req.falcon.decorators.queryrequest(method)[source]

Wraps method in a function that handles query string validation according to its handler’s spec. On success, it injects a single key into the request object’s context:

  • query represents an instance of the Schema that was populated with the request data.

This should be used in conjunction with jsonresponse().

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(object):
...   @jsonresponse
...   @queryrequest
...   def on_post(self, req, resp):
...     n = float(req.get_param("n"))
...     return {"n": n}
>>> class Some(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/"
...   handler = SomeHandler
...
...   class POST(Method):
...     class QueryString(schema.Schema):
...       n = schema.Regexp("\d+")
$ curl -XGET "http://api/some-handler/"
{"errors": ["n: missing"]}

$ curl -XGET "http://api/some-handler/?n=abc"
{"errors": ["n: must match regexp '\\d+'"]}

$ curl -XGET "http://api/some-handler/?n=1"
{"n": 1.0}
Raises:HTTPError – When a validation error is encountered.
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.falcon.decorators.entityrequest(method)[source]

Applies jsonrequest() to method and builds an entity that it then stores on the request context on success.

Note

This expects the validator to have a to_entity method that takes a dict representing the parsed JSON data and returns a new instance of an entity. The instance on which to_entity is called will always be prepopulated with the input data so the dict parameter is there for advanced use cases, it can be safely ignored most of the time.

Examples

>>> from collections import namedtuple
>>> from req import Endpoint, Method, schema
>>> NumberWrapper = namedtuple("NumberWrapper", "value")
>>> class SomeHandler(object):
...   @entityresponse
...   @entityrequest
...   def on_post(self, req, resp):
...     entity = req.context["entity"]
...     assert isinstance(entity, NumberWrapper)
...     return entity
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
...
...   class POST(Method):
...     class Request(schema.Schema):
...       n = schema.Number()
...
...       def to_entity(self, json_data):
...         return NumberWrapper(self.n)
...
...     class Response(schema.Schema):
...       n = schema.Number()
...
...       def from_entity(self, entity):
...         self.n = entity.value
$ curl -XPOST \
    -H"Content-type: application/json" \
    -d"{\"n\": 42}" \
    "http://api/some-handler/"
{"n": 42}
Raises:HTTPError – When the validator’s to_entity method failed with a ValidationError.
Parameters:method (callable) – A handler method.
Returns:The decorated handler method.
Return type:callable
req.falcon.decorators.entityresponse(method)[source]

Uses the method’s schema validator to build a response value that it then passes to jsonresponse().

Note

This expects the validator to have a from_entity method that takes an entity instance and returns a dict.

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(object):
...   @entityresponse
...   def on_get(self, req, resp, uuid):
...     return SomeModel.get(uuid)
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/{uuid}"
...   handler = SomeHandler
...
...   class GET(Method):
...     class Response(schema.Schema):
...       n = schema.Number()
...
...       def from_entity(self, entity):
...         self.n = entity.value
$ curl -XGET "http://api/some-handler/"
{"n": ...}
Parameters:method (callable) – A handler method.
Returns:The decorated handler method.
Return type:callable
req.falcon.decorators.entityhandler(method)[source]

A convenience decorator that combines entityrequest() and entityresponse().

This:

>>> class SomeHandler(object):
...   @entityhandler
...   def on_post(self, req, resp):
...     return {}

Is equivalent to:

>>> class SomeHandler(object):
...   @entityresponse
...   @entityrequest
...   def on_post(self, req, resp):
...     return {}
Parameters:method (callable) – The method to decorate.
Returns:The decorated method.
Return type:callable
req.falcon.decorators.listingrequest(default_limit=20, max_limit=50)[source]

Applies queryrequest() to method, validating the request’s query string and injecting limit and cursor arguments into the wrapped method.

Note

This assumes that the validator for the wrapped method implements the following properties:

class ListingRequest(schema.Schema):
  limit = schema.Regexp("\d+", _optional=True)
  cursor = schema.String(_optional=True)

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(object):
...   @listingresponse
...   @listingrequest(default_limit=5, max_limit=100)
...   def on_get(self, req, resp, limit, cursor):
...     return []
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
...
...   class GET(Method):
...     QueryString = ListingRequest
$ curl -XGET "http://api/some-handler/?limit=10"
{"_meta": {..., "limit": 10, ...}, "_items": []}
Parameters:
  • default_limit (int) – This is the limit that gets passed in if one wasn’t sent with the HTTP request.
  • max_limit (int) – The max limit that the request will allow.
Returns:

A decorator.

Return type:

callable

req.falcon.decorators.listingresponse(method)[source]

Uses the method’s schema validator to build a response containing a list of entities that it then passes to jsonresponse().

Note

This expects the validator to have a from_resultset method that takes an object representing a set of results and updates itself to represent that resultset.

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(object):
...   @listingresponse
...   def on_get(self, req, resp):
...     return [1, 2]
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
...
...   class GET(Method):
...     class Response(schema.Schema):
...         items = schema.List(schema.Integer(), _name="_items")
...
...       def from_resultset(self, resultset):
...         self.items = resultset
$ curl -XGET "http://api/some-handler/"
{"_items": [1, 2]}
Parameters:method (callable) – A handler method.
Returns:The decorated handler method.
Return type:callable
req.falcon.decorators.listinghandler(default_limit=20, max_limit=50)[source]

A convenience decorator that combines listingrequest() and listingresponse().

This:

>>> class SomeHandler(object):
...   @listinghandler(default_limit=30)
...   def on_post(self, req, resp):
...     return {}

Is equivalent to:

>>> class SomeHandler(object):
...   @listingresponse
...   @listingrequest(default_limit=30)
...   def on_post(self, req, resp):
...     return {}
Parameters:
  • default_limit (int) – This is the limit that gets passed in if one wasn’t sent with the HTTP request.
  • max_limit (int) – The max limit that the request will allow.
Returns:

A decorator.

Return type:

callable

Webapp2 Integration

req.webapp2.register(app, endpoint, logger=None)[source]

Register endpoint and all its children with the given webapp2 application.

Raises:

TypeError – When app is not a webapp2.WSGIApplication instance.

Parameters:
  • app (webapp2.WSGIApplication) – The application with which to register the endpoints.
  • endpoint (Endpoint) – The root endpoint to register.
  • logger (Logger) – An optional logger instance to use when displaying debugging information.

Examples

>>> import example_app.endpoints
>>> import webapp2
>>> import req.webapp2
>>> app = webapp2.WSGIApplication()
>>> req.webapp2.register(app, example_app.endpoints.V1)

Decorators

req.webapp2.decorators.exposespec(handler)[source]

Monkey-patches an options handler method onto the given request handler that returns the handler’s spec in JSON format.

This decorator expects the given handler to have a __spec__ attribute that points to its Endpoint. This is usually injected during handler instantiation.

Examples

>>> import webapp2
>>> from req import Endpoint
>>> from req.webapp2 import register
>>> @exposespec
... class SomeHandler(webapp2.RequestHandler):
...   pass
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
>>> app = webapp2.WSGIApplication()
>>> register(app, SomeEndpoint)
$ curl -XOPTIONS "http://api/some-endpoint"
{"spec": {...}}
Parameters:handler (class) – The handler class to decorate.
Returns:The decorated class.
Return type:class
req.webapp2.decorators.jsonrequest(method)[source]

Wraps method in a function that handles input validation based on its handler’s spec. On success, it injects two keys into the request object’s registry:

  • json represents the parsed json object.
  • request represents an instance of the Schema that was populated with the request data.

This should be used in conjunction with jsonresponse().

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(webapp2.RequestHandler):
...   @jsonresponse
...   @jsonrequest
...   def post(self):
...     request_data = self.request.registry["request"]
...     return {"x": request_data.n}
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/"
...   handler = SomeHandler
...
...   class POST(Method):
...     class Request(schema.Schema):
...       n = schema.Number()
...
...     class Response(schema.Schema):
...       x = schema.Number()
$ curl -XPOST \
    -H"Content-type: application/json" \
    -d"{\"n\": 42}" \
    "http://api/some-handler/"
{"x": 42}
Raises:HTTPException – When a validation error is encountered.
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.webapp2.decorators.jsonresponse(method)[source]

Wraps method in a function that will convert the value that method returns to a JSON response. Wrapped handlers are free to call self.abort(<status>, <message>), those are captured and a standard error response format is generated and written to the response.

Examples

>>> class SomeHandler(webapp2.RequestHandler):
...   @jsonresponse
...   def get(self):
...     return {"n": 42}
>>> class FailingHandler(webapp2.RequestHandler):
...   @jsonresponse
...   def get(self):
...     self.abort(404, "not found")
$ curl -XGET "http://api/some-handler/"
{"n": 42}

$ curl -XGET "http://api/failing-handler/"
{"errors": ["not found"]}
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.webapp2.decorators.jsonhandler(method)[source]

A convenience decorator that combines jsonrequest() and jsonresponse().

This:

>>> class SomeHandler(webapp2.RequestHandler):
...   @jsonhandler
...   def post(self):
...     return {}

Is equivalent to:

>>> class SomeHandler(webapp2.RequestHandler):
...   @jsonresponse
...   @jsonrequest
...   def post(self):
...     return {}
Parameters:method (callable) – The method to decorate.
Returns:The decorated method.
Return type:callable
req.webapp2.decorators.queryrequest(method)[source]

Wraps method in a function that handles query string validation according to its handler’s spec. On success, it injects a single key into the request object’s registry:

  • query represents an instance of the Schema that was populated with the request data.

This should be used in conjunction with jsonresponse().

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(webapp2.RequestHandler):
...   @jsonresponse
...   @queryrequest
...   def post(self):
...     n = self.request.registry["query"].n
...     return {"n": n}
>>> class Some(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/"
...   handler = SomeHandler
...
...   class POST(Method):
...     class QueryString(schema.Schema):
...       n = schema.Regexp("\d+")
$ curl -XGET "http://api/some-handler/"
{"errors": ["n: missing"]}

$ curl -XGET "http://api/some-handler/?n=abc"
{"errors": ["n: must match regexp '\\d+'"]}

$ curl -XGET "http://api/some-handler/?n=1"
{"n": 1.0}
Raises:HTTPException – When a validation error is encountered.
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.webapp2.decorators.entityrequest(method)[source]

Applies jsonrequest() to method and builds an entity that it then stores on the request context on success.

Note

This expects the validator to have a to_entity method that takes a dict representing the parsed JSON data and returns a new instance of an entity. The instance on which to_entity is called will always be prepopulated with the input data so the dict parameter is there for advanced use cases, it can be safely ignored most of the time.

Examples

>>> from collections import namedtuple
>>> from req import Endpoint, Method, schema
>>> NumberWrapper = namedtuple("NumberWrapper", "value")
>>> class SomeHandler(webapp2.RequestHandler):
...   @entityresponse
...   @entityrequest
...   def post(self):
...     entity = self.request.registry["entity"]
...     assert isinstance(entity, NumberWrapper)
...     return entity
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
...
...   class POST(Method):
...     class Request(schema.Schema):
...       n = schema.Number()
...
...       def to_entity(self):
...         return NumberWrapper(self.n)
...
...     class Response(schema.Schema):
...       n = schema.Number()
...
...       def from_entity(self, entity):
...         self.n = entity.value
$ curl -XPOST \
    -H"Content-type: application/json" \
    -d"{\"n\": 42}" \
    "http://api/some-handler/"
{"n": 42}
Raises:HTTPException – When the validator’s to_entity method failed with a ValidationError.
Parameters:method (callable) – A handler method.
Returns:The decorated handler method.
Return type:callable
req.webapp2.decorators.entityresponse(method)[source]

Uses the method’s schema validator to build a response value that it then passes to jsonresponse().

Note

This expects the validator to have a from_entity method that takes an entity instance and returns a dict.

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(webapp2.RequestHandler):
...   @entityresponse
...   def get(self, uuid):
...     return SomeModel.get(uuid)
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/{uuid}"
...   handler = SomeHandler
...
...   class GET(Method):
...     class Response(schema.Schema):
...       n = schema.Number()
...
...       def from_entity(self, entity):
...         self.n = entity.value
$ curl -XGET "http://api/some-handler/"
{"n": ...}
Parameters:method (callable) – A handler method.
Returns:The decorated handler method.
Return type:callable
req.webapp2.decorators.entityhandler(method)[source]

A convenience decorator that combines entityrequest() and entityresponse().

This:

>>> class SomeHandler(webapp2.RequestHandler):
...   @entityresponse
...   @entityrequest
...   def post(self):
...     return {}

Is equivalent to:

>>> class SomeHandler(webapp2.RequestHandler):
...   @entityhandler
...   def post(self):
...     return {}
Parameters:method (callable) – The method to decorate.
Returns:The decorated method.
Return type:callable
req.webapp2.decorators.listingrequest(default_limit=20, max_limit=50)[source]

Applies queryrequest() to method, validating the request’s query string and injecting limit and cursor arguments into the wrapped method.

Note

This assumes that the validator for the wrapped method implements the following properties:

class ListingRequest(schema.Schema):
  limit = schema.Regexp("\d+", _optional=True)
  cursor = schema.String(_optional=True)

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(webapp2.RequestHandler):
...   @listingresponse
...   @listingrequest(default_limit=5, max_limit=100)
...   def get(self, limit, cursor):
...     return []
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
...
...   class GET(Method):
...     QueryString = ListingRequest
$ curl -XGET "http://api/some-handler/?limit=10"
{"_meta": {..., "limit": 10, ...}, "_items": []}
Parameters:
  • default_limit (int) – This is the limit that gets passed in if one wasn’t sent with the HTTP request.
  • max_limit (int) – The max limit that the request will allow.
Returns:

A decorator.

Return type:

callable

req.webapp2.decorators.listingresponse(method)[source]

Uses the method’s schema validator to build a response containing a list of entities that it then passes to jsonresponse().

Note

This expects the validator to have a from_resultset method that takes an object representing a set of results and updates itself to represent that resultset.

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(webapp2.RequestHandler):
...   @listingresponse
...   def get(self):
...     return [1, 2]
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
...
...   class GET(Method):
...     class Response(schema.Schema):
...         items = schema.List(schema.Integer(), _name="_items")
...
...       def from_resultset(self, resultset):
...         self.items = resultset
$ curl -XGET "http://api/some-handler/"
{"_items": [1, 2]}
Parameters:method (callable) – A handler method.
Returns:The decorated handler method.
Return type:callable
req.webapp2.decorators.listinghandler(default_limit=20, max_limit=50)[source]

A convenience decorator that combines listingrequest() and listingresponse().

This:

>>> class SomeHandler(webapp2.RequestHandler):
...   @listinghandler(default_limit=30)
...   def post(self, limit, cursor):
...     return {}

Is equivalent to:

>>> class SomeHandler(webapp2.RequestHandler):
...   @listingresponse
...   @listingrequest(default_limit=30)
...   def post(self, limit, cursor):
...     return {}
Parameters:
  • default_limit (int) – This is the limit that gets passed in if one wasn’t sent with the HTTP request.
  • max_limit (int) – The max limit that the request will allow.
Returns:

A decorator.

Return type:

callable

Wask Integration

req.wask.register(app, endpoint, logger=None)[source]

Register endpoint and all its children with the given Flask application using the wask adapter library.

Raises:

TypeError – When app is not a flask.Flask instance.

Parameters:
  • app (flask.Flask) – The application with which to register the endpoints.
  • endpoint (Endpoint) – The root endpoint to register.
  • logger (Logger) – An optional logger instance to use when displaying debugging information.

Examples

>>> import example_app.endpoints
>>> from flask import Flask
>>> import req.wask
>>> app = Flask(__name__)
>>> req.wask.register(app, example_app.endpoints.V1)

Decorators

req.wask.decorators.exposespec(handler)[source]

Monkey-patches an options handler method onto the given request handler that returns the handler’s spec in JSON format.

This decorator expects the given handler to have a __spec__ attribute that points to its Endpoint. This is usually injected during handler instantiation.

Examples

>>> from flask import Flask
>>> from wask.adapters import WaskMethodView
>>> from req import Endpoint
>>> from req.wask import register
>>> @exposespec
... class SomeHandler(WaskMethodView):
...   pass
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint"
...   handler = SomeHandler
>>> app = Flask(__name__)
>>> register(app, SomeEndpoint)
$ curl -XOPTIONS "http://api/some-endpoint"
{"spec": {...}}
Parameters:handler (class) – The handler class to decorate.
Returns:The decorated class.
Return type:class
req.wask.decorators.jsonrequest(method)[source]

Wraps method in a function that handles input validation based on its handler’s spec. On success, it injects two keys into the request object’s registry:

  • json represents the parsed json object.
  • request represents an instance of the Schema that was populated with the request data.

This should be used in conjunction with jsonresponse().

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(wask.adapters.WaskMethodView):
...   @jsonresponse
...   @jsonrequest
...   def post(self):
...     request_data = self.request.registry["request"]
...     return {"x": request_data.n}
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/"
...   handler = SomeHandler
...
...   class POST(Method):
...     class Request(schema.Schema):
...       n = schema.Number()
...
...     class Response(schema.Schema):
...       x = schema.Number()
$ curl -XPOST \
    -H"Content-type: application/json" \
    -d"{\"n\": 42}" \
    "http://api/some-handler/"
{"x": 42}
Raises:HTTPException – When a validation error is encountered.
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.wask.decorators.jsonresponse(method)[source]

Wraps method in a function that will convert the value that method returns to a JSON response. Wrapped handlers are free to call self.abort(<status>, <message>), those are captured and a standard error response format is generated and written to the response.

Examples

>>> class SomeHandler(wask.adapters.WaskMethodView):
...   @jsonresponse
...   def get(self):
...     return {"n": 42}
>>> class FailingHandler(wask.adapters.WaskMethodView):
...   @jsonresponse
...   def get(self):
...     self.abort(404, "not found")
$ curl -XGET "http://api/some-handler/"
{"n": 42}

$ curl -XGET "http://api/failing-handler/"
{"errors": ["not found"]}
Parameters:method (callable) – A handler method.
Returns:A decorated handler method.
Return type:callable
req.wask.decorators.jsonhandler(method)[source]

A convenience decorator that combines jsonrequest() and jsonresponse().

This:

>>> class SomeHandler(wask.adapters.WaskMethodView):
...   @jsonhandler
...   def post(self):
...     return {}

Is equivalent to:

>>> class SomeHandler(wask.adapters.WaskMethodView):
...   @jsonresponse
...   @jsonrequest
...   def post(self):
...     return {}
Parameters:method (callable) – The method to decorate.
Returns:The decorated method.
Return type:callable
req.wask.decorators.entityresponse(method)[source]

Uses the method’s schema validator to build a response value that it then passes to jsonresponse().

Note

This expects the validator to have a from_entity method that takes an entity instance and returns a dict.

Examples

>>> from req import Endpoint, Method, schema
>>> class SomeHandler(wask.adapters.WaskMethodView):
...   @entityresponse
...   def get(self, uuid):
...     return SomeModel.get(uuid)
>>> class SomeEndpoint(Endpoint):
...   name = "some_endpoint"
...   path = "/some-endpoint/{uuid}"
...   handler = SomeHandler
...
...   class GET(Method):
...     class Response(schema.Schema):
...       n = schema.Number()
...
...       def from_entity(self, entity):
...         self.n = entity.value
$ curl -XGET "http://api/some-handler/"
{"n": ...}
Parameters:method (callable) – A handler method.
Returns:The decorated handler method.
Return type:callable