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'', default_mediatype=u'application/json', decorators=None, catch_all_404s=False, serve_challenge_on_401=False, **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.
  • 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’)
as_postman(urlvars=False, swagger=False)[source]

Serialize the API as Postman collection (v1)

Parameters:
  • urlvars (bool) – whether to include or not placeholders for query strings
  • swagger (bool) – whether to include or not the swagger.json specifications
base_path

The API path

Return type:str
base_url

The API base absolute url

Return type:str
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:
  • resource (Resource) – the resource for which we want an endpoint
  • namespace (Namespace) – the namespace holding the resource
Returns str:

An endpoint name

documentation(func)[source]

A decorator to specify a view funtion for the documentation

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
errorhandler(exception)[source]

A decorator to register an error handler for a given exception

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
mediatypes()[source]

Returns a list of requested mediatypes sent in the Accept header

mediatypes_method()[source]

Return a method that returns a list of mediatypes

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

render_doc()[source]

Override this method to customize the documentation page

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
specs_url

The Swagger specifications absolute url (ie. swagger.json)

Return type:str
unauthorized(response)[source]

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().

class flask_restplus.Namespace(name, description=None, path=None, decorators=None, validate=None, **kwargs)[source]

Group resources together.

Namespace is to API what flask.Blueprint is for flask.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
  • api (Api) – an optional API to attache to the namespace
abort(*args, **kwargs)[source]

Properly abort the current request

See: abort()

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 in fields.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")
as_list(field)[source]

Allow to specify nested lists for documentation

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()

deprecated(func)[source]

A decorator to mark a resource or a method as deprecated

doc(shortcut=None, **kwargs)[source]

A decorator to add some api documentation to the decorated object

errorhandler(exception)[source]

A decorator to register an error handler for a given exception

expect(*inputs, **kwargs)[source]

A decorator to Specify the expected input model

Parameters:
  • inputs (Model|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:
  • name (str) – the HTTP header name
  • description (str) – a description about the header
hide(func)[source]

A decorator to hide a resource or a method from specifications

inherit(name, *specs)[source]

Inherit a modal (use the Swagger composition pattern aka. allOf)

See also

Model.inherit()

marshal(*args, **kwargs)[source]

A shortcut to the marshal() helper

marshal_list_with(fields, **kwargs)[source]

A shortcut decorator for marshal_with() with as_list=True

marshal_with(fields, as_list=False, code=200, description=None, **kwargs)[source]

A decorator specifying the fields to use for serialization.

Parameters:
  • as_list (bool) – Indicate that the return type is a list (for the documentation)
  • code (int) – Optionally give the expected HTTP response code if its different from 200
model(name=None, model=None, mask=None, **kwargs)[source]

Register a model

See also

Model

param(name, description=None, _in=u'query', **kwargs)[source]

A decorator to specify one of the expected parameters

Parameters:
  • name (str) – the parameter name
  • description (str) – a small description
  • _in (str) – the parameter location (query|header|formData|body|cookie)
parser()[source]

Instanciate a RequestParser

response(code, description, model=None, **kwargs)[source]

A decorator to specify one of the expected responses

Parameters:
  • code (int) – the HTTP status code
  • description (str) – a small description about the response
  • model (Model) – an optional response model
route(*urls, **kwargs)[source]

A decorator to route resources.

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.

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 the dispatch_request() method on it.

The arguments passed to as_view() are forwarded to the constructor of the class.

validate_payload(func)[source]

Perform a payload validation on expected model if necessary

Models

class flask_restplus.Model(name, *args, **kwargs)[source]

A thin wrapper on dict to store API doc metadata.

Parameters:
  • name (str) – The model public name
  • mask (str) – an optional default model mask
ancestors

Return the ancestors tree

classmethod clone(name, *parents)[source]

Clone these models (Duplicate all fields)

It can be used from the class

>>> model = Model.clone(fields_1, fields_2)

or from an Instanciated model

>>> new_model = model.clone(fields_1, fields_2)
Parameters:
  • name (str) – The new model name
  • parents (dict) – The new model extra fields
extend(name, fields)[source]

Extend this model (Duplicate all fields)

Parameters:
  • name (str) – The new model name
  • fields (dict) – The new model extra fields
Depreated:

since 0.9. Use clone() instead.

classmethod inherit(name, *parents)[source]

Inherit this model (use the Swagger composition pattern aka. allOf)

Parameters:
  • name (str) – The new model name
  • fields (dict) – The new model extra fields
resolved[source]

Resolve real fields before submitting them to marshal

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)[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 to unicode in python2 and str 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:
  • endpoint (str) – Endpoint name. If endpoint is None, request.endpoint is used instead
  • absolute (bool) – If True, ensures that the generated urls will have the hostname included
  • scheme (str) – URL scheme specifier (e.g. http, https)
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 or iso8601
format_iso8601(dt)[source]

Turn a datetime object into an ISO8601 formatted date.

Parameters:dt (datetime) – The datetime to transform
Returns:A ISO 8601 formatted date string
format_rfc822(dt)[source]

Turn a datetime object into a formatted date.

Parameters:dt (datetime) – The datetime to transform
Returns:A RFC 822 formatted date string
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 to False.

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, 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
  • 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
resolve_ancestor(models)[source]

Resolve the common ancestor for all models.

Assume there is only one common ancestor.

exception flask_restplus.fields.MarshallingError(underlying_exception)[source]

This is an encapsulating Exception in case of marshalling error.

Serialization

flask_restplus.marshal(data, fields, envelope=None, mask=None)[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
>>> from flask_restplus import fields, marshal
>>> data = { 'a': 100, 'b': 'foo' }
>>> mfields = { 'a': fields.Raw }
>>> marshal(data, mfields)
OrderedDict([('a', 100)])
>>> marshal(data, mfields, envelope='data')
OrderedDict([('data', OrderedDict([('a', 100)]))])
flask_restplus.marshal_with(fields, envelope=None, mask=None)[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)]))])

see flask_restplus.marshal()

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]

see flask_restplus.marshal_with()

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
clean(mask)[source]

Remove unecessary characters

filter_data(data)[source]

Handle the data filtering given a parsed mask

Parameters:
  • data (dict) – the raw data to filter
  • mask (list) – a parsed mask tofilter against
  • skip (bool) – whether or not to skip missing fields
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

Inputs

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 and str 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
source(request)[source]

Pulls values off the request in the provided location :param request: The flask request object to parse arguments from

flask_restplus.reqparse.LOCATIONS = {u'files': u'formData', u'form': u'formData', u'args': u'query', 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 = {<type 'str'>: u'string', <type 'int'>: u'integer', <type 'bool'>: u'boolean', None: u'void'}

Maps Pyton primitives types to Swagger ones

class flask_restplus.reqparse.ParseResult[source]

The default result container as an Object dict.

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:
  • trim (bool) – If enabled, trims whitespace on all arguments in this parser
  • bundle_errors (bool) – If enabled, do not abort when first error occurs, return a dict with the name of the argument and the error message to be bundled and return all validation errors
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.

copy()[source]

Creates a copy of this RequestParser with the same set of arguments

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 as result_class)
Return type:ParseResult
remove_argument(name)[source]

Remove the argument matching the given name.

replace_argument(name, *args, **kwargs)[source]

Replace the argument matching the given name with a new version.

flask_restplus.inputs.boolean(value)[source]

Parse the string "true" or "false" as a boolean (case insensitive).

Also accepts "1" and "0" as True/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(value)[source]

Parse a valid looking date in the format YYYY-mm-dd

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:
  • 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
  • domains (list|tuple) – Restrict valid domains to this list
  • exclude (list|tuple) – Exclude some domains
class flask_restplus.inputs.int_range(low, high, argument=u'argument')[source]

Restrict input to an integer in a range (inclusive)

flask_restplus.inputs.ip(value)[source]

Validate an IP address (both IPv4 and IPv6)

flask_restplus.inputs.ipv4(value)[source]

Validate an IPv4 address

flask_restplus.inputs.ipv6(value)[source]

Validate an IPv6 address

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(value)[source]

Validate a URL.

Parameters:value (str) – The URL to validate
Returns:The URL if valid.
Raises:ValueError

Errors

flask_restplus.errors.abort(code=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:
  • code (int) – The associated HTTP status code
  • message (str) – An optional details message
  • kwargs – Any additional data to pass to the error payload
Raises:

HTTPException

exception flask_restplus.errors.RestError(msg)[source]

Base class for all Flask-Restplus Errors

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.

exception flask_restplus.mask.MaskError(msg)[source]

Raised when an error occurs on mask

exception flask_restplus.mask.ParseError(msg)[source]

Raised when the mask parsing failed

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:
  • first (dict) – The first dictionnary
  • second (dict) – The second dictionnary
Returns:

the resulting merged dictionnary

Return type:

dict

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.default_id(resource, method)[source]

Default operation ID generator

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=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:

tuple

Raises:

ValueError – if the response does not have one of the expected format