【转】最佳Restful API 实践
原文转自:https://bourgeois.me/rest/
REST APIs are a very common topic nowaday; they are part of almost every web application. A simple, consistent and pragmatic interface is a mandatory thing; it will be much easier for others to use your API. Even if these practices may look common to your eye, I often see people that don't really respect them. That's why I decided to write a post about it.
Here are some best practices to keep in mind while designing a RESTful API.
Discalmer: these best practices are what I think is good, based from my past expriences. If you think otherwise, feel free to send me an email so we can have a discussion about it.
Version your API
API versions should be mandatory. This way, you will be futureproof as the API changes through time. One way is to do is to pass the API version in the URL (/api/v1/...).
One other neat trick is to use the Accept HTTP header to pass the verison desired. Github does that.
Using versions will allow you to change the API structure without breaking compatibility with older clients.
Use nouns, not verbs
One thing I often see is people using verbs instead of nouns in their resources name. Here are some bad examples :
/getProducts/listOrders/retreiveClientByOrder?orderId=1
For a clean and conscice structure, you should always use nouns. Moreover, a good use of HTTP methods will allow you to remove actions from your resources names. Here is a much cleaner example :
GET /products: will return the list of all productsPOST /products: will add a product to the collectionGET /products/4: will retreive product #4PATCH/PUT /products/4: will update product #4
Use the plural form
In my opinion, it is not a really good idea to mix singular and plural forms in a single resource naming; it can quickly become confusing and non consistent.
Use /artists instead of /artist, even for the show/delete/update actions
GET and HEAD calls should always be safe
RFC2616 cleary states that HEAD and GET methods should always be safe to call (in other words, the state should not be altered).
Here is a bad example: GET /deleteProduct?id=1
Imagine a search engine indexing that page...
Use nested resources
If you want to get a sub collection (collection of an other one), use nested routing for a cleaner design. For instance, if you want to get a list of all albums of a particular artist, you would want to use :
GET /artists/8/albums
Paging
Returning a very large resultset over HTTP is not a very good idea neither. You will eventually run into performance issues as serializing a large JSON may quickly become expensive.
An option to get around that would be to paginate your results. Facebook, Twitter, Github, etc. does that. It is much more efficient to make more calls that takes little time to complete, than a big one that is very slow to execute.
Also, if you are using pagination, one good way to indicate the next and previous pages links is through the Link HTTP header. Github does that too.
Use proper HTTP status codes
Always use proper HTTP status codes when returning content (for both successful and error requests). Here a quick list of non common codes that you may want to use in your application.
Success codes
201 Createdshould be used when creating content (INSERT),202 Acceptedshould be used when a request is queued for background processing (async tasks),204 No Contentshould be used when the request was properly executed but no content was returned (a good example would be when you delete something).
Client error codes
400 Bad Requestshould be used when there was an error while processing the request payload (malformed JSON, for instance).401 Unauthorizedshould be used when a request is not authenticiated (wrong access token, or username or password).403 Forbiddenshould be used when the request is successfully authenticiated (see 401), but the action was forbidden.406 Not Acceptableshould be used when the requested format is not available (for instance, when requesting an XML resource from a JSON only server).410 GoneShould be returned when the requested resource is permenantely deleted and will never be available again.422 Unprocesable entityCould be used when there was a validation error while creating an object.
A more complete list of status codes can be found in RFC2616.
Always return a consistent error payload
When an exception is raised, you should always return a consistent payload describing the error. This way, it will be easier for other to parse the error message (the structure will always be the same, whatever the error is).
Here one I often use in my web applications. It is clear, simple and self descriptive.
HTTP/1.1 401 Unauthorized
{
"status": "Unauthorized",
"message": "No access token provided.",
"request_id": "594600f4-7eec-47ca-8012-02e7b89859ce"
}
【转】最佳Restful API 实践的更多相关文章
- 基于Spring Boot的RESTful API实践(一)
1. RESTful简述 REST是一种设计风格,是一组约束条件及原则,而遵循REST风格的架构就称为RESTful架构,资源是RESTful的核心,一个好的RESTful架构,通过URL就能很 ...
- 通俗易懂的RESTful API实践详解(含代码)
来源:点击进入 点击上方链接,版面更好 一.什么是RESTful REST 是面向资源的,这个概念非常重要,而资源是通过 URI 进行暴露,URI 的设计只要负责把资源通过合理方式暴露出来就可以了,对 ...
- RESTful API实践总结
REST架构 你是如何理解上网这件事的? 打开浏览器,输入网址,展现在你面前的就是一个网站了. 你可以在网站里看视频.看博客.写文章.听音乐. 但凡写过点代码的人都知道,我们平时访问的网站,其实是HT ...
- RESTful API 设计最佳实践
背景 目前互联网上充斥着大量的关于RESTful API(为了方便,以后API和RESTful API 一个意思)如何设计的文章,然而却没有一个"万能"的设计标准:如何鉴权?API ...
- [转]10个有关RESTful API良好设计的最佳实践
Web API已经在最近几年变成重要的话题,一个干净的API设计对于后端系统是非常重要的. 通常我们为Web API使用RESTful设计,REST概念分离了API结构和逻辑资源,通过Http方法GE ...
- 10个有关RESTful API良好设计的最佳实践
Web API已经在最近几年变成重要的话题,一个干净的API设计对于后端系统是非常重要的. 通常我们为Web API使用RESTful设计,REST概念分离了API结构和逻辑资源,通过Http方法GE ...
- ****RESTful API 设计最佳实践(APP后端API设计参考典范)
http://blog.jobbole.com/41233/ 背景 目前互联网上充斥着大量的关于RESTful API(为方便,下文中“RESTful API ”简写为“API”)如何设计的文章,然而 ...
- RESTful API 设计最佳实践(转)
摘要:目前互联网上充斥着大量的关于RESTful API(为了方便,以后API和RESTful API 一个意思)如何设计的文章,然而却没有一个”万能“的设计标准:如何鉴权?API格式如何?你的API ...
- RESTful API 设计最佳实践(转)
背景 目前互联网上充斥着大量的关于RESTful API(为方便,下文中“RESTful API ”简写为“API”)如何设计的文章,然而却没有一个”万能“的设计标准:如何鉴权?API 格式如何?你的 ...
随机推荐
- thinkjs中自定义sql语句
一直以为在使用thinkjs时,只能是它自带的sql语句查询,当遇到类似于这样的sql语句时,却不知道这该怎样来写程序,殊不知原来thinkjs可以执行自定义sql语句 SELECT * from a ...
- QT-4.8.6 编译配置过程
1.编译 TSLib sudo apt-get install automake autogen libtool libtool-bin./autogen.sh./configure --host=a ...
- c#文本框限制输入内容
//限制输入不能为中文和全角 private void zhbh_KeyPress(object sender, KeyPressEventArgs e) { ...
- spark发行版笔记11
本期概览: ReceiverTracker架构设计 消息循环系统 ReceiverTracker具体的实现 Spark Streaming作为Spark Core基础 架构之上的一个应用程序,其中的R ...
- python网络编程【一】
TCP/IP 是标准的协议,它可以使用世界范围内的计算机通过Internet或本地的网络通信 1.编写一个TCP客户端程序 #!/usr/bin/env python import socket, s ...
- [CodeForces - 712D]Memory and Scores (DP 或者 生成函数)
题目大意: 两个人玩取数游戏,第一个人分数一开始是a,第二个分数一开始是b,接下来t轮,每轮两人都选择一个[-k,k]范围内的整数,加到自己的分数里,求有多少种情况使得t轮结束后a的分数比b高. ( ...
- jsp页面验证码(完整实例)
项目结构如下,MyEclipse中新建一个Web Project,取名servlet 1.src下new一个servlet类 package com.servlet; import java.awt. ...
- lnmp 设置ci pathinfo和去掉index.php
LNMP上各个版本pathinfo各个版本的设置基本一样: lnmp v1.1上,修改对应虚拟主机的配置文件去掉#include pathinfo.conf前面的#,把try_files $uri = ...
- OC基础--构造方法 id类型
new方法实现原理: new做了三件事情 1.开辟存储空间 + alloc 方法 2.初始化所有的属性(成员变量) - init 方法 3.返回对象的地址 [Person new]; == [[Pe ...
- ThinkPHP模板中如何操作session,以及如果session中保存的是数组的情况
在ThinkPHP的模板中操作session时,可以参考ThinkPHP参考文档中的“模板—>系统变量”部分,在默认模板引擎中,语法如下: {$Think.session.user} //输出s ...