API

Core

class flask_restx.Api(app=None, version='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='/', default_id=<function default_id>, default='default', default_label='Default namespace', validate=None, tags=None, prefix='', ordered=False, default_mediatype='application/json', decorators=None, catch_all_404s=False, serve_challenge_on_401=False, format_checker=None, url_scheme=None, default_swagger_filename='swagger.json', **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.
  • url_scheme – If set to a string (e.g. http, https), then the specs_url and base_url will explicitly use this scheme regardless of how the application is deployed. This is necessary for some deployments behind a reverse proxy.
  • default_swagger_filename (str) – The default swagger filename.
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:
  • 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 algorithm 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 function for the documentation

error_router(original_handler, e)[source]

This function decides whether the error occurred in a flask-restx endpoint or not. If it happened in a flask-restx 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-restx 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)
  • url_scheme – If set to a string (e.g. http, https), then the specs_url and base_url will explicitly use this scheme regardless of how the application is deployed. This is necessary for some deployments behind a reverse proxy.
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 relative url (ie. swagger.json). If the spec_url_scheme attribute is set, then the full url is provided instead (e.g. http://localhost/swaggger.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_restx.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 for flask.Flask.

Parameters:
  • name (str) – The namespace name
  • description (str) – An optional 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
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 (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:
  • 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 model (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=<HTTPStatus.OK: 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, strict=False, **kwargs)[source]

Register a model

:param bool strict - should model validation raise error when non-specified param
is provided?

See also

Model

param(name, description=None, _in='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

payload

Store the input payload in the current request context

produces(mimetypes)[source]

A decorator to specify the MIME types the API can produce

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 (ModelBase) – an optional response model
route(*urls, **kwargs)[source]

A decorator to route resources.

schema_model(name=None, schema=None)[source]

Register a model

See also

Model

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_restx.Resource(api=None, *args, **kwargs)[source]

Represents an abstract RESTX 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: str, *class_args, **class_kwargs) → Union[Callable[[...], Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes], Tuple[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes]], Union[Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes]], int], Tuple[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes]], int, Union[Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], WSGIApplication]], Callable[[...], Awaitable[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes], Tuple[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes]], Union[Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], Tuple[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes]], int], Tuple[Union[Response, str, bytes, List[Any], Mapping[str, Any], Iterator[str], Iterator[bytes]], int, Union[Headers, Mapping[str, Union[str, List[str], Tuple[str, ...]]], Sequence[Tuple[str, Union[str, List[str], Tuple[str, ...]]]]]], WSGIApplication]]]]

Convert the class into a view function that can be registered for a route.

By default, the generated view will create a new instance of the view class for every request and call its dispatch_request() method. If the view class sets init_every_request to False, the same instance will be used for every request.

Except for name, all other arguments passed to this method are forwarded to the view class __init__ method.

Changed in version 2.2: Added the init_every_request class attribute.

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

The actual view function behavior. Subclasses must override this and return a valid response. Any variables from the URL rule are passed as keyword arguments.

validate_payload(func)[source]

Perform a payload validation on expected model if necessary

Models

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

A thin wrapper on fields dict to store API doc metadata. Can also be used for response marshalling.

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

All fields accept a required boolean and a description string in kwargs.

class flask_restx.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_restx.fields.String(*args, **kwargs)[source]

Marshal a value as a string.

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()
class flask_restx.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.
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_restx.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)
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_restx.fields.DateTime(dt_format='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(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()
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_restx.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_restx.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.

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()
class flask_restx.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.
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()
class flask_restx.fields.Float(*args, **kwargs)[source]

A double as IEEE-754 double precision.

ex : 3.141592653589793 3.1415926535897933e-06 3.141592653589793e+24 nan inf -inf

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()
class flask_restx.fields.Arbitrary(*args, **kwargs)[source]

A floating point number with an arbitrary precision.

ex: 634271127864378216478362784632784678324.23432

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()
class flask_restx.fields.Fixed(decimals=5, **kwargs)[source]

A decimal number with a fixed precision.

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()
class flask_restx.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)
output(key, obj, ordered=False, **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_restx.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.
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, data, ordered=False, **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_restx.fields.ClassName(dash=False, **kwargs)[source]

Return the serialized object class name as string.

Parameters:dash (bool) – If True, transform CamelCase to kebab_case.
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_restx.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
output(key, obj, ordered=False, **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
resolve_ancestor(models)[source]

Resolve the common ancestor for all models.

Assume there is only one common ancestor.

class flask_restx.fields.Wildcard(cls_or_instance, **kwargs)[source]

Field for marshalling list of “unkown” fields.

Parameters:cls_or_instance – The field type the list will contain.
output(key, obj, ordered=False)[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
exception flask_restx.fields.MarshallingError(underlying_exception)[source]

This is an encapsulating Exception in case of marshalling error.

Serialization

flask_restx.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_restx 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_restx.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_restx 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)])

see flask_restx.marshal()

flask_restx.marshal_with_field(field)[source]

A decorator that formats the return values of your methods with a single field.

>>> from flask_restx 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_restx.marshal_with()

class flask_restx.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 unnecessary 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 to filter 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_restx.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_restx.reqparse.Argument(name, default=None, dest=None, required=False, ignore=False, type=<class 'str'>, location=('json', 'values'), choices=(), action='store', help=None, operators=('=', ), 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 str.
  • 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_restx.reqparse.LOCATIONS = {'args': 'query', 'files': 'formData', 'form': 'formData', 'headers': 'header', 'json': 'body', 'values': 'query'}

Maps Flask-RESTX RequestParser locations to Swagger ones

flask_restx.reqparse.PY_TYPES = {<class 'int'>: 'integer', <class 'str'>: 'string', <class 'bool'>: 'boolean', <class 'float'>: 'number', None: 'void'}

Maps Python primitives types to Swagger ones

class flask_restx.reqparse.ParseResult[source]

The default result container as an Object dict.

class flask_restx.reqparse.RequestParser(argument_class=<class 'flask_restx.reqparse.Argument'>, result_class=<class 'flask_restx.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_restx 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.

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 documentation
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_restx.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. If check 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_restx.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_restx.inputs.date(value)[source]

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

flask_restx.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_restx.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_restx.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_restx.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_restx.inputs.int_range(low, high, argument='argument')[source]

Restrict input to an integer in a range (inclusive)

flask_restx.inputs.ip(value)[source]

Validate an IP address (both IPv4 and IPv6)

flask_restx.inputs.ipv4(value)[source]

Validate an IPv4 address

flask_restx.inputs.ipv6(value)[source]

Validate an IPv6 address

flask_restx.inputs.iso8601interval(value, argument='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_restx.inputs.natural(value, argument='argument')[source]

Restrict input type to the natural numbers (0, 1, 2, 3…)

flask_restx.inputs.positive(value, argument='argument')[source]

Restrict input type to the positive integers (1, 2, 3…)

class flask_restx.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_restx.inputs.url = <flask_restx.inputs.URL object>

Validate an URL

Legacy validator, allows, auth, port, ip and local Only allows schemes ‘http’, ‘https’, ‘ftp’ and ‘ftps’

Errors

flask_restx.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:
  • 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_restx.errors.RestError(msg)[source]

Base class for all Flask-RESTX Errors

exception flask_restx.errors.ValidationError(msg)[source]

A helper class for validation errors.

exception flask_restx.errors.SpecsError(msg)[source]

A helper class for incoherent specifications.

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

This is an encapsulating Exception in case of marshalling error.

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

Raised when an error occurs on mask

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

Raised when the mask parsing failed

Schemas

This module give access to OpenAPI specifications schemas and allows to validate specs against them.

New in version 0.12.1.

class flask_restx.schemas.LazySchema(filename, validator=<class 'jsonschema.validators.Draft4Validator'>)[source]

A thin wrapper around schema file lazy loading the data on first access

Parameters:
  • str (filename) – The package relative json schema filename
  • validator – The jsonschema validator class version

New in version 0.12.1.

validator

The jsonschema validator to validate against

flask_restx.schemas.OAS_20 = <flask_restx.schemas.LazySchema object>

OpenAPI 2.0 specification schema

exception flask_restx.schemas.SchemaValidationError(msg, errors=None)[source]

Raised when specification is not valid

New in version 0.12.1.

flask_restx.schemas.VERSIONS = {'2.0': <flask_restx.schemas.LazySchema object>}

Map supported OpenAPI versions to their JSON schema

flask_restx.schemas.validate(data)[source]

Validate an OpenAPI specification.

Supported OpenAPI versions: 2.0

Parameters:

dict (data) – The specification to validate

Returns boolean:
 

True if the specification is valid

Raises:

New in version 0.12.1.

Internals

These are internal classes or helpers. Most of the time you shouldn’t have to deal directly with them.

class flask_restx.api.SwaggerView(api=None, *args, **kwargs)[source]

Render the Swagger specifications as JSON

class flask_restx.swagger.Swagger(api)[source]

A Swagger documentation wrapper for an API instance.

class flask_restx.postman.PostmanCollectionV1(api, swagger=False)[source]

Postman Collection (V1 format) serializer

flask_restx.utils.merge(first, second)[source]

Recursively merges two dictionaries.

Second dictionary values will take precedence over those from the first one. Nested dictionaries are merged too.

Parameters:
  • first (dict) – The first dictionary
  • second (dict) – The second dictionary
Returns:

the resulting merged dictionary

Return type:

dict

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

Default operation ID generator

flask_restx.utils.not_none(data)[source]

Remove all keys where value is None

Parameters:data (dict) – A dictionary with potentially some values set to None
Returns:The same dictionary without the keys with values to None
Return type:dict
flask_restx.utils.not_none_sorted(data)[source]

Remove all keys where value is None

Parameters:data (OrderedDict) – A dictionary with potentially some values set to None
Returns:The same dictionary without the keys with values to None
Return type:OrderedDict
flask_restx.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 response 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