After understanding the basics of Django REST Framework (DRF), the next step is to install and configure it in a Django project. Proper setup ensures that you can start building APIs quickly and efficiently.
Prerequisites
Before installing DRF, make sure you have:
- Python installed
- Django installed
- A Django project created
If you do not have a Django project yet, create one using:
django-admin startproject myproject
cd myproject
Install Django REST Framework
Install DRF using pip:
pip install djangorestframework
Verify the installation:
pip show djangorestframework
Add DRF to Installed Apps
Open settings.py and add rest_framework to the INSTALLED_APPS list:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
Create a Django App
Create an application where your APIs will reside:
python manage.py startapp api
Add the app to INSTALLED_APPS:
INSTALLED_APPS = [
...
'api',
]
Create a Basic API View
Inside api/views.py:
from rest_framework.views import APIView
from rest_framework.response import Response
class HelloAPIView(APIView):
def get(self, request):
return Response({
"message": "Django REST Framework is working!"
})
Configure URLs
Create api/urls.py:
from django.urls import path
from .views import HelloAPIView
urlpatterns = [
path('hello/', HelloAPIView.as_view(), name='hello-api'),
]
Include the app URLs in the 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')),
]
Run the Development Server
Start the server:
python manage.py runserver
Visit:
http://127.0.0.1:8000/api/hello/
You should see:
{
"message": "Django REST Framework is working!"
}
DRF Browsable API
One of the best features of DRF is its browsable API interface. Open the API endpoint in your browser, and DRF automatically provides a user-friendly interface for testing APIs without using external tools.
Optional DRF Global Settings
You can configure DRF globally in settings.py:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
]
}
This setting ensures responses are returned in JSON format.
Conclusion
Setting up Django REST Framework is straightforward. After installing the package, adding it to INSTALLED_APPS, creating API views, and configuring URLs, you are ready to start building powerful REST APIs with Django.