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:
-
envs¶ The environments in which this Endpoint must be available. Defaults to
().Type: str tuple
-
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:
-
children¶ A list of this Endpoint’s children.
Type: Endpoint list
-
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:
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.Endpointadapters. Endpoint adapters translate endpoint definitions from code to any other representation.
-
class
req.adapter.DictionaryAdapter(schema_adapter)[source]¶ Adapts an
endpoint.Endpointto adict.Parameters: schema_adapter (Adapter) – The Adapter to apply to schemas.
-
class
req.adapter.SwaggerAdapter(host, base_path, title, description, version, schemes=('https', ), security_definitions=None, security=None)[source]¶ Adapts an
endpoint.Endpointto 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.
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.
-
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
-
class
req.schema.Schema(_optional=False, _description=None, **properties)[source]¶ Bases:
req.schema.schema.SchemaLikeSchema 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
Schemainto 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
dataagainst thisSchemaand 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
-
class
req.schema.Property(_name=None, _description=None, _optional=None)[source]¶ Bases:
req.schema.schema.SchemaLikeBase 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.
-
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
-
req.schema.Alternative(*schemas)[source]¶ Unifies a list of
Schemasubclasses into one, selecting the most appropriate one on each call toSchemaLike.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 Schemaclasses.Returns: A Schemarepresenting 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
Numberbut 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:
-
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 datetimecompatible format to use when rendering this property.
-
class
req.schema.Email(_name=None, _description=None, _optional=None)[source]¶ Like
Stringbut 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
Stringbut 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
Stringbut 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
IPv4but 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
Dictionaryvariant that validates all values against the specifiedSchemaLike.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
Lazyis 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
schemawithin 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
schemacannot be found at runtime. - TypeError – When the object referenced by
schemais not a subclass ofSchemaLike. This error is raised at runtime.
Parameters: Returns: A proxy that will lazily instantiate the referenced schema on its first use.
Return type: - RuntimeError – When the object referenced by
Exceptions¶
-
exception
req.schema.ValidationError(message)[source]¶ Raised by
SchemaLikeswhenever some data fails to validate.-
message¶ One or more error messages.
Type: str|str list
-
Falcon Integration¶
-
req.falcon.register(app, endpoint, logger=None)[source]¶ Register
endpointand all its children with the given Falcon application.Raises: TypeError – When
appis 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
handlerto have a__spec__attribute that points to itsEndpoint. 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:jsonrepresents the parsed json object.requestrepresents 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()andjsonresponse().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:queryrepresents 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()tomethodand builds an entity that it then stores on the request context on success.Note
This expects the validator to have a
to_entitymethod that takes adictrepresenting the parsed JSON data and returns a new instance of an entity. The instance on whichto_entityis 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_entitymethod failed with aValidationError.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_entitymethod that takes an entity instance and returns adict.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()andentityresponse().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()tomethod, validating the request’s query string and injectinglimitandcursorarguments 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: 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_resultsetmethod 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()andlistingresponse().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: Returns: A decorator.
Return type: callable
Webapp2 Integration¶
-
req.webapp2.register(app, endpoint, logger=None)[source]¶ Register
endpointand all its children with the given webapp2 application.Raises: TypeError – When
appis 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
handlerto have a__spec__attribute that points to itsEndpoint. 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:jsonrepresents the parsed json object.requestrepresents 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()andjsonresponse().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:queryrepresents 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()tomethodand builds an entity that it then stores on the request context on success.Note
This expects the validator to have a
to_entitymethod that takes adictrepresenting the parsed JSON data and returns a new instance of an entity. The instance on whichto_entityis 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_entitymethod failed with aValidationError.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_entitymethod that takes an entity instance and returns adict.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()andentityresponse().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()tomethod, validating the request’s query string and injectinglimitandcursorarguments 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: 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_resultsetmethod 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()andlistingresponse().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: Returns: A decorator.
Return type: callable
Wask Integration¶
-
req.wask.register(app, endpoint, logger=None)[source]¶ Register
endpointand all its children with the given Flask application using the wask adapter library.Raises: TypeError – When
appis 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
handlerto have a__spec__attribute that points to itsEndpoint. 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:jsonrepresents the parsed json object.requestrepresents 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()andjsonresponse().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_entitymethod that takes an entity instance and returns adict.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