Welcome to Spectastic’s documentation!¶
Contents:
Spectastic¶
Request and response validation via Open API/Swagger schemas.
- Free software: Apache 2 License
- Documentation: https://spectastic.readthedocs.org.
Features¶
- Validation of Request-like objects against Open API/Swagger schemas.
TODO¶
- Response validation.
- Query parameter validation.
- collectionformat support that ties into werkzeug’s datastructures.
- Authorization support not baked in.
Installation¶
At the command line:
$ easy_install spectastic
Or, if you have virtualenvwrapper installed:
$ mkvirtualenv spectastic
$ pip install spectastic
Basic Usage¶
To use Spectastic in a project:
import spectastic
First, it’s important to know that spectastic assumes that it’s working with a valid Open API / Swagger schema to reduce it’s dependency footprint. If you need to validate your schema, consider bravado-core.
Warning
You’ll want to make sure you’ve specified operation id's
for all paths.
These aren’t mandatory in an Open API specification, but are mandatory for
spectastic.
Validating Incoming Requests¶
Spectastic offers two strategies for validation:
- Iterative API’s that yield individual
FieldError
instances. ValidationErrors
raising methods.
Most of spectastic’s utility is contained within
Operation
instances. Lets make one using our
test schema:
from spectastic.schema import Schema
from spectastic import Operation
schema = Spec(SPEC)
op = Operation.from_schema(schema, 'GetItem')
Once instantiated, you can validate an incoming
BasicRequest
:
op.validate_request(request)
Note
BasicRequest
is probably not what you’re using
in your app. If you’re using flask, check out
convert_request()
to make the
conversion.
If there are validation errors, we’ll raise a ValidationErrors
exception, which contains an errors
property consisting of a list of
FieldError
:
from spectastic.request import BasicRequest
request = BasicRequest(
{"hello": "world"},
{"Authorization": "basic beefbabaabbabeef"},
{"query": "created:yesterday"},
"/things/are/great",
)
try:
op.validate_request(request)
except ValidationErrors as e:
print e.errors[0].field
Note
Though it works out of the box, strictly speaking the request doesn’t need
to be a werkzeug Request. See BasicRequest
for
an example.
Spectastic is MultiDict
and
Headers
aware. These data structures
facilitate query parameters / headers that occur multiple times in a request
e.g. a query such as “http://example.com?search=foo&search=bar”.
Flask Integration¶
Spectastic’s flask_utils
module has some additional
tools to automatically validate incoming requests for a given route against
your schema:
from spectastic.contrib.flask_utils import validate_route
...
@validate_route(schema, 'GetItems')
@app.route('/items/')
def get_items(*args, **kwargs):
return 'Success'
The validate_route()
function has a few
bonuses. The first argument may be a Schema
instance or a callable that returns a Schema. An optional responder
callable receives any ValidationErrors
that may
have occured and returns an appropriate flask-compatible response. You can use
this to customize your error output.
The default_responder()
simply outputs
the general structure shown below along with a 400 status code:
{
"errors": [
{
"msg": "Required path parameter is missing",
"location": "path",
"field": "query",
},
{
...
}
]
}
Spectastic API¶
Submodules¶
Errors¶
Operation¶
-
exception
spectastic.operation.
InvalidPath
[source]¶ Bases:
exceptions.Exception
Raised when a path does not match an operation’s route.
-
class
spectastic.operation.
Operation
(schema, route, method, local_schema)[source]¶ Bases:
object
Parameters: -
body_schema
()[source]¶ Returns a tuple of consisting of the body parameter and it’s corresponding body schema.
-
extract_path_args
(path)[source]¶ Matches a request path against this operation’s route, returning an intermediate dictionary of strings for each path parameter. The resulting dictionary is not validated nor are it’s types coerced.
Return dict: A dictionary of path arguments, with keys corresponding to the case sensitive name specified in the swagger schema.
-
header_schema
(header_name)[source]¶ Returns the schema for a header parameter of a given name. The parameter name is case-insensitive.
Raises: KeyError
If the header is not found.
-
iter_request_body_errors
(request_body)[source]¶ Validates a request body against the schema, yielding a
FieldError
for each failure.
-
iter_request_errors
(request)[source]¶ Validates an entire request, yielding a
FieldError
for each failure.Parameters: request (BasicRequest) – A request conforming to the structure outlined in BasicRequest
-
iter_request_header_errors
(request_headers)[source]¶ Validates individual request headers against the schema, yielding a
FieldError
for each failure.
-
iter_request_path_errors
(request_path)[source]¶ Validates a request path against the schema, yielding a
FieldError
for each failure.
-
iter_request_query_errors
(query_params)[source]¶ Validates a request query against the schema, yielding a
FieldError
for each failure.
-
path_schema
(path_param_name)[source]¶ Returns the schema for a path parameter of a given name. The parameter name is case-insensitive.
Raises: KeyError
If the query is not found.
-
query_schema
(query_param_name)[source]¶ Returns the schema for a query parameter of a given name. The parameter name is case-insensitive.
Raises: KeyError
If the query is not found.
-
validate_request
(request)[source]¶ Validates all components of a request.
Parameters: request – A request conforming to the structure outlined in BasicRequest
Raises: ValidationErrors
When validation fails.Return bool: True on success.
-
validate_request_body
(request_body)[source]¶ Validates a request body against the operation schema.
Raises: ValidationErrors
When validation fails.Return bool: True on success.
-
validate_request_headers
(headers)[source]¶ Validates headers against the operation.
Raises: ValidationErrors
When validation fails.Return bool: True on success.
-
validate_request_path
(path_arguments)[source]¶ Validates headers against the operation.
Raises: ValidationErrors
When validation fails.Return bool: True on success.
-
validate_request_query
(query_params)[source]¶ Validates the query parameters from a request.
Parameters: query_params (dict|werkzeug.datastructures.MultiDict) – A dictionary like object of query parameters. Raises: ValidationErrors
When validation fails.Return bool: True on success.
-
validator
¶
-
-
exception
spectastic.operation.
OperationNotFound
[source]¶ Bases:
exceptions.Exception
Raised when an operation cannot be found in a schema.
-
spectastic.operation.
coerce_param
(value, schema)[source]¶ Coerces a named parameter within a path, query, or headers to the type specified in the appropriate schema. If the string is not properly formated, raise a FieldError.
Parameters: Raises: FieldError
When the primitive type is not coercible.Returns: The value, coerced according to the parameter definition for the field named
name
located inlocation
.
-
spectastic.operation.
find_operation
(schema, operation_id)[source]¶ Returns a tuple of the route, method and schema for an operation.
Raises: OperationNotFound
When the operation_id does not exist anywhere in the sec.
Schema¶
-
class
spectastic.schema.
Schema
(schema_dict)[source]¶ Bases:
dict
Simple wrapper around Swagger / Open API schema’s. At some ‘semblance’ of type safety. Mostly used to resolve all references with the provided schema to make spectastic’s job easier.
Request¶
Flask Utilities¶
-
spectastic.contrib.flask_utils.
convert_request
(flask_request)[source]¶ Converts a flask
flask.Request
to aBasicRequest
Returns: BasicRequest
-
spectastic.contrib.flask_utils.
default_responder
(validation_errors)[source]¶ Generates a flask response from provided
validation_errors
.Parameters: validation_errors (ValidationErrors) – A instance containing an aggregate of all errors discovered during request parsing.
Module contents¶
Credits¶
Development Lead¶
- Jacob Straszynski <jacob.straszynski@planet.com>
Contributors¶
None yet. Why not be the first?
History¶
0.2.2 (2016-03-24)¶
- Addressed an issue when validating objects with more than one required field.