
In Django Rest Framework (DRF), routing refers to the process of mapping URLs to views. A view is a Python function that handles an HTTP request and returns an HTTP response. In DRF, views are typically classes based on APIView
class or generic views such as ListAPIView
and RetrieveAPIView
.
DRF uses the Django URL dispatcher to map URLs to views. To define a URL pattern in DRF, you use the path()
or re_path()
function in your URL configuration. Here’s an example of a simple URL configuration in DRF
from django.urls import path
from .views import UserListView
urlpatterns = [
path('users/', UserListView.as_view(), name='user-list'),
]
In this example, the URL pattern /users/
is mapped to the UserListView
view. When a user makes a GET request to /users/
, DRF will call the UserListView
view to handle the request and return a response.
In DRF, you can also use routers to automatically generate URL patterns for views..Routers are a simple way to define URL patterns and views in a single place, making it easier to manage your API. To use a router, you create an instance of the DefaultRouter
class and then register your views with the router using the register()
method.
Here’s an example of using a router in DRF:
from rest_framework import routers
from .views import UserViewSet
router = routers.DefaultRouter()
router.register('users', UserViewSet, basename='user')
urlpatterns = router.urls
With this illustration, the router automatically generates URL patterns for the UserViewSet viewset and stores the resulting patterns within the urlpatterns list. To further specify the URLs created by the router, the basename
argument is utilized to designate a base name for the URLs. This base name is then used within the URL names.
Here is an example of a simple project in Django Rest Framework that demonstrates routing:
1. Create a new Django project:
django-admin startproject myproject
2. Change into the project directory:
django-admin startproject myproject
3. Create a new Django app:
python manage.py startapp api
4. Install the Django Rest Framework:
pip install djangorestframework
5. Add 'rest_framework'
to your INSTALLED_APPS
list in settings.py
:
INSTALLED_APPS = [ ... 'rest_framework',]
6. In the api
app, create a serializers.py file:
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(max_length=100)
email = serializers.EmailField()
7. In the api
app, create a views.py file:
from rest_framework import viewsets
from .serializers import UserSerializer
class UserViewSet(viewsets.ViewSet):
serializer_class = UserSerializer
def list(self, request):
users = [
{'id': 1, 'name': 'John', 'email': '[email protected]'},
{'id': 2, 'name': 'Jane', 'email': '[email protected]'},
]
serializer = self.serializer_class(users, many=True)
return Response(serializer.data)
8. In the myproject
directory, create a urls.py file:
from django.urls import path, include
from rest_framework import routers
from api.views import UserViewSet
router = routers.DefaultRouter()
router.register('users', UserViewSet, basename='user')
urlpatterns = [
path('api/', include(router.urls)),
]
9. Run the development server:
python manage.py runserver
10. Access the API in your web browser at http://localhost:8000/api/users/
.
In this project, routing in Django Rest Framework is demonstrated by creating a basic API that returns a collection of users. Specifically, the UserViewSet class plays a crucial role by defining the view that handles incoming requests and returns appropriate responses. Meanwhile, the router comes into play by automatically generating the necessary URL patterns for the view. Finally, the UserSerializer class is employed to serialize the list of users into a JSON format for the response.