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…
Section overview
5 resourcesIntroduces 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
- Create a new Django project and application for a different type of data (e.g.,
Bookwith fieldstitle,author, andyear_published). - Add a new field to the
Studentmodel (e.g.,email) and update the serializer, view, and URL route accordingly. - Create a new view that only handles
GETrequests and returns a specific subset of the data.
Additional Resources
- Django REST Framework documentation
- Django documentation
- MDN Web Docs for a more in-depth Django tutorial.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article