Django Rest Framework User Endpoint

DRF is an awesome tool for building web APIs the RESTful way: allowing you to interact with your database like so:

POST request to /api/articles with hdata payload to create new Article instance. PATCH request to /api/articles/1/ to partially update Article with pk of PUT request to /api/articles/1/ to completely replace Article with pk of 1. DELETE request to /api/articles/1/ to delete Article with pk of 1. GET request to /api/articles/1/ to retrieve Article with pk of 1. HEAD request to /api/articles/1/ to see if Article with pk of exists.

Gone are the days when we POST data like

POST request to /api/create_article with data payload POST request to /api/update_article with data payload POST request to /api/delete_article with data payload

The main advantage I see in RESTful is it gives us sane restrictions we must develop under and in doing so so helps organize our web apps – thereby avoid accidentally being “clever” and implementing a hard to maintain codebase. Since using DRF I found adding new features to my apps quicker, DRYer and with more readable code.

If you are a django user and interested in DRF, do pip install djangorestframework. For existing DRF users note make sure you have DRF >= 2.3.11, which now supports write_only_fields.

Defining the endpoint

Below we go through how to expose the User model to the web using a DRF endpoint to allow creating, updating, listing, deleting User objects. Note my folder structure is:


We need to create a view that will serve list and detail view of users:

from django.contrib.auth.models import User
from rest_framework viewsets
from rest_framework.permissions import AllowAny

from .permissions import IsStaffOrTargetUser

class UserView(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    model = User

    def get_permissions(self):
        # allow non-authenticated user to create via POST
        return (AllowAny() if self.request.method == 'POST'
                else IsStaffOrTargetUser()),

We need to be careful with permissions – we dont want users to be able to view other user objects if they are not staff members.

from rest_framework import permissions

class IsStaffOrTargetUser(permissions.BasePermission):
    def has_permission(self, request, view):
        # allow user to list all users if logged in user is staff
        return view.action == 'retrieve' or request.user.is_staff

    def has_object_permission(self, request, view, obj):
        # allow logged in user to view own details, allows staff to view all records
        return request.user.is_staff or obj == request.user

Next we define the serializer that will serialize Querysets and objects to JSON. We need to be careful on create of User object to handle passwords correctly, and on read not to serialize and return the password to the client.

from django.contrib.auth.models import User
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('password', 'first_name', 'last_name', 'email',)
        write_only_fields = ('password',)
        read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined',)

    def restore_object(self, attrs, instance=None):
        # call set_password on user object. Without this
        # the password will be stored in plain text.
        user = super(UserSerializer, self).restore_object(attrs, instance)
        return user

Now register the endpoint in the app’s

from django.conf.urls import patterns, url, include
from rest_framework import routers

from . import api

router = routers.DefaultRouter()
router.register(r'accounts', api.views.UserView, 'list')

urlpatterns = patterns(
    url(r'^api/', include(router.urls)),


Using the endpoint

Below are examples of calling the endpoint using jQuery, showing the request and the data returned.

Create new user

var data = {username: '', password: '****', ...};
$.post('/api/accounts/', data).done(function(data){
{first_name: "New"
 last_name: "User",
 email: "",

Update user details

var data = {email: ''};
$.ajax({url: '/api/accounts/4', type: 'patch', data: data}).done(function(data){
{first_name: "New"
 last_name: "User",
 email: "",

List all users when logged in as staff

[{first_name: "Richard"
  last_name: "Tier"
  email: "",
  id: 1},
{first_name: "John"
 last_name: "Doe",
 email: "",
 id: 2},
{first_name: "Jane"
 last_name: "Doe",
 email: "",
 id: 3}];

Retrieve own record when logged in as

{first_name: "John"
 last_name: "Doe",
 email: "",
 id: 2}

Retrieve’s record when NOT logged in as staff member and NOT user

{detail: "You do not have permission to perform this action."}

In a follow up post we cover checking username and password using DRF.


22 thoughts on “Django Rest Framework User Endpoint

  1. Pingback: Richard Tier ~
  2. Great post my friend, help me a lot… I’m new on django and django rest framework now… maybe you can help me… I have a models called UserProfile with a OneToOneField to auth.User. Now, I need to create a new instance of userprofile when users craete a new user using the api… ¿how can I create this new instance?¿in the view?
    Something like:
    Thankyou, great post….

  3. Thanks for the post, would you mind showing how to upgrade to DRF 3? restore_object has been replaced with update and create for example.

  4. А good thought-out guide, thanks! I used DRF 3, so i ran into some troubles:
    – get_permissions() must return tuple, so:
    def get_permissions(self):
    #allow non-authenticated user to create via POST
    return (AllowAny() if self.request.method == ‘POST’ else IsStaffOrTargetUser(),)

    – ModelViewSet must have queryset property like:

    from django.contrib.auth import get_user_model
    class UserViewSet(viewsets.ModelViewSet):
    queryset = get_user_model().objects

    – to mark fields as write-only serializer must have “extra_kwargs” property like:
    extra_kwargs = {
    ‘password’: {‘write_only’: True},

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s