Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mix View and ViewSet in a browsable api_root

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 ViewSets and normal Views, and show everything in the same API root? The DefaultRouter is only listing the ViewSets it controls.

like image 864
blueFast Avatar asked Feb 08 '16 18:02

blueFast


People also ask

When should I use ViewSet and APIView?

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 .

What is difference between Api_view and ViewSet?

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.

What is model ViewSet?

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() , .

What does browsable API mean?

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.


1 Answers

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/

like image 143
Yevgeniy Shchemelev Avatar answered Sep 20 '22 06:09

Yevgeniy Shchemelev