1024programmer Java Django-Rest-Framework Tutorial: 5. Improve relevance and hyperlink API

Django-Rest-Framework Tutorial: 5. Improve relevance and hyperlink API

Author: Desmond Chen, Published date: 2014-06-02, Modified date: 2014-06-02

So far, the relationship between APIs is reflected in the form of primary keys (for example, open /users/1/, you can see the primary key of snippets in snippets). In this article, we will use hyperlinks form to further improve the relevance and discoverability of the API. First, we add some paths to make the entire API structure more complete.

1. Root path

Now, we have the paths for users and snippets, but there is no root path for the API itself. We use the @api_view decorator to create a function based view as the root path:

 # snippets/views.py
     from rest_framework import renderers
     from rest_framework.decorators import api_view
     from rest_framework.response import Response
     from rest_framework.reverse importreverse


     @api_view(('GET',))
     def api_root(request, format=None):
         return Response  ({
             'users': reverse('user-list', request=request, format=format),
             'snippets': reverse('snippet-list', request=request, format=format)
         })

Note that we used reverse() of django-rest-framework instead of reverse() that comes with django. If we open http://127.0.0.1/8000 at this time, an error will be reported because we have not yet set the Add name to url, we will add it later.

Add the corresponding path in urls.py:

 # snippets/urls.py
     url(r'^$', views.api_root),

2. Highlight snippet path

We also need to provide the path to the highlighted snippet. Of course, this path is different from the others, we want to use HTML instead of JSON to render. Django-rest_framework provides us with two ways to render HTML, one is to use templates, The other is the constructed HTML text. Since we have used pygments to convert the highlighted snippet into HTML text and store it in the database when creating the snippet, we use the second method.

Since what we return is not an object instance, but an attribute of an instance, django-rest-framework does not provide this generic class based view. So IWe need to use the basic view and create the get() method:

 # snippets/views.py
     from rest_framework import renderers
     from rest_framework.response import Response

     class SnippetHighlight  (generics.GenericAPIView):
         queryset = Snippet.objects.all()
         renderer_classes = (renderers.StaticHTMLRenderer,)

         def get  (self, request, *args, **kwargs):
             snippet = self.get_object()
             return Response  (snippet.highlighted)

Add the corresponding path in urls.py:

 # snippets/urls.py
     url(r'^snippets/(?P[  0-9]+)/highlight/$', views.  SnippetHighlight.as_view()),

3. Use hyperlinks

Dealing with the relationship between various component APIs is a headache. django-rest_framework provides us with the following methods to express relationships:

  • Use primary keys
  • Use hyperlinks
  • Use the slug field of the related item
  • Use default text information for related items
  • Display child items within parent item
  • Other expressions

This time, we use hyperlinks to reflect the relationship between user and snippet. In order to implement this method, we need to rewrite the serializers and use HyperlinkedModelSerializer instead of the original ModelSerializer. HyperlinkedModelSerializer has the following differences compared to ModelSerializer:

  • HyperlinkedModelSerializer does not automatically include pk field
  • HyperlinkedModelSerializer will automatically include the url field
  • The relationship uses HyperlinkedRelatedField instead of PrimaryKeyRelatedField
 # snippets/serializers.py
     class SnippetSerializer  (serializers.HyperlinkedModelSerializer):
         owner = serializers.Field(source='owner.username')
         highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')

         class Meta  :
             model = Snippet
             fields = ('url', 'highlight', 'owner',
                       'title', 'code', 'linenos', 'language', 'style')


     class UserSerializer  (serializers.HyperlinkedModelSerializer):
         snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')

         class Meta  :
             model = User
             fields = ('url', 'username', 'snippets')

Note that we also added the “highlight” field, which is the same as the url field, which is HyperlinkedRelatedField, but points to the snippet-highlight url instead of the snippet-detail url.

Since we include format information in the URL, we use the format=’html’ parameter to specify the .html suffix for highlight.

4. Add name to url

Edit snippets/urls.py as follows:

 # snippets/urls.py
     # API path
     urlpatterns = format_suffix_patterns(patterns('snippets.views',  
         url(r'^$', 'api_root'),
         url(r'^snippets/$',
             views.SnippetList.as_view(),span>
         owner = serializers.Field(source='owner.username')
         highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')

         class Meta  :
             model = Snippet
             fields = ('url', 'highlight', 'owner',
                       'title', 'code', 'linenos', 'language', 'style')


     class UserSerializer  (serializers.HyperlinkedModelSerializer):
         snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')

         class Meta  :
             model = User
             fields = ('url', 'username', 'snippets')

Note that we also added the “highlight” field, which is the same as the url field, which is HyperlinkedRelatedField, but points to the snippet-highlight url instead of the snippet-detail url.

Since we include format information in the URL, we use the format=’html’ parameter to specify the .html suffix for highlight.

4. Add name to url

Edit snippets/urls.py as follows:

 # snippets/urls.py
     # API path
     urlpatterns = format_suffix_patterns(patterns('snippets.views',  
         url(r'^$', 'api_root'),
         url(r'^snippets/$',
             views.SnippetList.as_view(),
             name='snippet-list'),
         url(r'^snippets/(?P[  0-9]+)/$',
             views.SnippetDetail.as_view(),
             name='snippet-detail'),
         url(r'^snippets/(?P[  0-9]+)/highlight/$',
             views.SnippetHighlight.as_view(),
             name='snippet-highlight'),
         url(r'^users/$',
             views.UserList.as_view(),
             name='user-list'),
         url(r'^users/(?P[  0-9]+)/$',
             views.UserDetail.as_view(),
             name='user-detail')
     ))

     # Browsable login API
     urlpatterns += patterns('',
         url(r'^api-auth/'  , include('rest_framework.  urls',
                                    namespace='rest_framework')),
     )

5. Pagination

If the data in the database reaches a certain level, users may return a large amount of data when using the API, so we’d better use the paging function:

We can use the setting options that come with django-rest-framework to make the list automatically use paging:

 # tutorial/settings.py
     REST_FRAMEWORK = {
         'PAGINATE_BY': 10
     }

6. Test

Now we can use the method mentioned before to test our API. You can see in /snippets/ that the original id has been replaced by url, and both url and highlight field are in the form of hyperlinks.

Original link: http://www.weiguda.com/blog/23/

name=‘snippet-list’),
url
(r‘^snippets/(?P[ 0-9]+)/$’,
views
.SnippetDetail.as_view(),
name
=‘snippet-detail’),
url
(r‘^snippets/(?P[ 0-9]+)/highlight/$’,
views
.SnippetHighlight.as_view(),
name
=‘snippet-highlight’),
url
(r‘^users/$’,
views
.UserList.as_view(),
name
=‘user-list’),
url
(r‘^users/(?P[ 0-9]+)/$’,
views
.UserDetail.as_view(),
name
=‘user-detail’)
))

# Browsable login API
urlpatterns
+= patterns(,
url
(r‘^api-auth/’ , include(‘rest_framework. urls’,
namespace=‘rest_framework’)),
)

5. Pagination

If the data in the database reaches a certain level, users may return a large amount of data when using the API, so we’d better use the paging function:

We can use the setting options that come with django-rest-framework to make the list automatically use paging:

 # tutorial/settings.py
     REST_FRAMEWORK = {
         'PAGINATE_BY': 10
     }

6. Test

Now we can use the method mentioned before to test our API. You can see in /snippets/ that the original id has been replaced by url, and both url and highlight field are in the form of hyperlinks.

Original link: http://www.weiguda.com/blog/23/

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/754392

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索