Problem
As recommended in the blogpost Best Practices for Designing a Pragmatic RESTful API, I would like to add a fields
query parameter to a Django Rest Framework based API which enables the user to select only a subset of fields per resource.
Example
Serializer:
class IdentitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Identity
fields = ('id', 'url', 'type', 'data')
A regular query would return all fields.
GET /identities/
[
{
"id": 1,
"url": "http://localhost:8000/api/identities/1/",
"type": 5,
"data": "John Doe"
},
...
]
A query with the fields
parameter should only return a subset of the fields:
GET /identities/?fields=id,data
[
{
"id": 1,
"data": "John Doe"
},
...
]
A query with invalid fields should either ignore the invalid fields or throw a client error.
Goal
Is this possible out of the box somehow? If not, what's the simplest way to implement this? Is there a 3rd party package around that does this already?
If you want something flexible like GraphQL, you can use django-restql. It supports nested data (both flat and iterable).
Example
A regular request returns all fields.
GET /users
A request with the
query
parameter on the other hand returns only a subset of the fields:GET /users/?query={id, username}
With django-restql you can access nested fields of any level. E.g
GET /users/?query={id, username, date_joined{year}}
For iterable nested fields, E.g groups on users.
GET /users/?query={id, username, groups{id, name}}
Configure a new pagination serializer class
Make dynamic serializer
Last, use a homemage mixin for your APIViews
Request
Now, when you request a resource, you can add a parameter
fields
to show only specified fields in url./?fields=field1,field2
You can find a reminder here : https://gist.github.com/Kmaschta/e28cf21fb3f0b90c597a