Creating Django Rest API Part-1

Today we will create a basic Rest API in Django. Suppose you have a project with products app. In this app, a model is given with the class name Product. The coding of the is

from django.db import models

# Create your models here.
class Product(models.Model):
    productname = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=15, decimal_places=2)

    def __str__(self):
        return self.productname

ok, now will create a rest api for the app products

Step-1: Install djangorestframework

pip install djangorestframework

Step-2: Create an app name “api”

python startapp api

Step-3: create a file named and the write the below code

from rest_framework import serializers
from products.models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product 
        # ('__all__')  for all fields
        # for custom fields:   
        # fields = ['productname', 'price']
        fields = ('__all__')

Step-4: include App name api in the settings file


Step-5: Now go to under api app and write the below code

from products.models import Product
from .serializers import ProductSerializer
# Create your views here.
class ProductAPIView(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

Step-6: Setup project

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('api/', include('api.urls')),


Step7: Now create under api apps and write the below code

from django.urls import path
from .views import ProductAPIView

urlpatterns = [
    path('products/', ProductAPIView.as_view()),

Now run the server by the below code

python runserver

Step-8: Now follow URL to see the get data through rest api

Finally, you will see the below data in browser

Product table data


Leave a Reply

Your email address will not be published. Required fields are marked *