Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Creating APIs with Django REST Framework

1. Introduction

In this tutorial, we will learn how to create APIs using the Django REST Framework. APIs (Application Programming Interfaces) are essential for enabling communication between different software systems. Django REST Framework is a powerful toolkit for building Web APIs in Django.

2. Setting Up the Environment

First, ensure that you have Python and pip installed on your system. Then, create a virtual environment and install Django and Django REST Framework.

python -m venv myenv

source myenv/bin/activate # On Windows use `myenv\Scripts\activate`

pip install django djangorestframework

3. Creating a New Django Project

Create a new Django project and navigate to the project directory.

django-admin startproject myproject

cd myproject

4. Creating a Django App

Create a new Django app within the project.

python manage.py startapp myapp

5. Setting Up the App

Add the new app and REST framework to the project's settings.

# myproject/settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
    'myapp',
]
                

6. Creating a Model

Create a model in the app to represent the data structure.

# myapp/models.py

from django.db import models

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.name
                

Run migrations to apply the model changes to the database.

python manage.py makemigrations

python manage.py migrate

7. Creating a Serializer

Create a serializer for the model in the app to convert model instances to JSON and vice versa.

# myapp/serializers.py

from rest_framework import serializers
from .models import Item

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

8. Creating Views

Create views for the API endpoints using Django REST Framework's generic views.

# myapp/views.py

from rest_framework import generics
from .models import Item
from .serializers import ItemSerializer

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

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

9. Configuring URLs

Configure the URLs for the API endpoints in the app and project URL configuration files.

# myapp/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('items/', views.ItemList.as_view(), name='item-list'),
    path('items//', views.ItemDetail.as_view(), name='item-detail'),
]
                
# 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')),
]
                

10. Running the Server

Run the Django development server and test the API endpoints using a tool like Postman or cURL.

python manage.py runserver

Now, you can access the API at http://127.0.0.1:8000/api/items/.

11. Conclusion

Congratulations! You have successfully created a basic API using the Django REST Framework. You can now extend this API by adding more models, serializers, and views as needed.