RESTFul API reference manual basis

This article provides the basics RESTFul API, including the basic concepts of RESTFul API, HTTP protocol knowledge, Spring REST support and so on.

Introduction REST

REST is not

Representational State Transfer (Representational State Transfer, REST) ​​information-centric has become a replacement for traditional SOAP Web services popular program. Their main difference is, SOAP will generally focus on behavior and treatment, and REST concern is data to be processed.

REST is not a "Web URL-based services", nor is it another type of remote procedure call (remote procedure call, RPC) mechanism. RPC is service-oriented, and focus on the behavior and actions; and REST is resource-oriented, emphasizing the description of the application objects and nouns.

What is REST

Representational RE- (Representational): REST resources can actually be expressed in a variety of forms, including XML, JSON (JavaScript Object Notation) even HTML-- best suited to any form of resource users.

S- state (State): When using REST, we are more concerned about the state of the resource rather than the behavior of resources taken.

T- transfer (Transfer): REST involve the transfer of resource data, it is transferred in some form of expression from one application to another.

Simply put, REST is to state resources in the form best suited to the client or the server is transferred from the server to the client (or vice versa)

REST resources

In REST, resource identification and location through a URL. As for the structure of RESTful URL is not strict rules, but should be able to identify a resource URL, rather than simply send a command to the server. Again, the core concern is the thing, not the behavior.

REST resources not referring to data, but the data and forms of combination, such as "10 members of the latest visit" and "10 most active member" in the data may have overlapping or identical, and because they different forms, it is classified as different resources.

REST in the state

REST there will be acts that are defined by the HTTP method. Specifically, that is, GET, POST, PUT, DELETE, PATCH and other HTTP methods constitute action in REST.

These methods typically HTTP match the CRUD following actions:

  • Create:POST
  • Read:GET
  • Update:PUT或PATCH
  • Delete:DELETE

Although generally speaking, HTTP methods are mapped to CRUD action, but this is not strictly limited. Sometimes, PUT can be used to create new resources, POST can be used to update the resource. Indeed, POST request is non-idempotent characteristics of (non-idempotent) makes it a very flexible approach to HTTP semantics can not accommodate other operations, which are capable.

REST与HTTP

HTTP Headers

HTTP header provides information about the request, response, or other information transmitting entity.

HTTP header information includes common header, the request header, and response header entity header portion of four. Each header field consists of a domain name, a colon (:) and the value of three parts.

  • General header: can be used to request, it can also be used for the response, as a whole rather than a particular resource associated with the transaction.
  • Request header: the client transmitting the response allows information about itself and form desired.
  • Response header: the server and transmitting a response to the information itself.
  • Entity header: Resources defined information is transmitted. Can be used for the request, the response may also be used.

HTTP Request Header

Request header:

Header Explanation Examples
Accept Content type of the client to receive the Accept: text/plain, text/html
Accept-Charset The browser can accept character encoding. Accept-Charset: iso-8859-5
Accept-Encoding Specifies the browser can support web server returns content compression encoding type. Accept-Encoding: compress, gzip
Accept-Language Browser language acceptable Accept-Language: en,zh
Accept-Ranges Entity can request a web page or a plurality of sub-range field Accept-Ranges: bytes
Authorization HTTP Authorization Certificate of Authorization Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control Cache mechanism specified requests and responses follow Cache-Control: no-cache
Connection Indicate the need for persistent connections. (HTTP 1.1 persistent connection by default) Connection: close
Cookie Cookie values ​​are sent with all HTTP request, the request will be stored at the domain name to the web server 。 Cookie: $Version=1; Skin=new;
Content-Length Requested content length Content-Length: 348
Content-Type MIME entity information corresponding to the request Content-Type: application/x-www-form-urlencoded
Date Date and time of the request Date: Tue, 15 Nov 2010 08:12:31 GMT
Expect Specific behavior of the server request Expect: 100-continue
From Email user requesting From: [email protected]
Host Specify the server requests the domain name and port number Host: www.zcmhi.com
If-Match Only the entity requesting the content matches the valid If-Match: “737060cd8c284d8af7ad3082f209582d”
If-Modified-Since If the request portion is modified request succeeds, not modified after the specified time code is returned 304 If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-Match If the content does not change the return code is 304, parameters for the previously transmitted Etag server, and the server response Etag comparison determination whether to change If-None-Match: “737060cd8c284d8af7ad3082f209582d”
If-Range If the entity is not changed, the server sends the client missing parts, or send the entire entity. Parameter also Etag If-Range: “737060cd8c284d8af7ad3082f209582d”
If-Unmodified-Since Only request was successful entity has not been modified after a specified time If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
Max-Forwards Limited time information transmitted through a proxy and gateway Max-Forwards: 10
Pragma To achieve specific instruction comprising Pragma: no-cache
Proxy-Authorization Connect to the proxy authorization certificate Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Range Only part of the request entity specified range Range: bytes=500-999
Referer Address of the previous page, requests a web page, followed by the current, i.e. antecedents Referer: www.zcmhi.com/archives/71…
TO Transmitting the encoded client is willing to accept, and notifies the server accepts receiving header information added at the end TE: trailers,deflate;q=0.5
Upgrade Specify certain transmission protocol to the server so that the server to convert (if supported) Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
User-Agen T User-Agent content comprises requesting the user information User-Agent: Mozilla/5.0 (Linux; X11)
Via Notification intermediate gateway or proxy server address, communication protocol Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning A warning message about an entity Warn: 199 Miscellaneous warning

HTTP Responses Header

Response headers:

Header Explanation Examples
Accept-Ranges It indicates whether the server supports the specified range requests and what type of segmentation request Accept-Ranges: bytes
Age 从原始服务器到代理缓存形成的估算时间(以秒计,非负 ) Age: 12
Allow 对某网络资源的有效的请求行为,不允许则返回405 Allow: GET, HEAD
Cache-Control 告诉所有的缓存机制是否可以缓存及哪种类型 Cache-Control: no-cache
Content-Encoding web服务器支持的返回内容压缩编码类型。 Content-Encoding: gzip
Content-Language 响应体的语言 Content-Language: en,zh
Content-Length 响应体的长度 Content-Length: 348
Content-Location 请求资源可替代的备用的另一地址 Content-Location: /index.htm
Content-MD5 返回资源的MD5校验值 Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
Content-Range 在整个返回体中本部分的字节位置 Content-Range: bytes 21010-47021/47022
Content-Type 返回内容的MIME类型 Content-Type: text/html; charset=utf-8
Date 原始服务器消息发出的时间 Date: Tue, 15 Nov 2010 08:12:31 GMT
ETag 请求变量的实体标签的当前值 ETag: “737060cd8c284d8af7ad3082f209582d”
Expires 响应过期的日期和时间 Expires: Thu, 01 Dec 2010 16:00:00 GMT
Last-Modified 请求资源的最后修改时间 Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT
Location 用来重定向接收方到非请求URL的位置来完成请求或标识新的资源 Location: www.zcmhi.com/archives/94…
Pragma 包括实现特定的指令,它可应用到响应链上的任何接收方 Pragma: no-cache
Proxy-Authenticate 它指出认证方案和可应用到代理的该URL上的参数 Proxy-Authenticate: Basic
refresh 应用于重定向或一个新的资源被创造,在5秒之后重定向(由网景提出,被大部分浏览器支持) Refresh: 5; url= www.zcmhi.com/archives/94…
Retry-After 如果实体暂时不可取,通知客户端在指定时间之后再次尝试 Retry-After: 120
Server web服务器软件名称 Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Set-Cookie 设置Http Cookie Set-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Trailer 指出头域在分块传输编码的尾部存在 Trailer: Max-Forwards
Transfer-Encoding 文件传输编码 Transfer-Encoding:chunked
Vary 告诉下游代理是使用缓存响应还是从原始服务器请求 Vary: *
Via 告知代理客户端响应是通过哪里发送的 Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning 警告实体可能存在的问题 Warning: 199 Miscellaneous warning
WWW-Authenticate 表明客户端请求实体应该使用的授权方案 WWW-Authenticate: Basic

HTTP Request Method

HTTP Request Method共计15种:

序号 方法 描述
1 GET 请求指定的页面信息,并返回实体主体。
2 HEAD 类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头
3 POST 向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。
4 PUT 从客户端向服务器传送的数据取代指定的文档的内容。
5 DELETE 请求服务器删除指定的页面。
6 CONNECT HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
7 OPTIONS 允许客户端查看服务器的性能。
8 TRACE 回显服务器收到的请求,主要用于测试或诊断。
9 PATCH 实体中包含一个表,表中说明与该URI所表示的原内容的区别。
10 MOVE 请求服务器将指定的页面移至另一个网络地址。
11 COPY 请求服务器将指定的页面拷贝至另一个网络地址。
12 LINK 请求服务器建立链接关系。
13 UNLINK 断开链接关系。
14 WRAPPED 允许客户端发送经过封装的请求。
15 Extension-mothed 在不改动协议的前提下,可增加另外的方法。

其中我们常用的POST请求数据被包含在请求体中,POST请求可能会导致新的资源的建立 和/或 已有资源的修改。

HTTP Status Code

HTTP状态码(英语:HTTP Status Code)是用以表示网页服务器超文本传输协议响应状态的3位数字代码。

HTTP状态码的第一个数字代表了响应的五种状态之一:

Value Description
1xx: Informational - Request received, continuing process
2xx: Success - The action was successfully received, understood, and accepted
3xx: Redirection - Further action must be taken in order to complete the request
4xx: Client Error - The request contains bad syntax or cannot be fulfilled
5xx: Server Error - The server failed to fulfill an apparently valid request

根据RFC7231规范,目前有以下HTTP状态码:

Value Description
100 Continue
101 Switching Protocols
102 Processing
103 Early Hints
104-199 Unassigned
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status
208 Already Reported
209-225 Unassigned
226 IM Used
227-299 Unassigned
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
306 (Unused)
307 Temporary Redirect
308 Permanent Redirect
309-399 Unassigned
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Payload Too Large
414 URI Too Long
415 Unsupported Media Type
416 Range Not Satisfiable
417 Expectation Failed
418-420 Unassigned
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
425 Too Early
426 Upgrade Required
427 Unassigned
428 Precondition Required
429 Too Many Requests
430 Unassigned
431 Request Header Fields Too Large
432-450 Unassigned
451 Unavailable For Legal Reasons
452-499 Unassigned
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates
507 Insufficient Storage
508 Loop Detected
509 Unassigned
510 Not Extended
511 Network Authentication Required
512-599 Unassigned

HTTP Content-type

Content-Type,内容类型,一般是指网页中存在的Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件。

比如输出图片文件、JSON数据、XML文件等非HTML内容时,就必须用header函数来指定Content-Type,才能达到输出一张图片或是其它指定内容类型的需求。

下面列举一些常用的内容类型:

文件扩展名 Content-Type(Mime-Type) 描述
.pdf application/pdf PDF(Portable Document Format的简称,意为“便携式文件格式”)
.json application/json JSON(JavaScript Object Notation)
.js application/javascript ECMAScript/JavaScript(相当于application/ecmascript但是宽松的处理规则)
.xml application/xml 可扩展标记语言(英语:eXtensible Markup Language,简称: XML),是一种标记语言。
.zip application/zip ZIP压缩文件
.gzip application/gzip Gzip是若干种文件压缩程序的简称,通常指GNU计划的实现,此处的gzip代表GNU zip。
.csv text/csv 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。
.html text/html
.mp3 audio/mp3
.mp4 audio/mp4 MP4,全称MPEG-4 Part 14,是一种使用MPEG-4的多媒体计算机文件格式,扩展名为.mp4,以存储数字音频及数字视频为主。
.tif image/tiff 标签图像文件格式(Tagged Image File Format,简写为TIFF)是一种主要用来存储包括照片和艺术图在内的图像的文件格式。它最初由Aldus公司与微软公司一起为PostScript打印开发。
.gif image/gif 图像互换格式(GIF,Graphics Interchange Format)是一种位图图形文件格式,以8位色(即256种颜色)重现真彩色的图像。
.jpeg image/jpeg JPEG是一种针对相片图像而广泛使用的一种有损压缩标准方法。
.png image/png 便携式网络图形(Portable Network Graphics,PNG)是一种无损压缩的位图图形格式,支持索引、灰度、RGB三种颜色方案以及Alpha通道等特性。

REST与Spring

Spring很早就有导出REST资源的需求。Spring对REST的支持是构建在Spring MVC之上的。从3.0版本开始,Spring针对Spring MVC的一些增强功能对REST提供了良好的支持。

Spring4.0 REST特性

4.0版本中,Spring支持以下方式来创建REST资源:

  • 控制器可以处理所有的HTTP方法,包含四个主要的REST方法:GET、PUT、DELETE以及POST。
package org.springframework.web.bind.annotation;
/**
 * Java 5 enumeration of HTTP request methods. 
 * @since 2.5
 */
public enum RequestMethod {
	GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
}
复制代码
  • Spring 3.2及以上版本还支持PATCH方法。

  • 借助@PathVariable注解,控制器能够处理参数化的URL(将变量输入作为URL的一部分)。

  • 借助Spring的视图和视图解析器,资源能够以多种方式进行表述,包括将模型数据渲染为XML、JSON、Atom以及RSS的View实现。

  • 可以使用ContentNegotiatingViewResolver来选择最适合客户端的表述。

  • 借助@ResponseBody注解和各种HttpMethodConverter实现,能够替换基于视图的渲染方式。

  • @RequestBody注解以及HttpMethodConverter实现可以将传入的HTTP数据转化为传入控制器处理方法的Java对象。

  • 借助RestTemplate,Spring应用能够方便地使用REST资源。

  • 通过ResponseEntity对象,可以封装HTTP返回的header、body和statusCode。

Links

代码资源

文章资源

参考资源

转载于:https://juejin.im/post/5cf933645188252c023fa3d9

Guess you like

Origin blog.csdn.net/weixin_34192732/article/details/91459019