API Docs

flask_restful.``marshal(data, fields, envelope=None)

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

flask_restful.``marshal_with(fields, envelope=None)

A decorator that apply marshalling to the return values of your methods.

  1. >>> from flask_restful import fields, marshal_with
  2. >>> mfields = { 'a': fields.Raw }
  3. >>> @marshal_with(mfields)
  4. ... def get():
  5. ... return { 'a': 100, 'b': 'foo' }
  6. ...
  7. ...
  8. >>> get()
  9. OrderedDict([('a', 100)])
  1. >>> @marshal_with(mfields, envelope='data')
  2. ... def get():
  3. ... return { 'a': 100, 'b': 'foo' }
  4. ...
  5. ...
  6. >>> get()
  7. OrderedDict([('data', OrderedDict([('a', 100)]))])

see flask_restful.marshal()

flask_restful.``marshal_with_field(field)

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

  1. >>> from flask_restful import marshal_with_field, fields
  2. >>> @marshal_with_field(fields.List(fields.Integer))
  3. ... def get():
  4. ... return ['1', 2, 3.0]
  5. ...
  6. >>> get()
  7. [1, 2, 3]

see flask_restful.marshal_with()

flask_restful.``abort(http_status_code, \*kwargs*)

Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing.

Api

class flask_restful.``Api(app=None, prefix=’’, default_mediatype=’application/json’, decorators=None, catch_all_404s=False, serve_challenge_on_401=False, url_part_order=’bae’, errors=None)

The main entry point for the application. You need to initialize it with a Flask Application:

  1. >>> app = Flask(__name__)
  2. >>> api = restful.Api(app)

Alternatively, you can use init_app() to set the Flask application after it has been constructed.

Parameters:
  • app (flask.Flask or flask.Blueprint) – the Flask application object
  • prefix (str) – Prefix all routes with a value, eg v1 or 2010-04-01
  • default_mediatype (str) – The default media type to return
  • decorators (list) – Decorators to attach to every resource
  • catch_all_404s (bool) – Use handle_error() to handle 404 errors throughout your app
  • serve_challenge_on_401 – Whether to serve a challenge response to clients on receiving 401. This usually leads to a username/password popup in web browers.
  • 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 () – A dictionary to define a custom response for each exception or error raised during a request
  • add_resource(resource, \urls, **kwargs*)

    Adds a resource to the api.

    Parameters:
    • resource (Type[Resource]) – the class name of your resource
    • 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 (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:

    1. api.add_resource(HelloWorld, '/', '/hello')
    2. api.add_resource(Foo, '/foo', endpoint="foo")
    3. api.add_resource(FooSpecial, '/special/foo', endpoint="foo")
  • error_router(original_handler, e)

    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)

    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)

    Initialize this class with the given flask.Flask application or flask.Blueprint object.

    Parameters:app (flask.Blueprint) – the Flask application or blueprint object

    Examples:

    1. api = Api()
    2. api.add_resource(...)
    3. api.init_app(app)
  • make_response(data, \args, **kwargs*)

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

    Returns a list of requested mediatypes sent in the Accept header

  • mediatypes_method()

    Return a method that returns a list of mediatypes

  • output(resource)

    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)

    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)

    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:

    1. @api.representation('application/xml')
    2. def xml(data, code, headers):
    3. resp = make_response(convert_data_to_xml(data), code)
    4. resp.headers.extend(headers)
    5. return resp
  • resource(\urls, **kwargs*)

    Wraps a Resource class, adding it to the api. Parameters are the same as add_resource().

    Example:

    1. app = Flask(__name__)
    2. api = restful.Api(app)
    3. @api.resource('/foo')
    4. class Foo(Resource):
    5. def get(self):
    6. return 'Hello, World!'
  • unauthorized(response)

    Given a response, change it to ask for credentials

  • url_for(resource, \*values*)

    Generates a URL to the given resource.

    Works like flask.url_for().

class flask_restful.``Resource

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.

  • dispatch_request(\args, **kwargs*)

    Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule.

ReqParse

class reqparse.``RequestParser(argument_class=<class ‘reqparse.Argument’>, namespace_class=<class ‘reqparse.Namespace’>, trim=False, bundle_errors=False)

Enables adding and parsing of multiple arguments in the context of a single request. Ex:

  1. from flask_restful import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument('foo')
  4. parser.add_argument('int_bar', type=int)
  5. 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*)

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

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

  • parse_args(req=None, strict=False, http_error_code=400)

    Parse all arguments from the provided request and return the results as a Namespace

    Parameters:
    • req – Can be used to overwrite request from Flask
    • strict – if req includes args not in parser, throw 400 BadRequest exception
    • http_error_code – use custom error code for flask_restful.abort()
  • remove_argument(name)

    Remove the argument matching the given name.

  • replace_argument(name, \args, **kwargs*)

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

class reqparse.``Argument(name, default=None, dest=None, required=False, ignore=False, type=<function <lambda>>, location=(‘json’, ‘values’), choices=(), action=’store’, help=None, operators=(‘=’, ), case_sensitive=True, store_missing=True, trim=False, nullable=True)

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 – The basic type of action to be taken when this argument is encountered in the request. Valid options are “store” and “append”.
  • ignore – 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.
  • __init__(name, default=None, dest=None, required=False, ignore=False, type=<function <lambda>>, location=(‘json’, ‘values’), choices=(), action=’store’, help=None, operators=(‘=’, ), case_sensitive=True, store_missing=True, trim=False, nullable=True)

    Initialize self. See help(type(self)) for accurate signature.

  • handle_validation_error(error, bundle_errors)

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

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

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

Fields

class fields.``String(default=None, attribute=None)

Marshal a value as a string. Uses six.text_type so values will be converted to unicode in python2 and str in python3.

  • format(value)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()

class fields.``FormattedString(src_str)

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:

  1. fields = {
  2. 'name': fields.String,
  3. 'greeting': fields.FormattedString("Hello {name}")
  4. }
  5. data = {
  6. 'name': 'Doug',
  7. }
  8. marshal(data, fields)
  • output(key, obj)

    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 fields.``Url(endpoint=None, absolute=False, scheme=None, \*kwargs*)

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)

    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 fields.``DateTime(dt_format=’rfc822’, \*kwargs*)

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)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()

class fields.``Float(default=None, attribute=None)

A double as IEEE-754 double precision. ex : 3.141592653589793 3.1415926535897933e-06 3.141592653589793e+24 nan inf -inf

  • format(value)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()

class fields.``Integer(default=0, \*kwargs*)

Field for outputting an integer value.

Parameters:default (int) – The default value for the field, if no value is specified.
  • format(value)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()

class fields.``Arbitrary(default=None, attribute=None)

  • A floating point number with an arbitrary precision

    ex: 634271127864378216478362784632784678324.23432

  • format(value)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()

class fields.``Nested(nested, allow_null=False, \*kwargs*)

Allows you to nest one set of fields inside another. See Advanced : Nested Field for more information

Parameters:
  • nested (dict) – The 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)
  • output(key, obj)

    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 fields.``List(cls_or_instance, \*kwargs*)

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)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()
  • output(key, data)

    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 fields.``Raw(default=None, attribute=None)

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.
  • format(value)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()
  • output(key, obj)

    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 fields.``Boolean(default=None, attribute=None)

Field for outputting a boolean value.

Empty collections such as "", {}, [], etc. will be converted to False.

  • format(value)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()

class fields.``Fixed(decimals=5, \*kwargs*)

A decimal number with a fixed precision.

  • format(value)

    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:

    1. class TitleCase(Raw):
    2. def format(self, value):
    3. return unicode(value).title()

fields.``Price

alias of fields.Fixed

Inputs

inputs.``boolean(value)

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.

inputs.``date(value)

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

inputs.``datetime_from_iso8601(datetime_str)

Turns an ISO8601 formatted date into a datetime object.

Example:

  1. inputs.datetime_from_iso8601("2012-01-01T23:30:00+02:00")
Parameters:datetime_str (str) – The ISO8601-complying string to transform
Returns:A datetime

inputs.``datetime_from_rfc822(datetime_str)

Turns an RFC822 formatted date into a datetime object.

Example:

  1. 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 inputs.``int_range(low, high, argument=’argument’)

Restrict input to an integer in a range (inclusive)

inputs.``iso8601interval(value, argument=’argument’)

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:

  1. "2013-01-01" -> datetime(2013, 1, 1), datetime(2013, 1, 2)
  2. "2013-01-01T12" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 13)
  3. "2013-01-01/2013-02-28" -> datetime(2013, 1, 1), datetime(2013, 2, 28)
  4. "2013-01-01/P3D" -> datetime(2013, 1, 1), datetime(2013, 1, 4)
  5. "2013-01-01T12:00/PT30M" -> datetime(2013, 1, 1, 12), datetime(2013, 1, 1, 12, 30)
  6. "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.

inputs.``natural(value, argument=’argument’)

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

inputs.``positive(value, argument=’argument’)

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

class inputs.``regex(pattern, flags=0)

Validate a string based on a regular expression.

Example:

  1. parser = reqparse.RequestParser()
  2. 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
  • flags (int) – Flags to change expression behavior

inputs.``url(value)

Validate a URL.

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

Logo

Table of Contents

Related Topics

This Page

Quick search