Tutorial 5: Relationships & Hyperlinked APIs
转载自:http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/
Tutorial 5: Relationships & Hyperlinked APIs
At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships.
Creating an endpoint for the root of our API
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the @api_view
decorator we introduced earlier. In your snippets/views.py
add:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@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)
})
Two things should be noticed here. First, we're using REST framework's reverse
function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our snippets/urls.py
.
Creating an endpoint for the highlighted snippets
The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints.
Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint.
The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance.
Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own .get()
method. In your snippets/views.py
add:
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)
As usual we need to add the new views that we've created in to our URLconf. We'll add a url pattern for our new API root in snippets/urls.py
:
url(r'^$', views.api_root),
And then add a url pattern for the snippet highlights:
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
Hyperlinking our API
Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:
- Using primary keys.
- Using hyperlinking between entities.
- Using a unique identifying slug field on the related entity.
- Using the default string representation of the related entity.
- Nesting the related entity inside the parent representation.
- Some other custom representation.
REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys.
In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend HyperlinkedModelSerializer
instead of the existing ModelSerializer
.
The HyperlinkedModelSerializer
has the following differences from ModelSerializer
:
- It does not include the
id
field by default. - It includes a
url
field, usingHyperlinkedIdentityField
. - Relationships use
HyperlinkedRelatedField
, instead ofPrimaryKeyRelatedField
.
We can easily re-write our existing serializers to use hyperlinking. In your snippets/serializers.py
add:
class SnippetSerializer(serializers.HyperlinkedModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
highlight = serializers.HyperlinkedIdentityField(view_name='snippet-highlight', format='html')
class Meta:
model = Snippet
fields = ('url', 'id', 'highlight', 'owner',
'title', 'code', 'linenos', 'language', 'style')
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
class Meta:
model = User
fields = ('url', 'id', 'username', 'snippets')
Notice that we've also added a new 'highlight'
field. This field is of the same type as the url
field, except that it points to the 'snippet-highlight'
url pattern, instead of the 'snippet-detail'
url pattern.
Because we've included format suffixed URLs such as '.json'
, we also need to indicate on the highlight
field that any format suffixed hyperlinks it returns should use the '.html'
suffix.
Making sure our URL patterns are named
If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name.
- The root of our API refers to
'user-list'
and'snippet-list'
. - Our snippet serializer includes a field that refers to
'snippet-highlight'
. - Our user serializer includes a field that refers to
'snippet-detail'
. - Our snippet and user serializers include
'url'
fields that by default will refer to'{model_name}-detail'
, which in this case will be'snippet-detail'
and'user-detail'
.
After adding all those names into our URLconf, our final snippets/urls.py
file should look like this:
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
# API endpoints
urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^snippets/$',
views.SnippetList.as_view(),
name='snippet-list'),
url(r'^snippets/(?P<pk>[0-9]+)/$',
views.SnippetDetail.as_view(),
name='snippet-detail'),
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
views.SnippetHighlight.as_view(),
name='snippet-highlight'),
url(r'^users/$',
views.UserList.as_view(),
name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$',
views.UserDetail.as_view(),
name='user-detail')
])
# Login and logout views for the browsable API
urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
Adding pagination
The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages.
We can change the default list style to use pagination, by modifying our tutorial/settings.py
file slightly. Add the following setting:
REST_FRAMEWORK = {
'PAGE_SIZE': 10
}
Note that settings in REST framework are all namespaced into a single dictionary setting, named 'REST_FRAMEWORK', which helps keep them well separated from your other project settings.
We could also customize the pagination style if we needed too, but in this case we'll just stick with the default.
Browsing the API
If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links.
You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations.
In part 6 of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API.
Tutorial 5: Relationships & Hyperlinked APIs的更多相关文章
- 05_Tutorial 5: Relationships & Hyperlinked APIs 关系和超链接
1.关系和超链接 0.文档 https://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/ h ...
- Django REST framework 第五章 Relationships & Hyperlinked APIs
到目前为止,API内部的关系是使用主键来代表的.在这篇教程中,我们将提高API的凝聚力和可发现性,通过在相互关系上使用超链接. Creating an endpoint for the root of ...
- 5,基于关系和超链接的 API
Tutorial 5: Relationships & Hyperlinked APIs At the moment relationships within our API are repr ...
- django-rest-framework快速入门
前言:第一次接触django-rest-framework是在实习的时候.当时也不懂,看到视图用类方法写的感觉很牛逼的样子.因为官网是英文的,这对我的学习还是有一点的阻力的,所以当时也没怎么学.真是太 ...
- django rest framework 详解
Django REST framework 是用于构建Web API 的强大而灵活的工具包. 我们可能想使用REST框架的一些原因: Web浏览API对于开发人员来说是一个巨大的可用性. 认证策略包括 ...
- drf 教程
1, 序列化 Serialization 创建一个新环境 在做其他事之前,我们会用virtualenv创建一个新的虚拟环境.这将确保我们的包配置与我们正在工作的其他项目完全隔离. virtualenv ...
- Hibernate quick start
Preface Working with both Object-Oriented software and Relational Databases can be cumbersome and ti ...
- Apache Atlas
atlas英 [ˈætləs] 阿特拉斯. 美 [ˈætləs] n.地图集;〈比喻〉身负重担的人 == Apache Atlas Version: 1.1.0 Last Published: 201 ...
- django restframework 简单总结
官方文档:http://www.django-rest-framework.org/ model.py class Snippet(models.Model): created = models.Da ...
随机推荐
- [BZOJ4553][HEOI2016]序列 CDQ分治
4553: [Tjoi2016&Heoi2016]序列 Time Limit: 20 Sec Memory Limit: 128 MB Description 佳媛姐姐过生日的时候,她的小伙 ...
- mysql安装使用详细教程
1.数据库存储数据的方式与Excel类似. 一.数据库介绍 1.什么是数据库? 数据库(Database)是按照数据结构来组织.存储和管理数据的仓库, 每个数据库都有一个或多个不同的API用于创建,访 ...
- WPA-PSK无线网络破解原理及过程
原文链接地址:http://www.freebuf.com/articles/wireless/58342.html 本文将主要讲讲WPA-PSK类型的无线网络安全问题,首先我们看下802.11协议相 ...
- 利用MailSniper越权访问Exchange邮箱
0x01 概述 Microsoft Exchange用户可以授权给其他用户对其邮箱文件夹进行各种级别的访问.例如,用户可以授予其他用户读取访问其收件箱中里面的电子邮件,但是要是用户(或Exchange ...
- [Wf2011]Chips Challenge
两个条件都不太好处理 每行放置的个数实际很小,枚举最多放x 但还是不好放 考虑所有位置先都放上,然后删除最少使得合法 为了凑所有的位置都考虑到,把它当最大流 但是删除最少,所以最小费用 行列相关,左行 ...
- Django CRM客户关系管理系统
CRM需求分析 随着信息化时代带来的科技创新,CRM客户关系管理系统带来的效益在已经成为很多企业提高竞争优势的一分部,CRM客户关系管理系统将企业管理和客户关系管理集成到统一的平台,其系统功能主要体现 ...
- 流媒体协议之JRTPLIB的使用20170919
主要介绍JRTPLIB 2.x系列和3.x系列两种版本,它们的区别是2.x系列代码量少使用简单,但是只支持RFC 1889不支持RFC 3550,3.x支持RFC 3550,但代码量稍多,以及使用也稍 ...
- TopCoder SRM420 Div1 500pt RedIsGood
桌面上有R 张红牌和B 张黑牌,随机打乱顺序后放在桌面上,开始一张一张地翻牌,翻到红牌得到1 美元,黑牌则付出1 美元.可以随时停止翻牌,在最优策略下平均能得到多少钱. R,B ≤ 100000. 输 ...
- array_diff、array_diff_key、array_diff_ukey、array_diff_assoc、array_diff_uassoc 的用法
<?php // array_diff* 系列的函数都返回关联数组// array_diff* 系列函数返回数组的差集(返回在第一个参数中, 但不在其他参数中的元素) $array1 = [ ' ...
- VLFeat在matlab和vs中安装
转:http://blog.csdn.net/u011718701/article/details/51452011 博主最近用vlfeat库做课题,网上搜索使用方法,一大片都会告诉你说:run(/v ...