Building Your First API with Django: A Beginner's Guide

What is Django?

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. With built-in security features and a powerful ORM (Object-Relational Mapper), Django simplifies the process of building robust web applications. When combined with Django REST Framework (DRF), it becomes an excellent choice for developing APIs.

Step 1: Setting Up Your Environment

Before you start, ensure that you have Python installed on your system. You can download it from the official Python website.

Once Python is installed, create a virtual environment and install Django:

mkdir my-django-api
cd my-django-api
python -m venv venv
source venv/bin/activate  # On Windows, use `venv\Scripts\activate`

Step 2: Installing Django and Django REST Framework

Install Django and Django REST Framework (DRF) using pip:

pip install django djangorestframework

Now, create a new Django project:

django-admin startproject myapi .

Then, create a new Django app inside your project:

python manage.py startapp api

Step 3: Configuring Django for API Development

Add rest_framework and api to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api',
]

Step 4: Creating Your First API Endpoint

Define a simple model in api/models.py:

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)

Run migrations to apply the model changes:

python manage.py makemigrations
python manage.py migrate

Step 5: Creating a Serializer

Create a serializer in api/serializers.py to convert model instances into JSON:

from rest_framework import serializers
from .models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

Step 6: Building a View and URL for the API

Modify api/views.py to create an API endpoint:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import User
from .serializers import UserSerializer

@api_view(['GET'])
def get_users(request):
    users = User.objects.all()
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data)

Update api/urls.py to register the new endpoint:

from django.urls import path
from .views import get_users

urlpatterns = [
    path('users/', get_users, name='get_users'),
]

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

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

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

Step 7: Running the Django Server

Start the development server:

python manage.py runserver

Visit http://localhost:8000/api/users/ in your browser or use Postman to see the API response.

Step 8: Next Steps

From here, you can enhance your API with:

  • Implementing CRUD (Create, Read, Update, Delete) operations.
  • Adding authentication and permissions.
  • Using Django’s ORM to connect to a database.
  • Structuring your project with viewsets and routers for scalability.

Conclusion

Django, combined with Django REST Framework, makes API development simple and efficient. Whether you’re building a small project or a large-scale application, Django provides all the tools you need to create a robust and secure backend.

STAY IN TOUCH

Get notified when I publish something new, and unsubscribe at any time.