-
Notifications
You must be signed in to change notification settings - Fork 42
19 API Users and filters
Our API can return lists of notes and details about them, but it's not easy to search it currently. We can add in filtering with just a few lines of code.
We'll also add in users at the same time so that we can use the note owners in the filter.
In note/api/resources.py
, add a new API resource:
from django.contrib.auth.models import User
from tastypie import fields
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from tastypie.authorization import Authorization
...
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
allowed_methods = ['get']
resource_name = 'user'
excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
filtering = {
'username': ALL,
}
Note how we restricted some User fields. We don't want to make the users emails and other private information publicly accessible.
In elevennote/urls.py
make sure to import your UserResource and register it the same way you did with the NoteResource.
Now update your note resource to add filtering.
class NoteResource(ModelResource): owner = fields.ForeignKey(UserResource, 'owner')
class Meta:
queryset = Note.objects.all()
allowed_methods = ['get']
filtering = {
'owner': ALL_WITH_RELATIONS,
'pub_date': ['exact', 'lt', 'lte', 'gte', 'gt'],
}
Now you can filter by username like this (swap [USERNAME]
with scot
or whatever user you have defined):
http://localhost:8000/api/v1/note/?format=json&owner__username=[USERNAME]
You can also now see users info at:
Schema: http://localhost:8000/api/v1/user/schema/?format=json
List: http://localhost:8000/api/v1/user/?format=json
These API calls are open to anyone, there is no authentication taking place. This isn't too dangerous because we restricted the allowed methods to only 'GET'. But be careful with an open API. If you allow POST, PUT, or DELETE then anyone can trash your data.
In the next chapter we'll show how to restrict your API to authenticated users.