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, **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 - url_part_order – A string that controls the order that the pieces of the url are concatenated when the full url is constructed. ‘b’ is the blueprint (or blueprint registration) prefix, ‘a’ is the api prefix, and ‘e’ is the path component the endpoint is added with
- authorizations (dict) – A Swagger Authorizations declaration as dictionary
-
add_resource
(resource, *urls, **kwargs)[source]¶ Register a Swagger API declaration for a given API Namespace
Parameters:
-
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
Returns str:
-
base_url
¶ The API base absolute url
Returns str:
-
default_endpoint
(resource, namespace=None)[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
-
doc
(shortcut=None, **kwargs)[source]¶ A decorator to add some api documentation to the decorated object
-
error_router
(original_handler, e)[source]¶ This function decides whether the error occured in a flask-restful endpoint or not. If it happened in a flask-restful 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-restful 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
-
expect
(body, validate=None)[source]¶ A decorator to Specify the expected input model
Parameters: - body (Model) – The expected model
- validate (bool) – whether to perform validation or not
-
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
-
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
-
inherit
(name, parent, fields)[source]¶ Inherit a modal (use the Swagger composition pattern aka. allOf)
-
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
-
marshal_list_with
(fields, **kwargs)[source]¶ A shortcut decorator for
marshal_with()
withas_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) – Optionnaly give the expected HTTP response code if its different from 200
-
model
(name=None, model=None, mask=None, **kwargs)[source]¶ Register a model
Model can be either a dictionary or a fields. Raw subclass.
-
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 in to account the Blueprint name part of the endpoint name.
Parameters: endpoint – 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
-
resource
(*urls, **kwargs)[source]¶ Wraps a
Resource
class, adding it to the api. Parameters are the same asadd_resource()
.Example:
app = Flask(__name__) api = restful.Api(app) @api.resource('/foo') class Foo(Resource): def get(self): return 'Hello, World!'
-
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 optionnal response model
-
specs_url
¶ The Swagger specifications absolute url (ie. swagger.json)
Returns str:
Given a response, change it to ask for credentials
- The API root/documentation will be
-
class
flask_restplus.
Resource
(api, *args, **kwargs)[source]¶ Represents an abstract RESTful 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 thedispatch_request()
method on it.The arguments passed to
as_view()
are forwarded to the constructor of the class.
-
Models¶
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 optionnal data example (for documentation purpose)
- mask (callable) – An optionnal 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 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: - 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
)
- endpoint (str) – Endpoint name. If endpoint is
-
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.
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, as_list=False, **kwargs)[source]¶ Allows you to nest one set of fields inside another. See Advanced : 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
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)]))])
-
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
-
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¶
-
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.
date_from_rfc822
(value)[source]¶ Turns an RFC822 formatted date into a date object.
Example:
inputs.date_from_rfc822('Wed, 02 Oct 2002 08:00:00 EST')
Parameters: value (str) – The RFC822-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.
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
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 optionnal details message
- kwargs – Any additionnal data to pass to the error payload
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.namespace.
Namespace
(api, name, description=None, endpoint=None, path=None, **kwargs)[source]¶ Group resources together
Parameters: - api (Api) – The API on which the namespace is attached
- name (str) – The namespace name
- description (str) – An optionnale short description
- path (str) – An optionnal prefix path. If not provided, prefix is
/+name
-
class
flask_restplus.model.
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 optionnal default model mask
-
class
flask_restplus.api.
SwaggerView
(api, *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.
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