The Django REST framework is a powerful and flexible toolkit for building Web APIs. This tutorial will provide a step-by-step guide to help you understand how to use Django REST framework to build APIs.
By the end of this tutorial, you should be able to:
Prerequisites for this tutorial include a basic understanding of Python, Django, and HTTP methods. Familiarity with JSON and RESTful APIs will also be beneficial.
Django REST framework works on top of Django and its ORM. It provides an easy way to serialize the data into JSON or XML formats and expose these data to be consumed by client-side applications.
Here is a detailed guide for creating a simple API using Django REST framework:
pip install django
pip install djangorestframework
django-admin startproject myproject
cd myproject
django-admin startapp myapp
Update settings.py: Add 'rest_framework' and 'myapp' to the INSTALLED_APPS in settings.py.
Create a model in models.py: For example, you can create a simple Book model with fields for title and author.
Create a serializer: In serializers.py, create a BookSerializer with fields for id, title, and author.
Create a view: In views.py, create a BookViewSet that uses the BookSerializer.
Update urls.py: Add a default router and register the BookViewSet with it.
Here are some examples to illustrate the steps mentioned above:
```python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
```
```python
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author']
```
```python
from rest_framework import viewsets
from .serializers import BookSerializer
from .models import Book
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
```
```python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet)
urlpatterns = [
path('', include(router.urls)),
]
```
In this tutorial, you learned the basics of using Django REST framework to build APIs. We covered how to install Django and Django REST framework, create a new Django project and application, and create a model, serializer, view, and URL pattern for the API.
Create a new model called Author
with fields for name
and bio
. Add a foreign key relationship between Book
and Author
.
Update the serializers and views to include the new Author
model.
Test the API by creating, updating, and deleting Author
and Book
instances.
Explore other features of Django REST framework, such as authentication and permissions.
Remember, the best way to learn is by doing. Happy coding!