Extending Flask-RESTful

We realize that everyone has different needs in a REST framework. Flask-RESTful tries to be as flexible as possible, but sometimes you might find that the builtin functionality is not enough to meet your needs. Flask-RESTful has a few different extension points that can help in that case.

Content Negotiation

Out of the box, Flask-RESTful is only configured to support JSON. We made this decision to give API maintainers full control of over API format support; so a year down the road you don’t have to support people using the CSV representation of your API you didn’t even know existed. To add additional mediatypes to your API, you’ll need to declare your supported representations on the Api object.

  1. app = Flask(__name__)
  2. api = Api(app)
  3. @api.representation('application/json')
  4. def output_json(data, code, headers=None):
  5. resp = make_response(json.dumps(data), code)
  6. resp.headers.extend(headers or {})
  7. return resp

These representation functions must return a Flask Response object.

Note

Flask-RESTful uses the json module from the Python standard library instead of flask.json because the Flask JSON serializer includes serializtion capabilities which are not in the JSON spec. If your application needs these customizations, you can replace the default JSON representation with one using the Flask JSON module as described above.

It is possible to configure how the default Flask-RESTful JSON representation will format JSON by providing a RESTFUL_JSON attribute on the application configuration. This setting is a dictionary with keys that correspond to the keyword arguments of json.dumps().

  1. class MyConfig(object):
  2. RESTFUL_JSON = {'separators': (', ', ': '),
  3. 'indent': 2,
  4. 'cls': MyCustomEncoder}

Note

If the application is running in debug mode (app.debug = True) and either sort_keys or indent are not declared in the RESTFUL_JSON configuration setting, Flask-RESTful will provide defaults of True and 4 respectively.

Custom Fields & Inputs

One of the most common additions to Flask-RESTful is to define custom types or fields based on your own data types.

Fields

Custom output fields let you perform your own output formatting without having to modify your internal objects directly. All you have to do is subclass Raw and implement the format() method:

  1. class AllCapsString(fields.Raw):
  2. def format(self, value):
  3. return value.upper()
  4. # example usage
  5. fields = {
  6. 'name': fields.String,
  7. 'all_caps_name': AllCapsString(attribute=name),
  8. }

Inputs

For parsing arguments, you might want to perform custom validation. Creating your own input types lets you extend request parsing with ease.

  1. def odd_number(value):
  2. if value % 2 == 0:
  3. raise ValueError("Value is not odd")
  4. return value

The request parser will also give you access to the name of the argument for cases where you want to reference the name in the error message.

  1. def odd_number(value, name):
  2. if value % 2 == 0:
  3. raise ValueError("The parameter '{}' is not odd. You gave us the value: {}".format(name, value))
  4. return value

You can also convert public parameter values to internal representations:

  1. # maps the strings to their internal integer representation
  2. # 'init' => 0
  3. # 'in-progress' => 1
  4. # 'completed' => 2
  5. def task_status(value):
  6. statuses = [u"init", u"in-progress", u"completed"]
  7. return statuses.index(value)

Then you can use these custom input types in your RequestParser:

  1. parser = reqparse.RequestParser()
  2. parser.add_argument('OddNumber', type=odd_number)
  3. parser.add_argument('Status', type=task_status)
  4. args = parser.parse_args()

Response Formats

To support other representations (xml, csv, html), you can use the representation() decorator. You need to have a reference to your API.

  1. api = Api(app)
  2. @api.representation('text/csv')
  3. def output_csv(data, code, headers=None):
  4. pass
  5. # implement csv output!

These output functions take three parameters, data, code, and headers

data is the object you return from your resource method, code is the HTTP status code that it expects, and headers are any HTTP headers to set in the response. Your output function should return a flask.Response object.

  1. def output_json(data, code, headers=None):
  2. """Makes a Flask response with a JSON encoded body"""
  3. resp = make_response(json.dumps(data), code)
  4. resp.headers.extend(headers or {})
  5. return resp

Another way to accomplish this is to subclass the Api class and provide your own output functions.

  1. class Api(restful.Api):
  2. def __init__(self, *args, **kwargs):
  3. super(Api, self).__init__(*args, **kwargs)
  4. self.representations = {
  5. 'application/xml': output_xml,
  6. 'text/html': output_html,
  7. 'text/csv': output_csv,
  8. 'application/json': output_json,
  9. }

Resource Method Decorators

There is a property on the Resource class called method_decorators. You can subclass the Resource and add your own decorators that will be added to all method functions in resource. For instance, if you want to build custom authentication into every request.

  1. def authenticate(func):
  2. @wraps(func)
  3. def wrapper(*args, **kwargs):
  4. if not getattr(func, 'authenticated', True):
  5. return func(*args, **kwargs)
  6. acct = basic_authentication() # custom account lookup function
  7. if acct:
  8. return func(*args, **kwargs)
  9. restful.abort(401)
  10. return wrapper
  11. class Resource(restful.Resource):
  12. method_decorators = [authenticate] # applies to all inherited resources

Alternatively, you can specify a dictionary of iterables that map to HTTP methods and the decorators will only apply to matching requests.

  1. def cache(f):
  2. @wraps(f)
  3. def cacher(*args, **kwargs):
  4. # caching stuff
  5. return cacher
  6. class MyResource(restful.Resource):
  7. method_decorators = {'get': [cache]}
  8. def get(self, *args, **kwargs):
  9. return something_interesting(*args, **kwargs)
  10. def post(self, *args, **kwargs):
  11. return create_something(*args, **kwargs)

In this case, the caching decorator would only apply to the GET request and not the POST request.

Since Flask-RESTful Resources are actually Flask view objects, you can also use standard flask view decorators.

Custom Error Handlers

Error handling is a tricky problem. Your Flask application may be wearing multiple hats, yet you want to handle all Flask-RESTful errors with the correct content type and error syntax as your 200-level requests.

Flask-RESTful will call the handle_error() function on any 400 or 500 error that happens on a Flask-RESTful route, and leave other routes alone. You may want your app to return an error message with the correct media type on 404 Not Found errors; in which case, use the catch_all_404s parameter of the Api constructor.

  1. app = Flask(__name__)
  2. api = flask_restful.Api(app, catch_all_404s=True)

Then Flask-RESTful will handle 404s in addition to errors on its own routes.

Sometimes you want to do something special when an error occurs - log to a file, send an email, etc. Use the got_request_exception() method to attach custom error handlers to an exception.

  1. def log_exception(sender, exception, **extra):
  2. """ Log an exception to our logging framework """
  3. sender.logger.debug('Got exception during processing: %s', exception)
  4. from flask import got_request_exception
  5. got_request_exception.connect(log_exception, app)

Define Custom Error Messages

You may want to return a specific message and/or status code when certain errors are encountered during a request. You can tell Flask-RESTful how you want to handle each error/exception so you won’t have to fill your API code with try/except blocks.

  1. errors = {
  2. 'UserAlreadyExistsError': {
  3. 'message': "A user with that username already exists.",
  4. 'status': 409,
  5. },
  6. 'ResourceDoesNotExist': {
  7. 'message': "A resource with that ID no longer exists.",
  8. 'status': 410,
  9. 'extra': "Any extra information you want.",
  10. },
  11. }

Including the ‘status’ key will set the Response’s status code. If not specified it will default to 500.

Once your errors dictionary is defined, simply pass it to the Api constructor.

  1. app = Flask(__name__)
  2. api = flask_restful.Api(app, errors=errors)

Logo

Table Of Contents

Related Topics

This Page

Quick search