intermediate#Django#API#Rest Framework
Creating a RESTful API with Django Rest Framework
Learn how to create a RESTful API using Django Rest Framework, a powerful library for building web APIs.
Introduction to Django Rest Framework
Django Rest Framework (DRF) is a powerful library for building web APIs. In this tutorial, we will create a simple RESTful API using DRF.
Step 1: Install Django Rest Framework
To start, install Django Rest Framework using pip:
pip install djangorestframework
Step 2: Add DRF to INSTALLED_APPS
Add 'rest_framework' to INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
# ...
'rest_framework',
]
Step 3: Define the API Model
Define a model for the API in models.py:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
Step 4: Create a Serializer
Create a serializer for the Book model in serializers.py:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author']
Step 5: Create API Views
Create API views in views.py:
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import BookSerializer
from .models import Book
class BookList(APIView):
def get(self, request):
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
Step 6: Add API URL Patterns
Add API URL patterns to urls.py:
from django.urls import path
from . import views
django.urls.path('books/', views.BookList.as_view())