I have a browsable API:
restaurant_router = DefaultRouter()
restaurant_router.register(r'rooms', RoomsViewSet)
restaurant_router.register(r'printers', PrintersViewSet)
restaurant_router.register(r'shifts', ShiftsViewSet)
urlpatterns = patterns('',
url(r'^$', api_root),
url(r'^restaurant/$',
RestaurantView.as_view(),
name='api_restaurants_restaurant'),
url(r'^restaurant/', include(restaurant_router.urls)),
)
In the api_root
I can link to the named route:
@api_view(('GET',))
def api_root(request, format=None):
return Response({
'restaurant': reverse('api_restaurants_restaurant', request=request, format=format),
})
Or I can use the browsable API generated by the DefaultRouter
, as explained in the documentation:
The DefaultRouter class we're using also automatically creates the API root view for us, so we can now delete the api_root method from our views module.
What do I do if I want to mix ViewSet
s and normal Views, and show everything in the same API root? The DefaultRouter
is only listing the ViewSet
s it controls.
Summary. APIView and ViewSet all have their right use cases. But most of the time, if you are only doing CRUD on resources, you can directly use ViewSets to respect the DRY principle. But if you are looking for more complex features, you can go low-level because after all, viewsets are also a subclass of APIView .
APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.
ModelViewSet. The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the ModelViewSet class are . list() , . retrieve() , .
The browsable API feature in the Django REST framework generates HTML output for different resources. It facilitates interaction with RESTful web service through any web browser. To enable this feature, we should specify text/html for the Content-Type key in the request header.
You can define your views as ViewSets with only one method. So you can register it in router and it will be in one space with ViewSets.
http://www.django-rest-framework.org/api-guide/viewsets/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With