Django REST Framework Chapter Fifth Relationships & hyperlinked APIs

Source: Internet
Author: User

So far, the relationships within the API are represented by using primary keys. In this tutorial, we will improve the cohesion and visibility of the API by using hyperlinks on the interrelationships.

Creating An endpoint for the root of our API

Now that we have the snippets and users terminals, there is no single endpoint pointing to our API. Create one using the usual FBV method and the @api_view adorner. Within the views file of your app

 fromRest_framework.decoratorsImportApi_view fromRest_framework.responseImportResponse fromRest_framework.reverseImportReverse@api_view (['GET'])defApi_root (Request, format=None):returnResponse ({'Users': Reverse ('user-list', Request=request, format=format),'Snippets': Reverse ('snippet-list', Request=request, format=format)})

There are two points to note. First, the rest framework's reverse method is used to return the fully qualified URLs, followed by the convenient name identified later in the app's URLs file by the URL pattern.

Creating an endppoint for the highlighted snippets

Another obvious problem is that the code-highlighting endpoint is still missing from our API.

Unlike the API endpoints we wrote earlier, we don't want to use JSON, instead of the Web page's representation. The REST Framework provides 2 styles of HTML transformations, one for processing HTML using template rendering, and the other for processing pre-rendered HTML. The second renderer is the one we'd like to use at this endpoint.

There is another thing to consider when creating code highlighting views, there is no integrated common view that we can use. We are not going to return an object instance, instead of a property of an object instance.

Show examples we will be able to use the base class instead of the integrated common view and then create a GET method. In the app's views file, add:

 from Import renderers  from Import Response class Snippethighlight (generics. Genericapiview):    = Snippet.objects.all ()    = (renderers. Statichtmlrenderer,)    def get (self, request, *args, * *Kwargs)        := Self.get _object ()        return Response (snippet.highlighted)

As before, there is a need to add a new URL and view bindings. Add a URL pattern to the new API root in the app's URLs file:

    Path (", Views.api_root),

Then add a new URL pattern:

    Path ('snippets/<int:pk>/highlight/', views. Snippethighlight.as_view ()),

hyperlinking our API

Dealing with the relationships between entities is one of the more challenging aspects of Web API design. There are many different ways in which we can choose to represent this relationship.

A. Using the primary key

B. Use hyperlinks between entities

C. Use unique identification fields on related entities

D, using the default string representation of the related entity

E. Nesting related entities in parent representations

F, some other self-customized representations

The REST framework supports all of these methods and can be applied to a forward reverse relationship, or to custom management (such as a common foreign key)

In this case, we are more inclined to use hyperlinks between entities. To be able to do this, we are going to modify serializers to extend hyperlinkedmodelserializer instead of the existing Modelserializer:

1. The ID field is not included by default

2. It contains a URL field, using Hyperlinkedidentityfield

3, the relationship with Primarykeyrelatedfield instead of Hyperlinkedrelatedfield

With hyperlinks you can easily rewrite existing serializers and add them within the app's serializers.py file:

classSnippetserializer (serializers. Hyperlinkedmodelserializer): Owner= serializers. Readonlyfield (source='Owner.username') Highlight= serializers. Hyperlinkedidentityfield (view_name='Snippet-highlight', format='HTML')    classMeta:model=Snippet Fields= ('URL','ID','Highlight','owner',                  'title','Code','Linenos','language','style')classUserserializer (serializers. Hyperlinkedmodelserializer): Snippets= serializers. Hyperlinkedrelatedfield (Many=true, view_name='Snippet-detail', read_only=True)classMeta:model=User Fields= ('URL','ID','username','Snippets')

Note that a highlight field is added, which is the same type as the URL field, except that it points to 'snippet-highlight' instead of 'snippet-detail' URL pattern. Because we include the rul of the formatted suffix, such as json, it is also necessary to indicate on the highlight field that any hyperlink to the formatted suffix it returns should use the . html suffix.

Making sure our URL patterns is named

If we want to use the hyperlink API, we need to make sure ur is named. Take a look at those URLs that need to be named

A, the root API that references 'user-list' and 'snippet-list'

b, one of the fields contained in snippet serializer 'snippet-highlight'

C, a field contained in the user serializer reference 'snippet-detail'

D, the default snippet and user serializers contain the URL field, will refer to ' {model_name}-detail ', in this case will be‘snippet-detail‘和‘user-detail‘

Once these names are all added to the URL configuration, the URLs in the final app should look like this:

 fromApp01Import views fromDjango.urlsImportpath, include fromRest_framework.urlpatternsImportFormat_suffix_patternsapp_name='APP01'Urlpatterns=[Path ('snippets/', views. Snippetlist.as_view (), name='snippet-list'), Path ('snippets/<int:pk>/', views. Snippetdetail.as_view (), name='Snippet-detail'), Path ('users/', views. Userlist.as_view (), name='user-list'), Path ('users/<int:pk>/', views. Userdetail.as_view (), name='User-detail'), Path ('snippets/<int:pk>/highlight/', views. Snippethighlight.as_view (), name='Snippet-highlight'), Path ("', Views.api_root),]urlpatterns= Format_suffix_patterns (Urlpatterns)

Adding pagination

The list of views with the users and code snippets can eventually return many instances, so we really want to make sure that the results are paginated, allowing the API clients to traverse each individual page one at a.

You can change the default list style to use pagination by slightly modifying the settings file in your app:

Rest_framework = {    'default_pagination_class'rest_ Framework.pagination.PageNumberPagination',    'page_size' : Ten}

Note that all the settings in the REST FRAMEWORK are named in a separate dictionary rest_framework , which helps us to separate the settings of other projects well.

If necessary, we can also customize the paging form, but in this case we just deal with the default paging.

Django REST Framework Chapter Fifth Relationships & hyperlinked APIs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.