How to Install Django Rest Framework: A Step-by-Step Guide
Django Rest Framework (DRF) is a powerful and flexible toolkit for building Web APIs in the Python Django ecosystem. If you’re new to developing RESTful APIs with Django, this guide will walk you through installing and setting up DRF in your project with ease.
Prerequisites
- Basic knowledge of Python and Django
- Python 3.6 or higher installed on your system
- Django installed (version 2.2 or higher recommended)
- Command line/terminal access
If you don’t have Django installed yet, you can follow our How to Install Python Django Framework: Step-by-Step Guide to get a Django project running before proceeding.
Step 1: Create and Activate a Virtual Environment (Optional but Recommended)
Using a virtual environment isolates your dependencies and avoids conflicts between projects.
python3 -m venv env
source env/bin/activate # On Windows use `env\Scripts\activate`
Step 2: Install Django Rest Framework
With your virtual environment activated, install DRF via pip:
pip install djangorestframework
Step 3: Add ‘rest_framework’ to Your Django Project
Open your Django project’s settings.py file and add 'rest_framework' to the INSTALLED_APPS list:
INSTALLED_APPS = [
# Other apps
'rest_framework',
]
Step 4: Migrate Your Database
DRF doesn’t add models that require migrations, but it’s good practice to run migrations after adding new apps:
python manage.py migrate
Step 5: Test the Installation
To verify DRF is installed correctly, create a simple API view or use the built-in browsable API feature.
As an example, add this to your app’s views.py:
from rest_framework.views import APIView
from rest_framework.response import Response
class HelloWorld(APIView):
def get(self, request):
return Response({"message": "Hello, Django Rest Framework!"})
And add the route to urls.py:
from django.urls import path
from .views import HelloWorld
urlpatterns = [
path('hello/', HelloWorld.as_view()),
]
Run your development server:
python manage.py runserver
Navigate to http://127.0.0.1:8000/hello/ to see the JSON response.
Troubleshooting Common Issues
- Module Not Found Error: Ensure the virtual environment is activated and DRF installed within it.
- Not Showing Browsable API: Confirm
'rest_framework'is inINSTALLED_APPSand the server restarted. - APIView Import Issues: Confirm you installed the latest DRF and are importing from
rest_framework.views.
Summary Checklist
- ✅ Have Python and Django installed
- ✅ (Optional) Created and activated a virtual environment
- ✅ Installed Django Rest Framework using pip
- ✅ Added
'rest_framework'toINSTALLED_APPS - ✅ Ran migrations
- ✅ Tested basic API view and confirmed functionality
Installing and setting up Django Rest Framework is straightforward. With this foundation, you can build powerful RESTful APIs for your Django applications. For more Django-related tutorials, check out our guides on Creating Django Superusers and Creating Django Projects.
