Skip to main content
This quickstart guide will walk you through building a simple API that allows admin users to view and edit users and groups in the system.

Project Setup

1

Create project directory

First, create a new directory for your project and set up a virtual environment:
# Create the project directory
mkdir tutorial
cd tutorial

# Create a virtual environment
python3 -m venv .venv
source .venv/bin/activate
2

Install dependencies

Install Django and Django REST Framework:
pip install djangorestframework
Installing djangorestframework automatically installs Django as a dependency.
3

Create Django project

Set up a new Django project with a single application:
# Create project (note the trailing '.' character)
django-admin startproject tutorial .

# Create app inside the project directory
cd tutorial
django-admin startapp quickstart
cd ..
4

Initialize database

Sync your database and create an admin user:
python manage.py migrate
python manage.py createsuperuser --username admin --email [email protected]
You’ll be prompted to enter a password for the admin user.

Build the API

Now let’s create a simple API for managing users and groups.

Configure Settings

Add 'rest_framework' to INSTALLED_APPS in tutorial/settings.py:
tutorial/settings.py
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "rest_framework",
]

# Optional: Configure pagination
REST_FRAMEWORK = {
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
    "PAGE_SIZE": 10,
}

Create Serializers

Create a new file tutorial/quickstart/serializers.py:
tutorial/quickstart/serializers.py
from django.contrib.auth.models import Group, User
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ["url", "username", "email", "groups"]


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ["url", "name"]
We’re using HyperlinkedModelSerializer which uses hyperlinks to represent relationships between resources. This is good RESTful design.

Create ViewSets

Open tutorial/quickstart/views.py and add the following:
tutorial/quickstart/views.py
from django.contrib.auth.models import Group, User
from rest_framework import permissions, viewsets

from tutorial.quickstart.serializers import GroupSerializer, UserSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by("-date_joined")
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all().order_by("name")
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]
Instead of writing multiple views, we’re grouping common behavior into ViewSets. This keeps the code organized and concise.

Configure URLs

Update tutorial/urls.py to wire up the API URLs:
tutorial/urls.py
from django.urls import include, path
from rest_framework import routers

from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r"users", views.UserViewSet)
router.register(r"groups", views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path("", include(router.urls)),
    path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
]
By using viewsets with a router, we can automatically generate the URL configuration for our API.

Test Your API

1

Start the development server

python manage.py runserver
2

Access the browsable API

Open your browser and navigate to:
http://127.0.0.1:8000/
You’ll see the browsable API interface showing your users and groups endpoints.
Use the Login control in the top right corner to authenticate with the admin credentials you created earlier.
3

Test with command-line tools

You can also interact with the API using command-line tools like curl:
# List all users
curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/

# Response:
# {
#     "count": 1,
#     "next": null,
#     "previous": null,
#     "results": [
#         {
#             "url": "http://127.0.0.1:8000/users/1/",
#             "username": "admin",
#             "email": "[email protected]",
#             "groups": []
#         }
#     ]
# }

What You’ve Built

Congratulations! You’ve created a fully functional REST API with:

Browsable API

An interactive, web-browsable interface for your API

Authentication

Login and permission controls

Serialization

Automatic JSON serialization of Django models

CRUD Operations

Create, Read, Update, and Delete functionality

Understanding the Code

Serializers

Serializers convert complex data types (like Django models) into Python data types that can be easily rendered into JSON:
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ["url", "username", "email", "groups"]

ViewSets

ViewSets combine the logic for multiple related views into a single class:
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all().order_by("-date_joined")
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]
ModelViewSet provides default implementations for:
  • .list() - List all users
  • .create() - Create a new user
  • .retrieve() - Get a specific user
  • .update() - Update a user
  • .partial_update() - Partially update a user
  • .destroy() - Delete a user

Routers

Routers automatically generate URL patterns for your viewsets:
router = routers.DefaultRouter()
router.register(r"users", views.UserViewSet)
router.register(r"groups", views.GroupViewSet)
This creates the following URL patterns:
  • GET /users/ - List users
  • POST /users/ - Create user
  • GET /users/{id}/ - Retrieve user
  • PUT /users/{id}/ - Update user
  • PATCH /users/{id}/ - Partial update
  • DELETE /users/{id}/ - Delete user

Next Steps

Tutorial

Learn REST framework in depth with our step-by-step tutorial

API Guide

Explore the complete API reference

Serializers

Deep dive into serialization

ViewSets & Routers

Master advanced view patterns

Build docs developers (and LLMs) love