Function-based API Views in Django
In Django Rest Framework (DRF), you can define API views in two main ways: using function-based views (FBVs) or class-based views (CBVs). In this article, we will focus on function-based API views in Django, providing examples of how to create and handle simple APIs using Django Rest Framework.
1. What are Function-based Views (FBVs)?
Function-based views (FBVs) are the traditional way of defining views in Django. In the context of Django Rest Framework, FBVs allow you to define API endpoints using simple Python functions. These views handle HTTP requests and return HTTP responses, typically in the form of JSON data for API responses.
2. Installing Django Rest Framework (DRF)
Before we can create function-based API views, ensure that Django Rest Framework is installed in your project. You can install it using pip:
pip install djangorestframework
Once DRF is installed, add it to your INSTALLED_APPS
in the settings.py
file:
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # Add DRF here
]
3. Creating a Simple Model
For the examples in this article, we will use a simple model called Book
that represents books in a library system. Let's define this model in models.py
.
# models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
publish_date = models.DateField()
def __str__(self):
return self.title
This model contains three fields: title
, author
, and publish_date
. We will use this model to demonstrate our function-based API views.
4. Creating a Function-based API View
Now let's create a function-based view to list all the books in the database. We will use Django Rest Framework's Response
class to return data in JSON format.
Example: List All Books
# views.py
from django.http import JsonResponse
from .models import Book
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt # Disable CSRF check for this example (not recommended for production)
def book_list(request):
if request.method == 'GET':
books = Book.objects.all() # Get all books from the database
book_data = list(books.values('id', 'title', 'author', 'publish_date')) # Convert to dictionary format
return JsonResponse(book_data, safe=False) # Return the data as JSON
In this example, we define a function book_list
to handle GET requests. It fetches all books from the database, converts them to a list of dictionaries using values()
, and returns the data in JSON format using JsonResponse
.
5. Setting Up URLs for the API
Next, we need to create a URL route that maps to our function-based view. We can define this URL in the urls.py
file.
Example: Defining URL Patterns
# urls.py
from django.urls import path
from .views import book_list
urlpatterns = [
path('api/books/', book_list, name='book-list'),
]
In this example, we map the book_list
function to the URL /api/books/
. When you visit this URL, the book_list
function will be executed, and the list of books will be returned as a JSON response.
6. Handling POST Requests in Function-based Views
Function-based views can also handle POST requests. For example, we can create a view that allows users to create a new book by sending a POST request with book data.
Example: Creating a New Book
# views.py
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from .models import Book
import json
@csrf_exempt
def create_book(request):
if request.method == 'POST':
data = json.loads(request.body) # Parse JSON data from request body
title = data.get('title')
author = data.get('author')
publish_date = data.get('publish_date')
# Create a new Book instance
book = Book.objects.create(title=title, author=author, publish_date=publish_date)
return JsonResponse({'id': book.id, 'title': book.title, 'author': book.author, 'publish_date': book.publish_date}, status=201)
In this example, we create a create_book
view that accepts POST requests. The view reads the incoming JSON data, creates a new Book
instance, and returns the newly created book's data in the response.
7. Setting Up URLs for POST Requests
We also need to add a URL pattern for the create_book
view to handle POST requests.
Example: Adding URL for Create Book
# urls.py
from django.urls import path
from .views import book_list, create_book
urlpatterns = [
path('api/books/', book_list, name='book-list'),
path('api/books/create/', create_book, name='create-book'),
]
Now, you can send a POST request to /api/books/create/
with the data for the new book to create it in the database.
8. Conclusion
In this article, we covered the basics of creating function-based API views in Django using Django Rest Framework (DRF). We demonstrated how to handle GET and POST requests with function-based views, serialize data into JSON format, and set up URL routes for API endpoints. Function-based views are a simple and intuitive way to build APIs in Django, and with DRF, they become even more powerful and flexible for building APIs in Django projects.