Output Fields

Flask-RESTful provides an easy way to control what data you actually render in your response. With the fields module, you can use whatever objects (ORM models/custom classes/etc.) you want in your resource. fields also lets you format and filter the response so you don’t have to worry about exposing internal data structures.

It’s also very clear when looking at your code what data will be rendered and how it will be formatted.

Basic Usage

You can define a dict or OrderedDict of fields whose keys are names of attributes or keys on the object to render, and whose values are a class that will format & return the value for that field. This example has three fields: two are String and one is a DateTime, formatted as an RFC 822 date string (ISO 8601 is supported as well)

  1. from flask_restful import Resource, fields, marshal_with
  2. resource_fields = {
  3. 'name': fields.String,
  4. 'address': fields.String,
  5. 'date_updated': fields.DateTime(dt_format='rfc822'),
  6. }
  7. class Todo(Resource):
  8. @marshal_with(resource_fields, envelope='resource')
  9. def get(self, **kwargs):
  10. return db_get_todo() # Some function that queries the db

This example assumes that you have a custom database object (todo) that has attributes name, address, and date_updated. Any additional attributes on the object are considered private and won’t be rendered in the output. An optional envelope keyword argument is specified to wrap the resulting output.

The decorator marshal_with is what actually takes your data object and applies the field filtering. The marshalling can work on single objects, dicts, or lists of objects.

Note

marshal_with is a convenience decorator, that is functionally equivalent to

  1. class Todo(Resource):
  2. def get(self, **kwargs):
  3. return marshal(db_get_todo(), resource_fields), 200

This explicit expression can be used to return HTTP status codes other than 200 along with a successful response (see abort() for errors).

Renaming Attributes

Often times your public facing field name is different from your internal field name. To configure this mapping, use the attribute keyword argument.

  1. fields = {
  2. 'name': fields.String(attribute='private_name'),
  3. 'address': fields.String,
  4. }

A lambda (or any callable) can also be specified as the attribute

  1. fields = {
  2. 'name': fields.String(attribute=lambda x: x._private_name),
  3. 'address': fields.String,
  4. }

Nested properties can also be accessed with attribute

  1. fields = {
  2. 'name': fields.String(attribute='people_list.0.person_dictionary.name'),
  3. 'address': fields.String,
  4. }

Default Values

If for some reason your data object doesn’t have an attribute in your fields list, you can specify a default value to return instead of None.

  1. fields = {
  2. 'name': fields.String(default='Anonymous User'),
  3. 'address': fields.String,
  4. }

Custom Fields & Multiple Values

Sometimes you have your own custom formatting needs. You can subclass the fields.Raw class and implement the format function. This is especially useful when an attribute stores multiple pieces of information. e.g. a bit-field whose individual bits represent distinct values. You can use fields to multiplex a single attribute to multiple output values.

This example assumes that bit 1 in the flags attribute signifies a “Normal” or “Urgent” item, and bit 2 signifies “Read” or “Unread”. These items might be easy to store in a bitfield, but for a human readable output it’s nice to convert them to seperate string fields.

  1. class UrgentItem(fields.Raw):
  2. def format(self, value):
  3. return "Urgent" if value & 0x01 else "Normal"
  4. class UnreadItem(fields.Raw):
  5. def format(self, value):
  6. return "Unread" if value & 0x02 else "Read"
  7. fields = {
  8. 'name': fields.String,
  9. 'priority': UrgentItem(attribute='flags'),
  10. 'status': UnreadItem(attribute='flags'),
  11. }

Url & Other Concrete Fields

Flask-RESTful includes a special field, fields.Url, that synthesizes a uri for the resource that’s being requested. This is also a good example of how to add data to your response that’s not actually present on your data object.:

  1. class RandomNumber(fields.Raw):
  2. def output(self, key, obj):
  3. return random.random()
  4. fields = {
  5. 'name': fields.String,
  6. # todo_resource is the endpoint name when you called api.add_resource()
  7. 'uri': fields.Url('todo_resource'),
  8. 'random': RandomNumber,
  9. }

By default fields.Url returns a relative uri. To generate an absolute uri that includes the scheme, hostname and port, pass the keyword argument absolute=True in the field declaration. To override the default scheme, pass the scheme keyword argument:

  1. fields = {
  2. 'uri': fields.Url('todo_resource', absolute=True),
  3. 'https_uri': fields.Url('todo_resource', absolute=True, scheme='https')
  4. }

Complex Structures

You can have a flat structure that marshal() will transform to a nested structure

  1. >>> from flask_restful import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> resource_fields = {'name': fields.String}
  5. >>> resource_fields['address'] = {}
  6. >>> resource_fields['address']['line 1'] = fields.String(attribute='addr1')
  7. >>> resource_fields['address']['line 2'] = fields.String(attribute='addr2')
  8. >>> resource_fields['address']['city'] = fields.String
  9. >>> resource_fields['address']['state'] = fields.String
  10. >>> resource_fields['address']['zip'] = fields.String
  11. >>> data = {'name': 'bob', 'addr1': '123 fake street', 'addr2': '', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
  12. >>> json.dumps(marshal(data, resource_fields))
  13. '{"name": "bob", "address": {"line 1": "123 fake street", "line 2": "", "state": "NY", "zip": "10468", "city": "New York"}}'

Note

The address field doesn’t actually exist on the data object, but any of the sub-fields can access attributes directly from the object as if they were not nested.

List Field

You can also unmarshal fields as lists

  1. >>> from flask_restful import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> resource_fields = {'name': fields.String, 'first_names': fields.List(fields.String)}
  5. >>> data = {'name': 'Bougnazal', 'first_names' : ['Emile', 'Raoul']}
  6. >>> json.dumps(marshal(data, resource_fields))
  7. >>> '{"first_names": ["Emile", "Raoul"], "name": "Bougnazal"}'

Advanced : Nested Field

While nesting fields using dicts can turn a flat data object into a nested response, you can use Nested to unmarshal nested data structures and render them appropriately.

  1. >>> from flask_restful import fields, marshal
  2. >>> import json
  3. >>>
  4. >>> address_fields = {}
  5. >>> address_fields['line 1'] = fields.String(attribute='addr1')
  6. >>> address_fields['line 2'] = fields.String(attribute='addr2')
  7. >>> address_fields['city'] = fields.String(attribute='city')
  8. >>> address_fields['state'] = fields.String(attribute='state')
  9. >>> address_fields['zip'] = fields.String(attribute='zip')
  10. >>>
  11. >>> resource_fields = {}
  12. >>> resource_fields['name'] = fields.String
  13. >>> resource_fields['billing_address'] = fields.Nested(address_fields)
  14. >>> resource_fields['shipping_address'] = fields.Nested(address_fields)
  15. >>> address1 = {'addr1': '123 fake street', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
  16. >>> address2 = {'addr1': '555 nowhere', 'city': 'New York', 'state': 'NY', 'zip': '10468'}
  17. >>> data = { 'name': 'bob', 'billing_address': address1, 'shipping_address': address2}
  18. >>>
  19. >>> json.dumps(marshal_with(data, resource_fields))
  20. '{"billing_address": {"line 1": "123 fake street", "line 2": null, "state": "NY", "zip": "10468", "city": "New York"}, "name": "bob", "shipping_address": {"line 1": "555 nowhere", "line 2": null, "state": "NY", "zip": "10468", "city": "New York"}}'

This example uses two Nested fields. The Nested constructor takes a dict of fields to render as sub-fields. The important difference between the Nested constructor and nested dicts (previous example), is the context for attributes. In this example, billing_address is a complex object that has its own fields and the context passed to the nested field is the sub-object instead of the original data object. In other words: data.billing_address.addr1 is in scope here, whereas in the previous example data.addr1 was the location attribute. Remember: Nested and List objects create a new scope for attributes.

Use Nested with List to marshal lists of more complex objects:

  1. user_fields = {
  2. 'id': fields.Integer,
  3. 'name': fields.String,
  4. }
  5. user_list_fields = {
  6. fields.List(fields.Nested(user_fields)),
  7. }

Logo

Table of Contents

Related Topics

This Page

Quick search