If you are new to Django and need to create RESTful APIs, use Django Rest Framework (avoid Piston or Tastypie).
It’s fairly easy to get REST APIs up and running, but things can get a little confusing when you need to customize
Two problems I seem to solve a lot are adding filters via query parameters and excluding fields via query parameters.
Let’s say you have an API call that lists all the buildings in your database:
Now lets say I want to be able to filter out only data points which have submission=120. Unfortunately DRF
does not offer this functionality out of the box. To do this, you need to add some code to APIView:
As you can see, I am overriding get_queryset and checking to see if the submission get query parameter
is being passed. If it is, then I return a filter queryset rather than the queryset containing all objects
in the database.
Sometimes it is also useful to be able to filter the json responses. Say I only way to see the id, latitude, and
longitude from the above json response. You can easily provide this functionality by updating your Serializer
As you can see, here I am overriding the BuildingSerializer constructor. Again, I am checking to see if fields query
parameter is being passed, and if it is, I filter the response by the fields that are provided (comma separated list). This
code will enable API calls as follows: