Request Parsing

Warning

The whole request parser part of Flask-RESTful is slated for removal and will be replaced by documentation on how to integrate with other packages that do the input/output stuff better (such as marshmallow). This means that it will be maintained until 2.0 but consider it deprecated. Don’t worry, if you have code using that now and wish to continue doing so, it’s not going to go away any time too soon.

Flask-RESTful’s request parsing interface, reqparse, is modeled after the argparse interface. It’s designed to provide simple and uniform access to any variable on the flask.request object in Flask.

Basic Arguments

Here’s a simple example of the request parser. It looks for two arguments in the flask.Request.values dict: an integer and a string

  1. from flask_restful import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument('rate', type=int, help='Rate cannot be converted')
  4. parser.add_argument('name')
  5. args = parser.parse_args()

Note

The default argument type is a unicode string. This will be str in python3 and unicode in python2.

If you specify the help value, it will be rendered as the error message when a type error is raised while parsing it. If you do not specify a help message, the default behavior is to return the message from the type error itself. See error-messages for more details.

By default, arguments are not required. Also, arguments supplied in the request that are not part of the RequestParser will be ignored.

Also note: Arguments declared in your request parser but not set in the request itself will default to None.

Required Arguments

To require a value be passed for an argument, just add required=True to the call to add_argument().

  1. parser.add_argument('name', required=True,
  2. help="Name cannot be blank!")

Multiple Values & Lists

If you want to accept multiple values for a key as a list, you can pass action='append'

  1. parser.add_argument('name', action='append')

This will let you make queries like

  1. curl http://api.example.com -d "name=bob" -d "name=sue" -d "name=joe"

And your args will look like this

  1. args = parser.parse_args()
  2. args['name'] # ['bob', 'sue', 'joe']

Other Destinations

If for some reason you’d like your argument stored under a different name once it’s parsed, you can use the dest keyword argument.

  1. parser.add_argument('name', dest='public_name')
  2. args = parser.parse_args()
  3. args['public_name']

Argument Locations

By default, the RequestParser tries to parse values from flask.Request.values, and flask.Request.json.

Use the location argument to add_argument() to specify alternate locations to pull the values from. Any variable on the flask.Request can be used. For example:

  1. # Look only in the POST body
  2. parser.add_argument('name', type=int, location='form')
  3. # Look only in the querystring
  4. parser.add_argument('PageSize', type=int, location='args')
  5. # From the request headers
  6. parser.add_argument('User-Agent', location='headers')
  7. # From http cookies
  8. parser.add_argument('session_id', location='cookies')
  9. # From file uploads
  10. parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')

Note

Only use type=list when location='json'. See this issue for more details

Multiple Locations

Multiple argument locations can be specified by passing a list to location:

  1. parser.add_argument('text', location=['headers', 'values'])

When multiple locations are specified, the arguments from all locations specified are combined into a single MultiDict. The last location listed takes precedence in the result set.

If the argument location list includes the headers location the argument names will no longer be case insensitive and must match their title case names (see str.title()). Specifying location='headers' (not as a list) will retain case insensitivity.

Parser Inheritance

Often you will make a different parser for each resource you write. The problem with this is if parsers have arguments in common. Instead of rewriting arguments you can write a parent parser containing all the shared arguments and then extend the parser with copy(). You can also overwrite any argument in the parent with replace_argument(), or remove it completely with remove_argument(). For example:

  1. from flask_restful import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument('foo', type=int)
  4. parser_copy = parser.copy()
  5. parser_copy.add_argument('bar', type=int)
  6. # parser_copy has both 'foo' and 'bar'
  7. parser_copy.replace_argument('foo', required=True, location='json')
  8. # 'foo' is now a required str located in json, not an int as defined
  9. # by original parser
  10. parser_copy.remove_argument('foo')
  11. # parser_copy no longer has 'foo' argument

Error Handling

The default way errors are handled by the RequestParser is to abort on the first error that occurred. This can be beneficial when you have arguments that might take some time to process. However, often it is nice to have the errors bundled together and sent back to the client all at once. This behavior can be specified either at the Flask application level or on the specific RequestParser instance. To invoke a RequestParser with the bundling errors option, pass in the argument bundle_errors. For example

  1. from flask_restful import reqparse
  2. parser = reqparse.RequestParser(bundle_errors=True)
  3. parser.add_argument('foo', type=int, required=True)
  4. parser.add_argument('bar', type=int, required=True)
  5. # If a request comes in not containing both 'foo' and 'bar', the error that
  6. # will come back will look something like this.
  7. {
  8. "message": {
  9. "foo": "foo error message",
  10. "bar": "bar error message"
  11. }
  12. }
  13. # The default behavior would only return the first error
  14. parser = RequestParser()
  15. parser.add_argument('foo', type=int, required=True)
  16. parser.add_argument('bar', type=int, required=True)
  17. {
  18. "message": {
  19. "foo": "foo error message"
  20. }
  21. }

The application configuration key is “BUNDLE_ERRORS”. For example

  1. from flask import Flask
  2. app = Flask(__name__)
  3. app.config['BUNDLE_ERRORS'] = True

Warning

BUNDLE_ERRORS is a global setting that overrides the bundle_errors option in individual RequestParser instances.

Error Messages

Error messages for each field may be customized using the help parameter to Argument (and also RequestParser.add_argument).

If no help parameter is provided, the error message for the field will be the string representation of the type error itself. If help is provided, then the error message will be the value of help.

help may include an interpolation token, {error_msg}, that will be replaced with the string representation of the type error. This allows the message to be customized while preserving the original error

  1. from flask_restful import reqparse
  2. parser = reqparse.RequestParser()
  3. parser.add_argument(
  4. 'foo',
  5. choices=('one', 'two'),
  6. help='Bad choice: {error_msg}'
  7. )
  8. # If a request comes in with a value of "three" for `foo`:
  9. {
  10. "message": {
  11. "foo": "Bad choice: three is not a valid choice",
  12. }
  13. }

Logo

Table of Contents

Related Topics

This Page

Quick search