API¶
Core¶
-
class
flask_restplus.
Api
(app=None, version=u'1.0', title=None, description=None, terms_url=None, license=None, license_url=None, contact=None, contact_url=None, contact_email=None, authorizations=None, security=None, doc=u'/', default_id=<function default_id>, default=u'default', default_label=u'Default namespace', validate=None, tags=None, prefix=u'', ordered=False, default_mediatype=u'application/json', decorators=None, catch_all_404s=False, serve_challenge_on_401=False, format_checker=None, **kwargs)[source]¶ The main entry point for the application. You need to initialize it with a Flask Application:
>>> app = Flask(__name__) >>> api = Api(app)
Alternatively, you can use
init_app()
to set the Flask application after it has been constructed.The endpoint parameter prefix all views and resources:
- The API root/documentation will be
{endpoint}.root
- A resource registered as ‘resource’ will be available as
{endpoint}.resource
Parameters: - app (flask.Flask|flask.Blueprint) – the Flask application object or a Blueprint
- version (str) – The API version (used in Swagger documentation)
- title (str) – The API title (used in Swagger documentation)
- description (str) – The API description (used in Swagger documentation)
- terms_url (str) – The API terms page URL (used in Swagger documentation)
- contact (str) – A contact email for the API (used in Swagger documentation)
- license (str) – The license associated to the API (used in Swagger documentation)
- license_url (str) – The license page URL (used in Swagger documentation)
- endpoint (str) – The API base endpoint (default to ‘api).
- default (str) – The default namespace base name (default to ‘default’)
- default_label (str) – The default namespace label (used in Swagger documentation)
- default_mediatype (str) – The default media type to return
- validate (bool) – Whether or not the API should perform input payload validation.
- ordered (bool) – Whether or not preserve order models and marshalling.
- doc (str) – The documentation path. If set to a false value, documentation is disabled. (Default to ‘/’)
- decorators (list) – Decorators to attach to every resource
- catch_all_404s (bool) – Use
handle_error()
to handle 404 errors throughout your app - authorizations (dict) – A Swagger Authorizations declaration as dictionary
- serve_challenge_on_401 (bool) – Serve basic authentication challenge with 401 responses (default ‘False’)
- format_checker (FormatChecker) – A jsonschema.FormatChecker object that is hooked into the Model validator. A default or a custom FormatChecker can be provided (e.g., with custom checkers), otherwise the default action is to not enforce any format validation.
-
add_namespace
(ns, path=None)[source]¶ This method registers resources from namespace for current instance of api. You can use argument path for definition custom prefix url for namespace.
Parameters: - ns (Namespace) – the namespace
- path – registration prefix of namespace
-
as_postman
(urlvars=False, swagger=False)[source]¶ Serialize the API as Postman collection (v1)
Parameters:
-
default_endpoint
(resource, namespace)[source]¶ Provide a default endpoint for a resource on a given namespace.
Endpoints are ensured not to collide.
Override this method specify a custom algoryhtm for default endpoint.
Parameters: Returns str: An endpoint name
-
error_router
(original_handler, e)[source]¶ This function decides whether the error occured in a flask-restplus endpoint or not. If it happened in a flask-restplus endpoint, our handler will be dispatched. If it happened in an unrelated view, the app’s original error handler will be dispatched. In the event that the error occurred in a flask-restplus endpoint but the local handler can’t resolve the situation, the router will fall back onto the original_handler as last resort.
Parameters: - original_handler (function) – the original Flask error handler for the app
- e (Exception) – the exception raised while handling the request
-
handle_error
(e)[source]¶ Error handler for the API transforms a raised exception into a Flask response, with the appropriate HTTP status code and body.
Parameters: e (Exception) – the raised Exception object
-
init_app
(app, **kwargs)[source]¶ Allow to lazy register the API on a Flask application:
>>> app = Flask(__name__) >>> api = Api() >>> api.init_app(app)
Parameters: - app (flask.Flask) – the Flask application object
- title (str) – The API title (used in Swagger documentation)
- description (str) – The API description (used in Swagger documentation)
- terms_url (str) – The API terms page URL (used in Swagger documentation)
- contact (str) – A contact email for the API (used in Swagger documentation)
- license (str) – The license associated to the API (used in Swagger documentation)
- license_url (str) – The license page URL (used in Swagger documentation)
-
make_response
(data, *args, **kwargs)[source]¶ Looks up the representation transformer for the requested media type, invoking the transformer to create a response object. This defaults to default_mediatype if no transformer is found for the requested mediatype. If default_mediatype is None, a 406 Not Acceptable response will be sent as per RFC 2616 section 14.1
Parameters: data – Python object containing response data to be transformed
-
namespace
(*args, **kwargs)[source]¶ A namespace factory.
Returns Namespace: a new namespace instance
-
output
(resource)[source]¶ Wraps a resource (as a flask view function), for cases where the resource does not directly return a response object
Parameters: resource – The resource as a flask view function
-
owns_endpoint
(endpoint)[source]¶ Tests if an endpoint name (not path) belongs to this Api. Takes into account the Blueprint name part of the endpoint name.
Parameters: endpoint (str) – The name of the endpoint being checked Returns: bool
-
payload
¶ Store the input payload in the current request context
-
representation
(mediatype)[source]¶ Allows additional representation transformers to be declared for the api. Transformers are functions that must be decorated with this method, passing the mediatype the transformer represents. Three arguments are passed to the transformer:
- The data to be represented in the response body
- The http status code
- A dictionary of headers
The transformer should convert the data appropriately for the mediatype and return a Flask response object.
Ex:
@api.representation('application/xml') def xml(data, code, headers): resp = make_response(convert_data_to_xml(data), code) resp.headers.extend(headers) return resp
Given a response, change it to ask for credentials
-
url_for
(resource, **values)[source]¶ Generates a URL to the given resource.
Works like
flask.url_for()
.
- The API root/documentation will be
-
class
flask_restplus.
Namespace
(name, description=None, path=None, decorators=None, validate=None, authorizations=None, ordered=False, **kwargs)[source]¶ Group resources together.
Namespace is to API what
flask.Blueprint
is forflask.Flask
.Parameters: - name (str) – The namespace name
- description (str) – An optionale short description
- path (str) – An optional prefix path. If not provided, prefix is
/+name
- decorators (list) – A list of decorators to apply to each resources
- validate (bool) – Whether or not to perform validation on this namespace
- ordered (bool) – Whether or not to preserve order on models and marshalling
- api (Api) – an optional API to attache to the namespace
-
add_resource
(resource, *urls, **kwargs)[source]¶ Register a Resource for a given API Namespace
Parameters: - resource (Resource) – the resource ro register
- urls (str) – one or more url routes to match for the resource, standard flask routing rules apply. Any url variables will be passed to the resource method as args.
- endpoint (str) – endpoint name (defaults to
Resource.__name__.lower()
Can be used to reference this route infields.Url
fields - resource_class_args (list|tuple) – args to be forwarded to the constructor of the resource.
- resource_class_kwargs (dict) – kwargs to be forwarded to the constructor of the resource.
Additional keyword arguments not specified above will be passed as-is to
flask.Flask.add_url_rule()
.Examples:
namespace.add_resource(HelloWorld, '/', '/hello') namespace.add_resource(Foo, '/foo', endpoint="foo") namespace.add_resource(FooSpecial, '/special/foo', endpoint="foo")
-
clone
(name, *specs)[source]¶ Clone a model (Duplicate all fields)
Parameters: - name (str) – the resulting model name
- specs – a list of models from which to clone the fields
See also
Model.clone()
-
doc
(shortcut=None, **kwargs)[source]¶ A decorator to add some api documentation to the decorated object
-
expect
(*inputs, **kwargs)[source]¶ A decorator to Specify the expected input model
Parameters: - inputs (ModelBase|Parse) – An expect model or request parser
- validate (bool) – whether to perform validation or not
-
extend
(name, parent, fields)[source]¶ Extend a model (Duplicate all fields)
Deprecated: since 0.9. Use clone()
instead
-
header
(name, description=None, **kwargs)[source]¶ A decorator to specify one of the expected headers
Parameters:
-
inherit
(name, *specs)[source]¶ Inherit a modal (use the Swagger composition pattern aka. allOf)
See also
Model.inherit()
-
marshal_list_with
(fields, **kwargs)[source]¶ A shortcut decorator for
marshal_with()
withas_list=True
-
marshal_with
(fields, as_list=False, code=<HTTPStatus.OK: 200>, description=None, **kwargs)[source]¶ A decorator specifying the fields to use for serialization.
Parameters:
-
param
(name, description=None, _in=u'query', **kwargs)[source]¶ A decorator to specify one of the expected parameters
Parameters:
-
payload
¶ Store the input payload in the current request context
-
response
(code, description, model=None, **kwargs)[source]¶ A decorator to specify one of the expected responses
Parameters:
-
vendor
(*args, **kwargs)[source]¶ A decorator to expose vendor extensions.
Extensions can be submitted as dict or kwargs. The
x-
prefix is optionnal and will be added if missing.See: http://swagger.io/specification/#specification-extensions-128
-
class
flask_restplus.
Resource
(api=None, *args, **kwargs)[source]¶ Represents an abstract RESTPlus resource.
Concrete resources should extend from this class and expose methods for each supported HTTP method. If a resource is invoked with an unsupported HTTP method, the API will return a response with status 405 Method Not Allowed. Otherwise the appropriate method is called and passed all arguments from the url rule used when adding the resource to an Api instance. See
add_resource()
for details.-
classmethod
as_view
(name, *class_args, **class_kwargs)¶ Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the
View
on each request and call thedispatch_request()
method on it.The arguments passed to
as_view()
are forwarded to the constructor of the class.
-
classmethod
Models¶
-
class
flask_restplus.
Model
(name, *args, **kwargs)[source]¶ A thin wrapper on fields dict to store API doc metadata. Can also be used for response marshalling.
Parameters:
All fields accept a required
boolean and a description
string in kwargs
.
-
class
flask_restplus.fields.
Raw
(default=None, attribute=None, title=None, description=None, required=None, readonly=None, example=None, mask=None, **kwargs)[source]¶ Raw provides a base field class from which others should extend. It applies no formatting by default, and should only be used in cases where data does not need to be formatted before being serialized. Fields should throw a
MarshallingError
in case of parsing problem.Parameters: - default – The default value for the field, if no value is specified.
- attribute – If the public facing value differs from the internal value, use this to retrieve a different attribute from the response than the publicly named value.
- title (str) – The field title (for documentation purpose)
- description (str) – The field description (for documentation purpose)
- required (bool) – Is the field required ?
- readonly (bool) – Is the field read only ? (for documentation purpose)
- example – An optional data example (for documentation purpose)
- mask (callable) – An optional mask function to be applied to output
-
format
(value)[source]¶ Formats a field’s value. No-op by default - field classes that modify how the value of existing object keys should be presented should override this and apply the appropriate formatting.
Parameters: value – The value to format Raises: MarshallingError – In case of formatting problem Ex:
class TitleCase(Raw): def format(self, value): return unicode(value).title()
-
output
(key, obj, **kwargs)[source]¶ Pulls the value for the given key from the object, applies the field’s formatting and returns the result. If the key is not found in the object, returns the default value. Field classes that create values which do not require the existence of the key in the object should override this and return the desired value.
Raises: MarshallingError – In case of formatting problem
-
class
flask_restplus.fields.
String
(*args, **kwargs)[source]¶ Marshal a value as a string. Uses
six.text_type
so values will be converted tounicode
in python2 andstr
in python3.
-
class
flask_restplus.fields.
FormattedString
(src_str, **kwargs)[source]¶ FormattedString is used to interpolate other values from the response into this field. The syntax for the source string is the same as the string
format()
method from the python stdlib.Ex:
fields = { 'name': fields.String, 'greeting': fields.FormattedString("Hello {name}") } data = { 'name': 'Doug', } marshal(data, fields)
Parameters: src_str (str) – the string to format with the other values from the response.
-
class
flask_restplus.fields.
Url
(endpoint=None, absolute=False, scheme=None, **kwargs)[source]¶ A string representation of a Url
Parameters:
-
class
flask_restplus.fields.
DateTime
(dt_format=u'iso8601', **kwargs)[source]¶ Return a formatted datetime string in UTC. Supported formats are RFC 822 and ISO 8601.
See
email.utils.formatdate()
for more info on the RFC 822 format.See
datetime.datetime.isoformat()
for more info on the ISO 8601 format.Parameters: dt_format (str) – rfc822
oriso8601
-
class
flask_restplus.fields.
Date
(**kwargs)[source]¶ Return a formatted date string in UTC in ISO 8601.
See
datetime.date.isoformat()
for more info on the ISO 8601 format.
-
class
flask_restplus.fields.
Boolean
(default=None, attribute=None, title=None, description=None, required=None, readonly=None, example=None, mask=None, **kwargs)[source]¶ Field for outputting a boolean value.
Empty collections such as
""
,{}
,[]
, etc. will be converted toFalse
.
-
class
flask_restplus.fields.
Integer
(*args, **kwargs)[source]¶ Field for outputting an integer value.
Parameters: default (int) – The default value for the field, if no value is specified.
-
class
flask_restplus.fields.
Float
(*args, **kwargs)[source]¶ A double as IEEE-754 double precision.
ex : 3.141592653589793 3.1415926535897933e-06 3.141592653589793e+24 nan inf -inf
-
class
flask_restplus.fields.
Arbitrary
(*args, **kwargs)[source]¶ A floating point number with an arbitrary precision.
ex: 634271127864378216478362784632784678324.23432
-
class
flask_restplus.fields.
Fixed
(decimals=5, **kwargs)[source]¶ A decimal number with a fixed precision.
-
class
flask_restplus.fields.
Nested
(model, allow_null=False, skip_none=False, as_list=False, **kwargs)[source]¶ Allows you to nest one set of fields inside another. See Nested Field for more information
Parameters: - model (dict) – The model dictionary to nest
- allow_null (bool) – Whether to return None instead of a dictionary with null keys, if a nested dictionary has all-null keys
- skip_none (bool) – Optional key will be used to eliminate inner fields which value is None or the inner field’s key not exist in data
- kwargs – If
default
keyword argument is present, a nested dictionary will be marshaled as its value if nested dictionary is all-null keys (e.g. lets you return an empty JSON object instead of null)
-
class
flask_restplus.fields.
List
(cls_or_instance, **kwargs)[source]¶ Field for marshalling lists of other fields.
See List Field for more information.
Parameters: cls_or_instance – The field type the list will contain.
-
class
flask_restplus.fields.
ClassName
(dash=False, **kwargs)[source]¶ Return the serialized object class name as string.
Parameters: dash (bool) – If True, transform CamelCase to kebab_case.
-
class
flask_restplus.fields.
Polymorph
(mapping, required=False, **kwargs)[source]¶ A Nested field handling inheritance.
Allows you to specify a mapping between Python classes and fields specifications.
mapping = { Child1: child1_fields, Child2: child2_fields, } fields = api.model('Thing', { owner: fields.Polymorph(mapping) })
Parameters: mapping (dict) – Maps classes to their model/fields representation
Serialization¶
-
flask_restplus.
marshal
(data, fields, envelope=None, skip_none=False, mask=None, ordered=False)[source]¶ Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields.
Parameters: - data – the actual object(s) from which the fields are taken from
- fields – a dict of whose keys will make up the final serialized response output
- envelope – optional key that will be used to envelop the serialized response
- skip_none (bool) – optional key will be used to eliminate fields which value is None or the field’s key not exist in data
- ordered (bool) – Wether or not to preserve order
>>> from flask_restplus import fields, marshal >>> data = { 'a': 100, 'b': 'foo', 'c': None } >>> mfields = { 'a': fields.Raw, 'c': fields.Raw, 'd': fields.Raw }
>>> marshal(data, mfields) {'a': 100, 'c': None, 'd': None}
>>> marshal(data, mfields, envelope='data') {'data': {'a': 100, 'c': None, 'd': None}}
>>> marshal(data, mfields, skip_none=True) {'a': 100}
>>> marshal(data, mfields, ordered=True) OrderedDict([('a', 100), ('c', None), ('d', None)])
>>> marshal(data, mfields, envelope='data', ordered=True) OrderedDict([('data', OrderedDict([('a', 100), ('c', None), ('d', None)]))])
>>> marshal(data, mfields, skip_none=True, ordered=True) OrderedDict([('a', 100)])
-
flask_restplus.
marshal_with
(fields, envelope=None, skip_none=False, mask=None, ordered=False)[source]¶ A decorator that apply marshalling to the return values of your methods.
>>> from flask_restplus import fields, marshal_with >>> mfields = { 'a': fields.Raw } >>> @marshal_with(mfields) ... def get(): ... return { 'a': 100, 'b': 'foo' } ... ... >>> get() OrderedDict([('a', 100)])
>>> @marshal_with(mfields, envelope='data') ... def get(): ... return { 'a': 100, 'b': 'foo' } ... ... >>> get() OrderedDict([('data', OrderedDict([('a', 100)]))])
>>> mfields = { 'a': fields.Raw, 'c': fields.Raw, 'd': fields.Raw } >>> @marshal_with(mfields, skip_none=True) ... def get(): ... return { 'a': 100, 'b': 'foo', 'c': None } ... ... >>> get() OrderedDict([('a', 100)])
-
flask_restplus.
marshal_with_field
(field)[source]¶ A decorator that formats the return values of your methods with a single field.
>>> from flask_restplus import marshal_with_field, fields >>> @marshal_with_field(fields.List(fields.Integer)) ... def get(): ... return ['1', 2, 3.0] ... >>> get() [1, 2, 3]
-
class
flask_restplus.mask.
Mask
(mask=None, skip=False, **kwargs)[source]¶ Hold a parsed mask.
Parameters: - mask (str|dict|Mask) – A mask, parsed or not
- skip (bool) – If
True
, missing fields won’t appear in result
-
apply
(data)[source]¶ Apply a fields mask to the data.
Parameters: data – The data or model to apply mask on Raises: MaskError – when unable to apply the mask
-
parse
(mask)[source]¶ Parse a fields mask. Expect something in the form:
{field,nested{nested_field,another},last}
External brackets are optionals so it can also be written:
field,nested{nested_field,another},last
All extras characters will be ignored.
Parameters: mask (str) – the mask string to parse Raises: ParseError – when a mask is unparseable/invalid
-
flask_restplus.mask.
apply
(data, mask, skip=False)[source]¶ Apply a fields mask to the data.
Parameters: - data – The data or model to apply mask on
- mask (str|Mask) – the mask (parsed or not) to apply on data
- skip (bool) – If rue, missing field won’t appear in result
Raises: MaskError – when unable to apply the mask
Request parsing¶
-
class
flask_restplus.reqparse.
Argument
(name, default=None, dest=None, required=False, ignore=False, type=<function <lambda>>, location=(u'json', u'values'), choices=(), action=u'store', help=None, operators=(u'=', ), case_sensitive=True, store_missing=True, trim=False, nullable=True)[source]¶ Parameters: - name – Either a name or a list of option strings, e.g. foo or -f, –foo.
- default – The value produced if the argument is absent from the request.
- dest – The name of the attribute to be added to the object
returned by
parse_args()
. - required (bool) – Whether or not the argument may be omitted (optionals only).
- action (string) – The basic type of action to be taken when this argument is encountered in the request. Valid options are “store” and “append”.
- ignore (bool) – Whether to ignore cases where the argument fails type conversion
- type – The type to which the request argument should be converted.
If a type raises an exception, the message in the error will be returned in the response.
Defaults to
unicode
in python2 andstr
in python3. - location – The attributes of the
flask.Request
object to source the arguments from (ex: headers, args, etc.), can be an iterator. The last item listed takes precedence in the result set. - choices – A container of the allowable values for the argument.
- help – A brief description of the argument, returned in the response when the argument is invalid. May optionally contain an “{error_msg}” interpolation token, which will be replaced with the text of the error raised by the type converter.
- case_sensitive (bool) – Whether argument values in the request are case sensitive or not (this will convert all values to lowercase)
- store_missing (bool) – Whether the arguments default value should be stored if the argument is missing from the request.
- trim (bool) – If enabled, trims whitespace around the argument.
- nullable (bool) – If enabled, allows null value in argument.
-
handle_validation_error
(error, bundle_errors)[source]¶ Called when an error is raised while parsing. Aborts the request with a 400 status and an error message
Parameters: - error – the error that was raised
- bundle_errors (bool) – do not abort when first error occurs, return a dict with the name of the argument and the error message to be bundled
-
parse
(request, bundle_errors=False)[source]¶ Parses argument value(s) from the request, converting according to the argument’s type.
Parameters: - request – The flask request object to parse arguments from
- bundle_errors (bool) – do not abort when first error occurs, return a dict with the name of the argument and the error message to be bundled
-
flask_restplus.reqparse.
LOCATIONS
= {u'args': u'query', u'files': u'formData', u'form': u'formData', u'headers': u'header', u'json': u'body', u'values': u'query'}¶ Maps Flask-RESTPlus RequestParser locations to Swagger ones
-
flask_restplus.reqparse.
PY_TYPES
= {None: u'void', <type 'int'>: u'integer', <type 'float'>: u'number', <type 'bool'>: u'boolean', <type 'str'>: u'string'}¶ Maps Python primitives types to Swagger ones
-
class
flask_restplus.reqparse.
RequestParser
(argument_class=<class 'flask_restplus.reqparse.Argument'>, result_class=<class 'flask_restplus.reqparse.ParseResult'>, trim=False, bundle_errors=False)[source]¶ Enables adding and parsing of multiple arguments in the context of a single request. Ex:
from flask_restplus import RequestParser parser = RequestParser() parser.add_argument('foo') parser.add_argument('int_bar', type=int) args = parser.parse_args()
Parameters: -
add_argument
(*args, **kwargs)[source]¶ Adds an argument to be parsed.
Accepts either a single instance of Argument or arguments to be passed into
Argument
’s constructor.See
Argument
’s constructor for documentation on the available options.
-
parse_args
(req=None, strict=False)[source]¶ Parse all arguments from the provided request and return the results as a ParseResult
Parameters: strict (bool) – if req includes args not in parser, throw 400 BadRequest exception Returns: the parsed results as ParseResult
(or any class defined asresult_class
)Return type: ParseResult
-
Inputs¶
This module provide some helpers for advanced types parsing.
You can define you own parser using the same pattern:
def my_type(value):
if not condition:
raise ValueError('This is not my type')
return parse(value)
# Swagger documntation
my_type.__schema__ = {'type': 'string', 'format': 'my-custom-format'}
The last line allows you to document properly the type in the Swagger documentation.
-
class
flask_restplus.inputs.
URL
(check=False, ip=False, local=False, port=False, auth=False, schemes=None, domains=None, exclude=None)[source]¶ Validate an URL.
Example:
parser = reqparse.RequestParser() parser.add_argument('url', type=inputs.URL(schemes=['http', 'https']))
Input to the
URL
argument will be rejected if it does not match an URL with specified constraints. Ifcheck
is True it will also be rejected if the domain does not exists.Parameters: - check (bool) – Check the domain exists (perform a DNS resolution)
- ip (bool) – Allow IP (both ipv4/ipv6) as domain
- local (bool) – Allow localhost (both string or ip) as domain
- port (bool) – Allow a port to be present
- auth (bool) – Allow authentication to be present
- schemes (list|tuple) – Restrict valid schemes to this list
- domains (list|tuple) – Restrict valid domains to this list
- exclude (list|tuple) – Exclude some domains
-
flask_restplus.inputs.
boolean
(value)[source]¶ Parse the string
"true"
or"false"
as a boolean (case insensitive).Also accepts
"1"
and"0"
asTrue
/False
(respectively).If the input is from the request JSON body, the type is already a native python boolean, and will be passed through without further parsing.
Raises: ValueError – if the boolean value is invalid
-
flask_restplus.inputs.
date_from_iso8601
(value)[source]¶ Turns an ISO8601 formatted date into a date object.
Example:
inputs.date_from_iso8601("2012-01-01")
Parameters: value (str) – The ISO8601-complying string to transform Returns: A date Return type: date Raises: ValueError – if value is an invalid date literal
-
flask_restplus.inputs.
datetime_from_iso8601
(value)[source]¶ Turns an ISO8601 formatted date into a datetime object.
Example:
inputs.datetime_from_iso8601("2012-01-01T23:30:00+02:00")
Parameters: value (str) – The ISO8601-complying string to transform Returns: A datetime Return type: datetime Raises: ValueError – if value is an invalid date literal
-
flask_restplus.inputs.
datetime_from_rfc822
(value)[source]¶ Turns an RFC822 formatted date into a datetime object.
Example:
inputs.datetime_from_rfc822('Wed, 02 Oct 2002 08:00:00 EST')
Parameters: value (str) – The RFC822-complying string to transform Returns: The parsed datetime Return type: datetime Raises: ValueError – if value is an invalid date literal
-
class
flask_restplus.inputs.
email
(check=False, ip=False, local=False, domains=None, exclude=None)[source]¶ Validate an email.
Example:
parser = reqparse.RequestParser() parser.add_argument('email', type=inputs.email(dns=True))
Input to the
email
argument will be rejected if it does not match an email and if domain does not exists.Parameters:
-
class
flask_restplus.inputs.
int_range
(low, high, argument=u'argument')[source]¶ Restrict input to an integer in a range (inclusive)
-
flask_restplus.inputs.
iso8601interval
(value, argument=u'argument')[source]¶ Parses ISO 8601-formatted datetime intervals into tuples of datetimes.
Accepts both a single date(time) or a full interval using either start/end or start/duration notation, with the following behavior:
- Intervals are defined as inclusive start, exclusive end
- Single datetimes are translated into the interval spanning the largest resolution not specified in the input value, up to the day.
- The smallest accepted resolution is 1 second.
- All timezones are accepted as values; returned datetimes are localized to UTC. Naive inputs and date inputs will are assumed UTC.
Examples:
"2013-01-01" -> datetime(2013, 1, 1), datetime(2013, 1, 2) "2013-01-01T12" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 13) "2013-01-01/2013-02-28" -> datetime(2013, 1, 1), datetime(2013, 2, 28) "2013-01-01/P3D" -> datetime(2013, 1, 1), datetime(2013, 1, 4) "2013-01-01T12:00/PT30M" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 12, 30) "2013-01-01T06:00/2013-01-01T12:00" -> datetime(2013, 1, 1, 6), datetime(2013, 1, 1, 12)
Parameters: value (str) – The ISO8601 date time as a string Returns: Two UTC datetimes, the start and the end of the specified interval Return type: A tuple (datetime, datetime) Raises: ValueError – if the interval is invalid.
-
flask_restplus.inputs.
natural
(value, argument=u'argument')[source]¶ Restrict input type to the natural numbers (0, 1, 2, 3…)
-
flask_restplus.inputs.
positive
(value, argument=u'argument')[source]¶ Restrict input type to the positive integers (1, 2, 3…)
-
class
flask_restplus.inputs.
regex
(pattern)[source]¶ Validate a string based on a regular expression.
Example:
parser = reqparse.RequestParser() parser.add_argument('example', type=inputs.regex('^[0-9]+$'))
Input to the
example
argument will be rejected if it contains anything but numbers.Parameters: pattern (str) – The regular expression the input must match
-
flask_restplus.inputs.
url
= <flask_restplus.inputs.URL object>¶ Validate an URL
Legacy validator, allows, auth, port, ip and local Only allows schemes ‘http’, ‘https’, ‘ftp’ and ‘ftps’
Errors¶
-
flask_restplus.errors.
abort
(code=<HTTPStatus.INTERNAL_SERVER_ERROR: 500>, message=None, **kwargs)[source]¶ Properly abort the current request.
Raise a HTTPException for the given status code. Attach any keyword arguments to the exception for later processing.
Parameters: Raises: HTTPException –
-
exception
flask_restplus.errors.
ValidationError
(msg)[source]¶ An helper class for validation errors.
-
exception
flask_restplus.errors.
SpecsError
(msg)[source]¶ An helper class for incoherent specifications.
-
exception
flask_restplus.fields.
MarshallingError
(underlying_exception)[source] This is an encapsulating Exception in case of marshalling error.
Internals¶
These are internal classes or helpers. Most of the time you shouldn’t have to deal directly with them.
-
class
flask_restplus.api.
SwaggerView
(api=None, *args, **kwargs)[source]¶ Render the Swagger specifications as JSON
-
class
flask_restplus.swagger.
Swagger
(api)[source]¶ A Swagger documentation wrapper for an API instance.
-
class
flask_restplus.postman.
PostmanCollectionV1
(api, swagger=False)[source]¶ Postman Collection (V1 format) serializer
-
flask_restplus.utils.
merge
(first, second)[source]¶ Recursively merges two dictionnaries.
Second dictionnary values will take precedance over those from the first one. Nested dictionnaries are merged too.
Parameters: Returns: the resulting merged dictionnary
Return type:
-
flask_restplus.utils.
camel_to_dash
(value)[source]¶ Transform a CamelCase string into a low_dashed one
Parameters: value (str) – a CamelCase string to transform Returns: the low_dashed string Return type: str
-
flask_restplus.utils.
not_none
(data)[source]¶ Remove all keys where value is None
Parameters: data (dict) – A dictionnary with potentialy some values set to None Returns: The same dictionnary without the keys with values to None
Return type: dict
-
flask_restplus.utils.
not_none_sorted
(data)[source]¶ Remove all keys where value is None
Parameters: data (OrderedDict) – A dictionnary with potentialy some values set to None Returns: The same dictionnary without the keys with values to None
Return type: OrderedDict
-
flask_restplus.utils.
unpack
(response, default_code=<HTTPStatus.OK: 200>)[source]¶ Unpack a Flask standard response.
Flask response can be: - a single value - a 2-tuple
(value, code)
- a 3-tuple(value, code, headers)
Warning
When using this function, you must ensure that the tuple is not the reponse data. To do so, prefer returning list instead of tuple for listings.
Parameters: - response – A Flask style response
- default_code (int) – The HTTP code to use as default if none is provided
Returns: a 3-tuple
(data, code, headers)
Return type: Raises: ValueError – if the response does not have one of the expected format