Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating a Django Project
- Creating a Django App
- Defining Models
- Serializers
- Views
- URL Routing
- Testing the API
- Conclusion
Introduction
In this tutorial, we will learn how to build a REST API using Django Rest Framework. Django Rest Framework is a powerful and flexible framework for building web APIs. By the end of this tutorial, you will have a functioning REST API that you can use to perform CRUD operations on a database.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of the Python programming language and some knowledge of web development concepts. Additionally, you should have the following software installed on your machine:
- Python 3.x
- Django
- Django Rest Framework
If you need help installing Python or any of the mentioned libraries, please refer to their respective documentation.
Setup
Before we start building the REST API, let’s make sure we have the necessary tools and libraries installed. Open your command line or terminal and run the following commands:
bash
pip3 install django
pip3 install djangorestframework
These commands will install Django and Django Rest Framework on your system.
Creating a Django Project
To create a new Django project, navigate to your desired directory and run the following command:
bash
django-admin startproject myproject
This will create a new folder called myproject
with the basic Django project structure.
Creating a Django App
In Django, an app is a self-contained module that encapsulates a specific functionality of a project. To create a new app, navigate to the project directory (myproject
in this case) and run the following command:
bash
python3 manage.py startapp myapp
This will create a new folder called myapp
inside the myproject
folder with the basic structure of a Django app.
Defining Models
Models in Django are Python classes that represent database tables. They provide an abstraction layer for interacting with the database. Open the models.py
file inside the myapp
folder and define the following model:
```python
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
``` In this example, we defined a model called `MyModel` with two fields: `name` and `description`. The `CharField` is used for short string fields, while the `TextField` is used for longer text fields.
Serializers
Serializers in Django Rest Framework are used to convert complex data types (such as Django model instances) into JSON or other content types that can be easily rendered into an API response. They also provide deserialization, allowing parsed data to be converted back into complex types after first validating the incoming data.
Create a new file called serializers.py
inside the myapp
folder and add the following code:
```python
from rest_framework import serializers
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = '__all__'
``` In this example, we created a serializer called `MyModelSerializer` that specifies the model it should be based on (`MyModel`) and includes all the fields of the model.
Views
Views in Django are responsible for handling HTTP requests and returning HTTP responses. Open the views.py
file inside the myapp
folder and add the following code:
```python
from rest_framework import viewsets
from .models import MyModel
from .serializers import MyModelSerializer
class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
``` In this example, we created a viewset called `MyModelViewSet` that inherits from `viewsets.ModelViewSet`. This class provides the default CRU[D] operations for the model. We specified the queryset to retrieve all objects from the `MyModel` model and the serializer class to use for serialization and deserialization.
URL Routing
URL routing in Django maps URLs to views. Open the urls.py
file inside the myproject
folder and add the following code:
```python
from django.urls import include, path
from rest_framework import routers
from myapp.views import MyModelViewSet
router = routers.DefaultRouter()
router.register(r'mymodels', MyModelViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
``` In this example, we created a router using the `DefaultRouter` class from `rest_framework.routers`. We registered the `MyModelViewSet` with the router, associating it with the `/mymodels` URL. Finally, we included the router URLs under the `/api/` URL.
Testing the API
Now that we have built our REST API, let’s test it. Start the development server by running the following command:
bash
python3 manage.py runserver
Open your web browser and navigate to http://localhost:8000/api/mymodels/
. You should see an empty API response.
To create a new object, send a POST request to http://localhost:8000/api/mymodels/
with the following JSON data:
json
{
"name": "Example",
"description": "This is an example"
}
To retrieve all objects, send a GET request to http://localhost:8000/api/mymodels/
.
To retrieve a specific object, send a GET request to http://localhost:8000/api/mymodels/<id>/
, where <id>
is the ID of the object.
To update an object, send a PUT request to http://localhost:8000/api/mymodels/<id>/
with the updated JSON data.
To delete an object, send a DELETE request to http://localhost:8000/api/mymodels/<id>/
.
Conclusion
In this tutorial, we learned how to build a REST API using Django Rest Framework. We covered the basics of setting up a Django project, creating an app, defining models, serializers, views, and URL routing. We also tested our API by performing CRUD operations on the database. Django Rest Framework provides a convenient and powerful way to build APIs in Django, allowing us to easily interact with our data through HTTP requests.
Now that you have a solid understanding of building REST APIs with Django Rest Framework, you can explore more advanced features, such as authentication, pagination, filtering, and more. Happy coding!