1. Add 'rest_framework' to your INSTALLED_APPS setting.
INSTALLED_APPS = [
...
'rest_framework',
]
2. If you're intending to use the browsable API you'll probably also want
to add REST framework's login and logout views. Add the following to your
root urls.py file.
# don’t forget to import include on the url file
# from django.urls import include
urlpatterns = [
...
path('api-auth/', include(‘rest_framework.urls')),
]
3. Let’s take a look at a quick example of using REST framework to build a
simple model-backed API.
We'll create a read-write API for accessing information on the users of our
project.
Any global settings for a REST framework API are kept in a single
configuration dictionary named REST_FRAMEWORK. Start off by adding the
following to your settings.py module:
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
4. Create a folder named api on your app
> then initialise the folder by creating __init__.py file
5. Then create a file named serializers.py file on the api folder.
from rest_framework import serializers
from articles.models import Article
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
6. Create views.py file on api folder
from rest_frameworks.generics import ListAPIView
From articles.models import Article
From .serializers import ArticelSerialzer
class ArticelListView(listAPIView)
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetailView(RetrieveAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
7. Create urls.py file on api folder
from django.urls import path
from .views import AritleListView, ArticleDetailView
urlpatterns = [
path(‘’,AritleListView.as_view()),
path(‘<pk>’, ArticleDetailView())
]
8. On main url file
Add the following
urlpatterns = [
…
path(‘api/‘, include(‘articles.api.urls))
]