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
- errors (dict) – A dictionary to define a custom response for each exception or error raised during a request
- authorizations (dict) – A Swagger Authorizations declaration as dictionary
-
add_resource
(resource, *urls, **kwargs)[source]¶ Register a Swagger API declaration for a given API Namespace
-
default_endpoint
(resource, namespace=None)[source]¶ Provide a default endpoint for a resource on a given namespace.
Endpoints are ensured not to collide.
-
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
-
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
-
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 (integer) – Optionnaly give the expected HTTP response code if its different from 200
-
model
(name=None, model=None, **kwargs)[source]¶ Register a model
Model can be either a dictionary or a fields. Raw subclass.
-
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
-
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!'
Given a response, change it to ask for credentials
- The API root/documentation will be
-
class
flask_restplus.
Resource
(api, *args, **kwargs)[source]¶ -
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)[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
MarshallingException
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 MarshallingException: 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 MarshallingException: 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)
-
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'rfc822', **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)[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]
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.
-
flask_restplus.inputs.
datetime_from_iso8601
(datetime_str)[source]¶ Turns an ISO8601 formatted date into a datetime object.
Example:
inputs.datetime_from_iso8601("2012-01-01T23:30:00+02:00")
Parameters: datetime_str (str) – The ISO8601-complying string to transform Returns: A datetime
-
flask_restplus.inputs.
datetime_from_rfc822
(datetime_str)[source]¶ Turns an RFC822 formatted date into a datetime object.
Example:
inputs.datetime_from_rfc822('Wed, 02 Oct 2002 08:00:00 EST')
Parameters: datetime_str (str) – The RFC822-complying string to transform Returns: A datetime
-
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¶
-
exception
flask_restplus.exceptions.
RestException
(msg)[source]¶ Base class for all Flask-Restplus Exceptions
-
exception
flask_restplus.exceptions.
ValidationError
(msg)[source]¶ An helper class for validation errors.
-
exception
flask_restplus.exceptions.
SpecsError
(msg)[source]¶ An helper class for incoherent specifications.
-
exception
flask_restplus.fields.
MarshallingException
(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.
ApiNamespace
(api, name, description=None, endpoint=None, path=None, **kwargs)[source]¶
-
class
flask_restplus.model.
ApiModel
(*args, **kwargs)[source]¶ A thin wrapper on dict to store API doc metadata