DRF使用超链接API实现真正RESTful

本文探讨了RESTful API的设计原则,强调了超文本驱动的重要性。通过示例介绍了如何在Django Rest Framework(DRF)中创建超链接API,包括创建api_root的Endpoint、SnippetHighlight的Endpoint,以及使用HyperlinkedModelSerializer来改进Serializer,实现真正的RESTful特性。同时,文章还提到了添加分页功能的方法。
摘要由CSDN通过智能技术生成

很多API并不是真正的实现了RESTful,而应该叫做RPC (Remote Procedure Call 远程过程调用),Roy Fielding曾经提到了它们的区别,原文如下:

I am getting frustrated by the number of people calling any HTTP-based interface a REST API. Today’s example is the SocialSite REST API. That is RPC. It screams RPC. There is so much coupling on display that it should be given an X rating.

What needs to be done to make the REST architectural style clear on the notion that hypertext is a constraint? In other words, if the engine of application state (and hence the API) is not being driven by hypertext, then it cannot be RESTful and cannot be a REST API. Period. Is there some broken manual somewhere that needs to be fixed?
www.bjcar666.com
— Roy Fielding
https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

大概意思是,如果应用状态引擎(API)不是超文本驱动的,那么就不是RESTful。

我的理解是,像超文本一样携带一个地址,可以寻址定位信息,如超文本的link属性。

超链接(Hypermedia)API

Hypermedia指的是,返回结果中提供链接,连向其他API方法,使得用户不查文档,也知道下一步应该做什么。比如,当用户向api.example.com的根目录发出请求,会得到这样一个文档:

{“link”: {
“rel”: “collection https://www.example.com/zoos”,
“href”: “https://api.example.com/zoos”,
“title”: “List of zoos”,
“type”: “application/vnd.yourformat+json”
}}

上面代码表示,文档中有一个link属性,用户

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值