Creating a simple API

Introduction

Django Rest Framework (DRF) is a powerful toolkit that simplifies the creation of Web APIs in Django. This tutorial will guide you through the process of creating a simple API with DRF. By the end of this tutorial, you’ll have a functional API that can handle basic CRUD operations.

Prerequisites

If you haven’t set up a DRF project yet, please refer to our previous tutorial on setting up a DRF project to get started.

Step 1: Define a Model

For this tutorial, we’ll create a simple Book model.

# myapp/models.py

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title

Run the following commands to create and apply the migrations for your new model:

python manage.py makemigrations
python manage.py migrate

Step 2: Create a Serializer

Serializers in DRF convert complex data types like Django models into native Python data types that can be easily rendered into JSON or other content types.

# myapp/serializers.py

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']

Step 3: Create Views

Create a view to handle API requests. We’ll use DRF’s generic class-based views to create a list and create view for the Book model.

# myapp/views.py

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer

class BookListCreate(generics.ListCreateAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

Step 4: Configure URLs

Configure the URLs for your API. Create a urls.py file in your app directory and set up the routing:

# myapp/urls.py

from django.urls import path
from .views import BookListCreate

urlpatterns = [
    path('books/', BookListCreate.as_view(), name='book-list-create'),
]

Include the app’s URLs in the project’s main urls.py file:

# myproject/urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]

Step 5: Run the Development Server

Run the Django development server to test your setup:

python manage.py runserver

Open your web browser and navigate to http://127.0.0.1:8000/api/books/. You should see an empty list of books, indicating that your API is set up correctly.

Step 6: Test the API

You can use tools like Postman or curl to test your API.

{
    "title": "The Great Gatsby",
    "author": "F. Scott Fitzgerald",
    "published_date": "1925-04-10"
}

Conclusion

Congratulations! You’ve successfully created a simple API with Django Rest Framework. You now have a basic understanding of how to set up a DRF project and create API endpoints for handling CRUD operations. In future tutorials, we’ll explore more advanced features of DRF, such as authentication, permissions, and more.


Tags: Creating a simple API with Django Rest Framework, DRF simple API tutorial, Django API setup, Django Rest Framework guide