Listing API Exposed
Listing Exposed API Endpoints with DefaultRouter in Django REST Framework"
When you use the DefaultRouter
in Django REST Framework (DRF), it automatically generates API endpoints for the viewsets you register with it. To know which API endpoints are exposed, you can follow these steps:
-
Use
router.urls
:After registering your viewsets with the DefaultRouter, you can inspect the urls property of the router to see the list of generated URL patterns.
from rest_framework.routers import DefaultRouter from myapp.views import MyViewSet router = DefaultRouter() router.register(r'my-viewset', MyViewSet, basename='myviewset') # Print the list of URLs print(router.urls)
This will give you an idea of which endpoints are available. The output will be a list of
URLPattern
objects. -
Access the API Root Endpoint:
By default,
DefaultRouter
creates an API root endpoint, usually at/
. When you visit this endpoint in your browser or using a tool like Postman, it will list all the available endpoints.If you navigate to
http://localhost:8000/
(or your API's base URL), you'll see a list of all registered endpoints. -
Check the urls.py Configuration:
Ensure that you've included the router in your
urls.py
file. This is where you can see which viewsets are registered, giving you an idea of the endpoints exposed. -
Use DRF's schema or swagger:
If you're using tools like DRF's schema generation (/schema/) or Swagger (drf-yasg), you can generate documentation that lists all the exposed endpoints.
Example:
- Swagger: Visit the
/swagger/
endpoint to view a list of all endpoints in a Swagger UI. - Schema: Visit
/schema/
for a raw schema or/redoc/
for ReDoc documentation.
- Swagger: Visit the
-
Run
manage.py show_urls
:You can use third-party packages like django-extensions to run a command that shows all registered URLs in your Django application, including those from the
DefaultRouter
.
This will display all the URLs exposed by your application, including the ones managed by DRF's DefaultRouter
.