Sobes.tech
Junior — Middle

What methods are used to implement request routing in Django REST Framework?

sobes.tech AI

Answer from AI

In Django REST Framework, request routing is implemented using:

  • Routers — special classes that automatically create URL routes for ViewSets. For example, DefaultRouter or SimpleRouter.
  • URL configurations — in the urls.py file, you can explicitly define paths using the path() or re_path() functions, linking them to specific views.

Example of using a Router:

from rest_framework.routers import DefaultRouter
from myapp.views import UserViewSet

router = DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = router.urls

This approach simplifies creating RESTful APIs by automatically generating routes for standard actions (list, create, retrieve, update, delete).

You can also manually define routes:

from django.urls import path
from myapp.views import UserList, UserDetail

urlpatterns = [
    path('users/', UserList.as_view()),
    path('users/<int:pk>/', UserDetail.as_view()),
]