Creating Your First API with Django Rest Framework: A Quick Tutorial

Posted: September 12, 2024 | Updated: September 12, 2024

Django Rest Framework (DRF) is a powerful toolkit for building Web APIs in Django. In this tutorial, I will show you how to create a simple Django app that uses Django REST Framework (DRF) to set up a REST API

Steps

  1. Create a Django project and app.
  2. Set up Django REST Framework.
  3. Create a model.
  4. Create a serializer.
  5. Create API views.
  6. Configure URLs.
  7. Set up the front end to send data to the API.

1. Create a Django Project and App

First, create a virtual environment and activate it. Then install Django, Django rest framework in that virtual environment.

Use the following command to install both Django and Django rest framework.

pip install django djangorestframework

Then create a new project

django-admin startproject myproject .

Then create a new Django app.

python manage.py startapp myapp

2. Set up Django REST Framework.

Add both the Django app and rest_framework in the INSTALLED_APPS list.

# myproject/settings.py
INSTALLED_APPS = [
    ...
    'rest_framework',
    'myapp',
]

3. Create a Model

Define a model in myapp/models.py.

# myapp/models.py
from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Now run migrations to create the database table for this model.

python manage.py makemigrations
python manage.py migrate

4. Create a Serializer
Create a serializer in myapp/serializers.py.

# myapp/serializers.py
from rest_framework import serializers
from .models import Item

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

5. Create API Views

Create API views in myapp/views.py.

# myapp/views.py
from rest_framework import generics
from .models import Item
from .serializers import ItemSerializer

class ItemListCreateView(generics.ListCreateAPIView):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer

class ItemDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer

6. Configure URLs
Set up URLs for the API in myapp/urls.py.

# myapp/urls.py
from django.urls import path
from .views import ItemListCreateView, ItemDetailView

urlpatterns = [
    path('items/', ItemListCreateView.as_view(), name='item-list-create'),
    path('items/<int:pk>/', ItemDetailView.as_view(), name='item-detail'),
]

Include these URLs in the main project’s urls.py.

# 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')),
]

7. Set Up the Front End

Make sure configure Static Files in settings.py
Ensure you have configured the static files settings correctly in your settings.py:

# myproject/settings.py

import os

# Ensure this is added to your settings.py file
STATIC_URL = '/static/'

# If you have a STATICFILES_DIRS setting, add your static directory
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

# For production, you might also need to define STATIC_ROOT
# STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Place Your Static Files
Create a static directory in the root of your project (i.e., at the same level as manage.py), and place your index.html file inside it.
Your project structure should look like this:

    manage.py
    myproject/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    myapp/
        __init__.py
        admin.py
        apps.py
        models.py
        serializers.py
        views.py
        urls.py
    static/
        index.html

index.html file code is

<!-- myproject/static/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Item API</title>
</head>
<body>
    <h1>Item API</h1>
    <form id="item-form">
        <input type="text" id="name" placeholder="Name" required>
        <textarea id="description" placeholder="Description" required></textarea>
        <button type="submit">Submit</button>
    </form>
    <script>
        document.getElementById('item-form').addEventListener('submit', function(event) {
            event.preventDefault();
            
            const name = document.getElementById('name').value;
            const description = document.getElementById('description').value;

            fetch('http://localhost:8000/api/items/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ name, description }),
            })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                alert('Item created successfully!');
            })
            .catch(error => console.error('Error:', error));
        });
    </script>
</body>
</html>

Now start the Django server using the following code: Open http://localhost:8000/static/index.html in your browser. You should be able to submit data through the form, which will be sent to the API.

python manage.py runserver

That's all.

© 2024 Webapptiv. All rights reserved.