Hello! Welcome to your second lesson in the "Building APIs with Django REST Framework" module.
In our previous lesson, we established a strong theoretical foundation, exploring the architectural principles of REST. You learned about resource-based design, the uniform interface, and the six constraints that define a truly RESTful system. You now have the blueprint for designing clean, scalable web APIs.
Today, we transition from theory to practice. This lesson is all about setting up your toolkit. Our goal is to install and configure the Django REST Framework (DRF) in a Django project. DRF is a powerful and flexible toolkit that we will use to build the RESTful APIs we've been discussing. By the end of this lesson, you will have a fully functional "Hello, API!" endpoint running, confirming your setup is ready for development.
1. Preparing Your Development Environment
Before we can use DRF, we need to set up a clean, isolated environment for our project. As a developer, this is a non-negotiable first step to ensure consistency and avoid dependency conflicts. Your experience with complex data science projects, which often have their own sets of library dependencies, has likely shown you the importance of managing environments carefully.
We will walk through the professional standard for setting up a new Django project.
Build a Powerful API with Django From Scratch
This article from 42coffeecups provides an excellent rationale and guide for setting up a proper development environment. It emphasizes best practices that are crucial for professional backend development.
Read the section 'Setting Up Your Development Environment' up to the subsection 'Initializing Your Django Project'. Focus on understanding the why behind using a virtual environment and creating a requirements.txt file.
To summarize and execute the steps:
-
Create a Project Folder:
Choose a location on your computer and create a new directory for your API project. Navigate into it using your terminal.mkdir my_api_project cd my_api_project -
Create and Activate a Virtual Environment:
We'll use Python's built-invenvmodule. This creates an isolated environment where our project's dependencies will live.# For Mac/Linux python3 -m venv venv source venv/bin/activate # For Windows py -m venv venv .\venv\Scripts\activateYour terminal prompt should now be prefixed with
(venv), indicating the virtual environment is active. -
Install Packages:
With the virtual environment active, usepipto install Django and Django REST Framework.pip install django djangorestframework -
Create
requirements.txt:
It's a best practice to immediately record your project's dependencies. This file acts as a manifest, making it easy to replicate the environment elsewhere.pip freeze > requirements.txt
Now your environment is ready. You have a clean workspace with the necessary foundational packages installed.
2. Creating the Django Project and App
With the environment set up, we can now lay down the scaffolding for our Django project.
-
Create the Django Project:
This command creates the main project structure. We'll name our projectcoreand create it in the current directory (hence the.).django-admin startproject core .Note: The
.is important. It prevents Django from creating an extra, unnecessary level of directory nesting. -
Create a Django App:
Django projects are composed of "apps," which are self-contained modules for a specific piece of functionality. It's a common convention to put all API-related code into an app namedapi.python manage.py startapp api
Your directory should now look something like this:
my_api_project/
├── venv/
├── core/
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── api/
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations/
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── requirements.txt
3. Configuring DRF in Your Project
Now that we have DRF installed and our project structure created, we need to tell our Django project to use them. This is done in the main project settings file.
This next resource provides a concise, step-by-step guide for the entire installation and configuration process, which we will follow.
How to Use the Django REST Framework - Build Backend ...
The article 'How to Use the Django REST Framework' from freeCodeCamp offers a very clear, practical walkthrough. We will use it to guide the final configuration and verification steps.
Read 'Step 7: Add DRF to Installed Apps'. This is the critical step where you register the framework with your project.
Following the instructions, open the core/settings.py file in your code editor. Find the INSTALLED_APPS list. You need to add two new entries: 'rest_framework' and the name of the app you just created, 'api'.
The order doesn't strictly matter, but it's conventional to place third-party apps first, followed by your own apps.
# core/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party apps
'rest_framework',
# Local apps
'api',
]
By adding 'rest_framework' to INSTALLED_APPS, you've enabled all of DRF's features within your project. Adding 'api' makes Django aware of your new app, allowing it to discover its models, views, and URLs.
4. Verification: Your First API Endpoint
The configuration is complete, but how do we know it worked? The best way is to create a minimal, functioning API endpoint. This will give you immediate, practical feedback and serve as a "Hello, World!" for your backend journey.
This process will briefly touch on concepts we'll explore in-depth in upcoming lessons: Models, Serializers, Views, and URLs. For now, focus on their high-level role in the request-response cycle.

We will follow the excellent guide in the freeCodeCamp article to build this verification endpoint.
How to Use the Django REST Framework - Build Backend ...
This section of the article will guide you through creating every piece needed to test your installation, from the database model to the final URL.
Follow the instructions in 'Step 10: Verify DRF Installation'. I will break down each step below with additional context.
Let's walk through the steps together:
1. Create a Model (api/models.py)
A model is the Python representation of a database table. Let's define a simple Task model.
# api/models.py
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=200)
completed = models.BooleanField(default=False, blank=True, null=True)
def __str__(self):
return self.title
2. Run Migrations
These commands create a migration file (a blueprint for schema changes) and apply it to the database, creating the actual table for our Task model.
python manage.py makemigrations
python manage.py migrate
3. Create a Serializer (api/serializers.py)
A serializer's job is to translate complex data, like our Task model instance, into a format that can be easily sent over the internet, like JSON. Create a new file api/serializers.py.
# api/serializers.py
from rest_framework import serializers
from .models import Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = '__all__'
We'll cover serializers in great detail in the next lesson. For now, think of this as a "translator" for our Task model.
4. Create a View (api/views.py)
The view contains the logic for handling a request and returning a response. We'll use one of DRF's powerful generic ModelViewSets. This single class provides the logic for all the CRUD operations (GET, POST, PUT, DELETE) we discussed in the last lesson.
# api/views.py
from rest_framework import viewsets
from .serializers import TaskSerializer
from .models import Task
class TaskViewSet(viewsets.ModelViewSet):
queryset = Task.objects.all()
serializer_class = TaskSerializer
5. Configure URLs (core/urls.py)
Finally, we need to create a URL endpoint for our API. We'll use DRF's DefaultRouter, which automatically generates all the necessary URL patterns for our ViewSet.
# core/urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from api import views # Make sure to import views from your api app
# create a new router
router = routers.DefaultRouter()
# register our viewsets
router.register(r'tasks', views.TaskViewSet) # r'tasks' is the endpoint
urlpatterns = [
path('admin/', admin.site.urls),
# add the new url patterns
path('api/', include(router.urls)),
]
This configuration says, "Any request that comes to /api/ should be handled by the router we just defined." The router will then direct /api/tasks/ to our TaskViewSet.
6. Test It!
Start the development server:
python manage.py runserver
Now, open your web browser and navigate to http://127.0.0.1:8000/api/tasks/.
If everything is set up correctly, you should see DRF's Browsable API. This is a user-friendly HTML interface that allows you to interact with your API directly from the browser. It's an incredibly useful tool for development and testing.
Test your understanding!
The DRF Browsable API page you are looking at has a form at the bottom that allows you to create a new Task object. Try creating a new task by entering a title in the "title" field and submitting the form with a POST request.
What happens after you submit? Based on the REST principles from our last lesson, which HTTP method did you just use, and what was its purpose?
Show answer
After you submit the form, the page should refresh and show your newly created task in the list of results (likely with an id of 1).
You just used the POST HTTP method. Its purpose, in a RESTful context, is to create a new resource within a collection. In this case, you created a new Task resource in the /api/tasks/ collection.
Conclusion
Congratulations! You have successfully installed and configured Django REST Framework. You went through the professional workflow of setting up an isolated environment, installing packages, creating a Django project structure, and configuring the framework. Most importantly, you verified your entire setup by building a working API endpoint and interacting with it through the browsable API.
Key Takeaways:
- Always use a virtual environment (
venv) to isolate project dependencies. - DRF is installed via
pipand enabled by adding'rest_framework'toINSTALLED_APPSinsettings.py. - Any custom apps (like our
apiapp) must also be added toINSTALLED_APPS. - The DRF Browsable API is a powerful tool for testing and visualizing your API endpoints directly in the browser.
- The basic components of a DRF endpoint are the Model (data structure), Serializer (data translation), View (request logic), and URL (endpoint address).
Preview of the Next Lesson:
In our verification step, we created a TaskSerializer but didn't dive into the details. Serializers are one of the most important components of DRF. They are responsible for converting data to and from your API and for validating incoming data. In the next lesson, you will learn how to create serializers to convert Django models to JSON and validate input data. We will explore them in depth to gain fine-grained control over our API's data representation.