RunLoop
RunLoop

Reputation: 20376

Issue versioning api calls

I am trying to create an updated version of an api call.

urls.py

router.register(r'categories', views.CategoryViewSet)

router.register(r'categoriesv2', views.CategoryViewSetV2)

However, when I run the internal server, the autogenerated api root is as follows:

"categories": "http://10.0.5.119:8000/api/**categoriesv2**/",

"categoriesv2": "http://10.0.5.119:8000/api/categoriesv2/",

Why is "categories" also pointing to /categoriesv2/ and not /categories/? Any help would be appreciated please!

Upvotes: 0

Views: 43

Answers (1)

Gahan
Gahan

Reputation: 4213

The syntax of register as per doc has three parameters:

mandatory arguments : prefix and viewset which you have already specified

Optional argument: base_name

base_name - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the queryset attribute of the viewset, if it has one. Note that if the viewset does not include a queryset attribute then you must set base_name when registering the viewset.

So the better way to do versioning is to create alternate router as below:

# Create a router and register our viewsets with it.
router = DefaultRouter()
router_v2 = DefaultRouter()
router.register(r'categories', views.CategoryViewSet)
router_v2.register(r'categories', views.CategoryViewSetV2)

# The API URLs are now determined automatically by the router.
urlpatterns = [
    url(r'^api/', include(router.urls))
    url(r'^api/v2/', include(router_v2.urls))
]

Upvotes: 2

Related Questions