The Django REST framework makes it easy to create APIs. Here's what you need to know about the Django REST framework.
settings.py
Add rest_framework
to ʻINSTALLED_APPS`.
settings.py
INSTALLED_APPS = [
'rest_framework', #add to
]
Next, we will create a serializer.
serializers.py
from rest_framework import serializers
class SampleSerializer(serializers.ModelSerializer):
class Meta:
model =Object model
fields =Fields to include (in all cases'__all__') #Or exclude= (Fields you want to exclude)
After creating the serializer, add it to views.py
.
views.py
from rest_framework import generics
class SampleListAPI(generics.ListAPIView):
queryset =Object model.objects.all()
serializer_class =Serializer
class SampleDetailAPI(generics.ListAPIView):
queryset =Object model.objects.all()
serializer_class =Serializer
Finally, set the routing and you're done.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/sample/list', views.SampleListAPI.as_view(), name='api_sample_list'),
path('api/sample/detail/<int:pk>/', views.SampleDetailAPI.as_view(), name='api_sample_detail'),
]
Here, I explained how to create an API using the Django REST framework.
Recommended Posts