Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models asRESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.
Before creating an API, there are three main steps to understand:
- Serialization: Convert complex data like Djangomodels/querysets intoJSONorXMLformat.
- Viewsets: Define views that handleAPI requests andresponses.
- URL Routing: MapURLsto yourAPIviews so they can be accessed by clients.
This article will teach you how to implement Django REST framework to easily create API endpoints by building a simpleCRUD(Create, Read, Update, Delete) API for aBook modelwith three fields:title,author andpublish_date.
Refer to the following articles to check how to create a project and an app in Django.
Step 1: Add DRF to Installed Apps
In yoursettings.py, add 'rest_framework' and you 'app' toINSTALLED_APPSto enableDRFin your Django project:
Python# Application definitionINSTALLED_APPS=['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework','app']
Also make sure to install Django restframework module if it isn't already installed using command:
pip install djangorestframework
Step 2: Create the Book Model
Inapp/models.py, define the Book model with three fields:
Pythonfromdjango.dbimportmodelsclassBook(models.Model):title=models.CharField(max_length=200)author=models.CharField(max_length=100)publish_date=models.DateField()def__str__(self):returnself.title
- CharFieldis used for short text (title, author).
- DateFieldstores the date when the book was published.
- __str__method returns a human-readable representation of each book instance.
Step 3: Create a Serializer
Serializers convert model instances into JSON andvalidate incoming JSONdata. Createapp/serializers.py:
Pythonfromrest_frameworkimportserializersfrom.modelsimportBookclassBookSerializer(serializers.ModelSerializer):classMeta:model=Bookfields=['id','title','author','publish_date']
- ModelSerializerautomatically generates fields based on the model.
- fieldstuple specifies which model fields to expose via the API.
- id field (primary key) is included to uniquely identify each record.
Step 4: Define a ViewSet
ViewSets provideCRUDoperations in one place. Inapp/views.py:
Pythonfromrest_frameworkimportviewsetsfrom.modelsimportBookfrom.serializersimportBookSerializerclassBookViewSet(viewsets.ModelViewSet):queryset=Book.objects.all()serializer_class=BookSerializer
- ModelViewSetautomatically provides list, retrieve, create, update and destroy actions.
- querysetdefines the set of objects available via the API.
- serializer_classtells DRF how toserialize/deserialize the Book data.
Step 5: Configure URLs with a Router
DRF routers automatically generate URL patterns for your ViewSets. Createapp/urls.py:
Pythonfromdjango.urlsimportpath,includefromrest_framework.routersimportDefaultRouterfrom.viewsimportBookViewSetrouter=DefaultRouter()router.register(r'books',BookViewSet)urlpatterns=[path('',include(router.urls)),]
UsingDefaultRouter, youdon’t need to manually define eachURLforCRUDoperations. It automatically creates standardRESTfulendpoints like:
- GET /books/(list all books)
- POST /books/ (create new book)
- GET /books/{id}/(retrieve a single book)
- PUT /books/{id}/ (update a book)
- DELETE /books/{id}/(delete a book)
Including these URLs in your mainprojectName/urls.py will expose the API.
Step 6: Migrate and Run the Server
Run the following commands to create your database tables and start the server:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
You can now:
- See a list of books (empty at first)
- Use POST requests to add new books
- Access individual books, update or delete them using standard HTTP methods
Accessing the API Endpoints:
Because in yourprojectName/urls.py you included your app’s URLs with the prefixapi/, all your API endpoints will be accessed through URLs starting with/api/.
For example, the DefaultRouter in yourapp/urls.py registered theBookViewSetwith the route books. So, the endpoints you can use are:
HTTP Method | Endpoint URL | Description |
---|
GET | http://127.0.0.1:8000/api/books/ | List all books |
---|
POST | http://127.0.0.1:8000/api/books/ | Create a new book |
---|
GET | http://127.0.0.1:8000/api/books/{id}/ | Retrieve a book by its ID |
---|
PUT | http://127.0.0.1:8000/api/books/{id}/ | Update a book by its ID |
---|
DELETE | http://127.0.0.1:8000/api/books/{id}/ | Delete a book by its ID |
---|
Note:
Replace {id} with the actual bookIDyou want toretrieve,update ordelete.
The/api/prefix is required because you included your app URLs under path('api/', include('app.urls')) in the mainurls.py.
Output:
Below is the snapshot of the/books/ endpoint after adding some entries:
Snapshot after adding three entriesLet's look at the options we get when we navigate the/book/{id}/ with id of some book:
Django REST FrameworkIn the above snapshot, we are getting the options of performing all theCRUDoperations, which means out app is working fine.