Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python Quiz
Next article icon

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:

  1. Serialization: Convert complex data like Djangomodels/querysets intoJSONorXMLformat.
  2. Viewsets: Define views that handleAPI requests andresponses.
  3. 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:

Python
fromdjango.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:

Python
fromrest_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:

Python
fromrest_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:

Python
fromdjango.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:

  1. See a list of books (empty at first)
  2. Use POST requests to add new books
  3. 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 MethodEndpoint URLDescription
GEThttp://127.0.0.1:8000/api/books/List all books
POSThttp://127.0.0.1:8000/api/books/Create a new book
GEThttp://127.0.0.1:8000/api/books/{id}/Retrieve a book by its ID
PUThttp://127.0.0.1:8000/api/books/{id}/Update a book by its ID
DELETEhttp://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:

django37
Snapshot after adding three entries

Let's look at the options we get when we navigate the/book/{id}/ with id of some book:

Create-a-basic-API-with-Django-REST-Framework
Django REST Framework

In the above snapshot, we are getting the options of performing all theCRUDoperations, which means out app is working fine.


Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp