DEV Community

tobiadiks
tobiadiks

Posted on

Writing an API in Django (Class Based)

Rest API solve the problem of writing specific codes for different platform.
Django is a Python framework that supports the MVT and follows the DRY principle for writing codes.
To write API for your Django web app, here is how to go about it.

pip install django-rest-framework
Enter fullscreen mode Exit fullscreen mode

Go to your project setting.py and add rest_framework as an installed app.

[... ,
... ,
rest_framework,
... ,
]
Enter fullscreen mode Exit fullscreen mode

now we will create a new script called serializer.py in our app folder.
Open and add the following code

from rest_framework import serializers
from .models import model_name


class mySerializer(serializers.ModelSerializer):
    class Meta:
        model = model_name
        fields = ['__all__']
Enter fullscreen mode Exit fullscreen mode

Brace up 😁, you are almost done with your API.

Next up,
In views.py write the code below

from rest_framework.generics import ListCreateAPIView
from .serializer import mySerializer
from .models import model_name

class listApi(ListCreateAPIView):
    queryset = model_name.objects.all()
    serializer_class = mySerializer
Enter fullscreen mode Exit fullscreen mode

Lastly we are going to assign a URL to our API
open urls.py

from django.urls import path
from .views import listApi

urlpatterns = [path('api/list', listApi.as_view),
]
Enter fullscreen mode Exit fullscreen mode

open browser 127.0.0.1:8000

🎉🎉🎉

You just made a Class Based API view.

Top comments (0)