Python endpoint discovery

List Django REST Framework Endpoints and Nested URL Patterns

Django exposes a runtime URL resolver, while Django REST Framework routers generate patterns for registered viewsets. A useful inventory has to recurse through included URLconfs, preserve prefixes, and separate API endpoints from admin, static, and non-API views.

Direct framework method

Start with the routes registered at runtime

Walk Django's root URL resolver after settings load, joining each include() prefix and turning DRF's router regexes and path() converters into {param} paths. Skip the admin and the format-suffix copies DRF adds, and read the HTTP methods from the view: a viewset route carries its actions, and a class-based or @api_view view defines one handler per method.

Django REST Framework route inventory · python
import re

from django.urls import URLResolver, get_resolver


def to_path(pattern: str) -> str:
    pattern = pattern.removeprefix("^").removesuffix("$")
    pattern = re.sub(r"\(\?P<(\w+)>[^)]*\)", r"{\1}", pattern)  # DRF router regexes
    return re.sub(r"<(?:\w+:)?(\w+)>", r"{\1}", pattern)  # path() converters


def view_methods(callback) -> str:
    actions = getattr(callback, "actions", None)  # DRF viewset routes
    if actions:
        return ", ".join(method.upper() for method in actions)
    view_class = getattr(callback, "cls", None) or getattr(callback, "view_class", None)
    if view_class is None:
        return "ANY"  # a function view decides its methods inside the function
    return ", ".join(
        method.upper()
        for method in view_class.http_method_names
        if method != "options" and hasattr(view_class, method)
    )


def list_endpoints(patterns, prefix="/"):
    for pattern in patterns:
        raw = str(pattern.pattern)
        if "(?P<format>" in raw or "drf_format_suffix" in raw:
            continue  # .json/.api copies that DRF adds for every route
        path = prefix + to_path(raw)
        if path.startswith("/admin/"):
            continue
        if isinstance(pattern, URLResolver):
            yield from list_endpoints(pattern.url_patterns, path)
        else:
            yield view_methods(pattern.callback), path


for methods, path in list_endpoints(get_resolver().url_patterns):
    print(f"{methods:28} {path}")

Where a route-listing snippet stops

  • Django settings and application imports must initialize successfully before the resolver is available.
  • The URL tree includes admin, static, health, and regular web views unless you classify them explicitly.
  • A URL pattern alone does not reliably expose every allowed HTTP method, serializer, permission, or authentication requirement.
  • Dynamically selected URLconfs and deployment-specific settings can produce different runtime inventories.

Use source as the second inventory

APIScout analyzes supported Django and Django REST Framework projects from source in VS Code, connects routes with implementation context, and creates an OpenAPI baseline without booting the application.

Review supported frameworks

Source scan example

What a source scan finds in a Django REST Framework app

We ran the APIScout engine on a small DRF project: two include() levels, one with an app namespace, a DefaultRouter with a ModelViewSet and an @action, a generic RetrieveUpdateAPIView with lookup_url_kwarg, an @api_view function, and the Django admin. It read the source without setting up Django or installing dependencies, left the admin URLs out of the inventory, and linked each endpoint back to the file that defines it.

shop/urls.py
urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/v1/", include("orders.urls")),
    path("api/v1/accounts/", include(("accounts.urls", "accounts"))),
]
orders/urls.py
router = DefaultRouter()
router.register("orders", views.OrderViewSet)

urlpatterns = [
    path("stats/", views.order_stats),
] + router.urls
orders/views.py
class OrderViewSet(viewsets.ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

    @action(detail=True, methods=["post"])
    def cancel(self, request, pk=None):
        order = self.get_object()
        order.status = "cancelled"
        order.save()
        return Response({"status": order.status})


@api_view(["GET"])
def order_stats(request):
    return Response({"count": Order.objects.count()})
accounts/urls.py
urlpatterns = [
    path("users/<int:user_id>/", views.UserDetailView.as_view()),
]
accounts/views.py
class UserDetailView(generics.RetrieveUpdateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    lookup_url_kwarg = "user_id"

Endpoints found

GET, POST/api/v1/orders/ModelViewSet list and create; request body from OrderSerializer fields
GET, PUT, PATCH, DELETE/api/v1/orders/{id}/The four detail actions; {pk} reported as {id}, as DRF's own schema generator does
POST/api/v1/orders/{id}/cancel/@action(detail=True, methods=["post"])
GET, PUT, PATCH/api/v1/accounts/users/{user_id}/Generic view; lookup_url_kwarg names the parameter; UserSerializer fields id, username, and email
GET/api/v1/stats/Methods from @api_view(["GET"])

Not resolved from source: paths built in code, such as URL patterns generated in a loop or list comprehension. Compare those with a runtime listing.

Route patterns: the snippet above vs a source scan

DefaultRouter routesOne line per URL, with methods from the viewset's actionsEach operation listed, with the serializer as the request body
Format-suffix copies (.json, .api)Skipped by the snippet; the resolver has one for every routeNot listed
Django adminSkipped by the /admin/ checkLeft out
Generic views with lookup_url_kwargMethods from the view class; path from the URL patternMethods, the {user_id} parameter, and serializer fields
Serializer fieldsNot shownRequest bodies from ModelSerializer fields
@api_view(["GET"]) functionsMethods from the decoratorMethods from the decorator
Loading DjangoNeeds settings, installed apps, and imports to loadReads the source; Django is not set up
Paths built in code (loops)Final values, because Django has loadedNot resolved; check them against a runtime listing

Questions about listing Django REST Framework routes

How do I list all URLs in a Django project?

Walk the root resolver: get_resolver().url_patterns holds URLPattern and URLResolver objects, and every include() is a resolver whose url_patterns you visit recursively while joining the prefixes. The show_urls command from django-extensions prints the same tree.

Why do my DRF router routes show up as regular expressions?

By default DefaultRouter and SimpleRouter build their routes with regular expressions, such as ^orders/(?P<pk>[^/.]+)/$, so str(pattern.pattern) prints the regex. DefaultRouter also adds an API root view and a format-suffix copy of each route for .json and .api. The snippet converts named groups to {pk} and skips the copies.

How do I see which HTTP methods a DRF endpoint accepts?

For viewset routes, the view function the router creates carries an actions mapping, such as {"get": "list", "post": "create"}. For class-based and @api_view views, check which handler methods the class defines. A plain Django function view answers any method unless it checks request.method itself.

Can I get an OpenAPI document for a DRF project without running it?

DRF's generateschema command builds the document from the running URL configuration, so Django has to load with its settings. APIScout reads the source instead: it expands routers and viewsets, reads serializers, path parameters, and @action routes, and exports an OpenAPI document.

Turn the inventory into a reviewable API contract

Export OpenAPI, review the endpoints with the team that owns them, and use the same contract for documentation and security testing.

Open the source-to-OpenAPI workflow