Django / Django REST Framework (DRF)

Building REST APIs with Django REST Framework

This tutorial will guide you through the process of building a RESTful API using Django REST Framework. You'll learn how to create a new Django project, a new application within t…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Introduces Django REST Framework (DRF) for building RESTful APIs with Django.

Building REST APIs with Django REST Framework

1. Introduction

This tutorial aims to guide you through the process of building a RESTful API using Django REST Framework. By the end of this guide, you will have a fully functional API that can create, retrieve, update, and delete data from a database.

What you will learn:
- How to create a new Django project
- How to create a new application within the project
- How to use serializers to transform Django models into JSON

Prerequisites:
- Basic understanding of Python and Django
- Django and Django REST Framework installed on your system

2. Step-by-Step Guide

Creating a new Django project and application

First, we'll create a new Django project using the command django-admin startproject projectname. Replace projectname with the name of your project.

Next, navigate to the newly created project directory and create a new application using the command python manage.py startapp appname. Replace appname with your preferred application name.

Creating a model

In Django, a model is a Python class that represents a database table. In your application's models.py file, you can create a model for the data your API will handle. For example:

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    grade = models.IntegerField()

This creates a Student table with name, age, and grade fields.

Serializers

Serializers allow complex data types, such as Django models, to be converted to Python datatypes that can then be easily rendered into JSON. In your application's directory, create a new file named serializers.py, and add the following code:

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ('name', 'age', 'grade')

This code creates a serializer for the Student model, specifying the fields to be included in the serialized representation.

Creating Views

In Django, a view is a Python function that takes a web request and returns a web response. Django REST Framework provides two styles of views: function-based views and class-based views. For this tutorial, we'll use class-based views.

In your application's views.py file, add the following code:

from rest_framework import viewsets
from .serializers import StudentSerializer
from .models import Student

class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all().order_by('name')
    serializer_class = StudentSerializer

This code creates a view that handles GET, POST, PUT, and DELETE requests for the Student model.

Routing

Finally, we need to create a URL route for our view. In your application's directory, create a new file named urls.py, and add the following code:

from django.urls import include, path
from rest_framework.routers import DefaultRouter
from .views import StudentViewSet

router = DefaultRouter()
router.register(r'students', StudentViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

This code sets up a route for students that maps to our StudentViewSet view.

3. Code Examples

Let's demonstrate how to make requests to our API using curl.

Creating a new student

To create a new student, we'll make a POST request to the students endpoint:

curl -X POST -H "Content-Type: application/json" -d '{"name":"John", "age":18, "grade":12}' http://localhost:8000/students/

Retrieving all students

To retrieve all students, we'll make a GET request to the students endpoint:

curl -X GET http://localhost:8000/students/

Updating a student

To update a student, we'll make a PUT request to the students/{id} endpoint:

curl -X PUT -H "Content-Type: application/json" -d '{"name":"John", "age":19, "grade":12}' http://localhost:8000/students/1/

Deleting a student

To delete a student, we'll make a DELETE request to the students/{id} endpoint:

curl -X DELETE http://localhost:8000/students/1/

4. Summary

In this tutorial, we created a new Django project and application, created a model for our data, used serializers to transform our model into JSON, created a view to handle web requests, and set up a URL route for our view.

To continue learning, you could explore Django's authentication and permission systems, which allow you to control who can access your API.

5. Practice Exercises

  1. Create a new Django project and application for a different type of data (e.g., Book with fields title, author, and year_published).
  2. Add a new field to the Student model (e.g., email) and update the serializer, view, and URL route accordingly.
  3. Create a new view that only handles GET requests and returns a specific subset of the data.

Additional Resources

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Hex to Decimal Converter

Convert between hexadecimal and decimal values.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help