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
Go to your project setting.py and add rest_framework as an installed app.
[... ,
... ,
rest_framework,
... ,
]
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__']
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
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),
]
open browser 127.0.0.1:8000
๐๐๐
You just made a Class Based API view.
Top comments (0)