Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest-framework - autogenerate form in browsable API?

Not sure if i'm using the right vocabulary. In the browsable api that comes for free with django-rest-framework, I was wondering if there was a way to autogenerate a form similar to how we define ModelForms. This would allow us to more easily test input to the API in some cases. I'm currently using ModelSerializers and the generic view APIView in case that makes a difference.

I have read the documentation (several times at this point) but didn't see it mentioned anywhere.

screenshot

like image 979
w-- Avatar asked Jan 31 '13 00:01

w--


People also ask

What is browsable API in Django REST Framework?

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.

Which is the argument to Get_schema_view ()?

The get_schema_view() helper takes the following keyword arguments: title : May be used to provide a descriptive title for the schema definition. description : Longer descriptive text. version : The version of the API.

How do I add swagger to Django project?

Update settings.py file in main Django project to load django-rest-swagger app. Update urls.py file in main Django project to first load the get_swagger_view utility function and then add path to route to Swagger UI view. This is where the first hiccup rears it's head.


2 Answers

If you're using the generic class-based-views you'll get that for free. Try the live tutorial at http://restframework.herokuapp.com logging in as one of the users, so that you can create some snippets. eg user: 'max', password: 'max'.

Any views subclassing GenericAPIView and setting a serializer_class will get that behavior, as REST framework can determine what the form should look like.

For example:

screenshot of form input

(Note the form input at the bottom of the screen shot)

If you're just working from APIView you'll get the generic content input (such as json), like the once you've included a screenshot of, which is also useful, but not quite as convenient as the forms.

like image 142
Tom Christie Avatar answered Sep 28 '22 10:09

Tom Christie


Create a serialiser class that fits the form input fields you want and set it on your APIView like so;

class MyView(APIView):
    serializer_class = MySerializer  # Used for the form in the browsable api

That works just perfectly.

Example of a serializer class based on a model:

from rest_framework import serializers

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = MyModel
like image 35
Christoffer Avatar answered Sep 28 '22 10:09

Christoffer