Creating A RESTful API With Django Detailed
Creating A RESTful API With Django Detailed
Django is a full-featured web framework for Python that simplifies the process of building
web applications, including APIs. To create a RESTful API, we'll use Django Rest Framework
(DRF). DRF provides powerful tools for building APIs quickly and efficiently.
```bash
pip install django djangorestframework
```
```bash
django-admin startproject myapi
cd myapi
```
Django organizes its functionality into apps. Let’s create an app for our API:
```bash
python manage.py startapp api
```
In your `settings.py`, add `rest_framework` and the new `api` app to the `INSTALLED_APPS`
section:
```python
INSTALLED_APPS = [
...,
'rest_framework',
'api',
]
```
```python
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
published = models.DateField()
def __str__(self):
return self.title
```
6. **Create a Serializer**
```python
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
```
```python
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer
class BookListCreate(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
```
8. **Set Up URLs**
```python
from django.urls import path
from . import views
urlpatterns = [
path('books/', views.BookListCreate.as_view()),
path('books/<int:pk>/', views.BookDetail.as_view()),
]
```
```python
from django.urls import path, include
urlpatterns = [
path('api/', include('api.urls')),
]
```
```bash
python manage.py migrate
python manage.py runserver
```
Your API is now running. You can visit `http://127.0.0.1:8000/api/books/` to interact with
it.
### Summary
In this project, we built a simple RESTful API using Django Rest Framework. We created a
model, a serializer, and API views, and set up the routing. DRF simplifies the process of
building APIs by providing reusable components. With DRF, handling tasks like serialization
and authentication becomes much easier.