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: |
|
---|
>>> from flask_restful 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_restful.``marshal_with
(fields, envelope=None)
A decorator that apply marshalling to the return values of your methods.
>>> from flask_restful 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_restful.``marshal_with_field
(field)
A decorator that formats the return values of your methods with a single field.
>>> from flask_restful 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_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:
>>> app = Flask(__name__)
>>> api = restful.Api(app)
Alternatively, you can use init_app()
to set the Flask application after it has been constructed.
Parameters: |
|
---|
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 infields.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:
api.add_resource(HelloWorld, '/', '/hello')
api.add_resource(Foo, '/foo', endpoint="foo")
api.add_resource(FooSpecial, '/special/foo', endpoint="foo")
- resource (
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 orflask.Blueprint
object.Parameters: app (flask.Blueprint) – the Flask application or blueprint object Examples:
api = Api()
api.add_resource(...)
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:
@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*)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!'
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:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('foo')
parser.add_argument('int_bar', type=int)
args = parser.parse_args()
Parameters: |
---|
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: |
|
---|
__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:
class TitleCase(Raw):
def format(self, value):
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:
fields = {
'name': fields.String,
'greeting': fields.FormattedString("Hello {name}")
}
data = {
'name': 'Doug',
}
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: |
---|
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:
class TitleCase(Raw):
def format(self, value):
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:
class TitleCase(Raw):
def format(self, value):
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:
class TitleCase(Raw):
def format(self, value):
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:
class TitleCase(Raw):
def format(self, value):
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: |
|
---|
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:
class TitleCase(Raw):
def format(self, value):
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: |
|
---|
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:
class TitleCase(Raw):
def format(self, value):
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:
class TitleCase(Raw):
def format(self, value):
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:
class TitleCase(Raw):
def format(self, value):
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:
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:
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:
"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. |
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:
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: |
---|
inputs.``url
(value)
Validate a URL.
Parameters: | value (string) – The URL to validate |
---|---|
Returns: | The URL if valid. |
Raises: | ValueError |
Table of Contents
Related Topics
- Documentation overview
- Previous: Intermediate Usage
- Next: Running the Tests