Understanding REST and RESTful APIs

Understanding REST and RESTful APIs

If you've spent any amount of time with modern web development, you will have come across terms like REST and API. If you've heard of these terms or work with APIs but don't have a complete understanding of how they work or how to build your own API, this series is for you.

如果您花了很多时间进行现代Web开发,那么您将遇到诸如REST和API之类的术语。如果您听说过这些术语或使用过API,但对它们的工作方式或如何构建自己的API没有完全的了解,那么本系列适合您

In this tutorial series, we will start with an overview of REST principles and concepts. Then we will go on to create our own full-fledged API that runs on a Node.js Express server and connects to a MySQL database. After finishing this series, you should feel confident building your own API or delving into the documentation of an existing API.

在本教程系列中,我们将从REST原理和概念的概述开始。然后,我们将继续创建自己的成熟API,该API在Node.js Express服务器上运行并连接到MySQL数据库。完成本系列后,您应该自信地构建自己的API或研究现有API的文档

Prerequisites

In order to get the most out of this tutorial, you should already have some basic command line knowledge, know the fundamentals of JavaScript, and have Node.js installed globally.

What Are REST and RESTful APIs?

Representational State Transfer, or REST, describes an architectural style for web services. REST consists of a set of standards or constraints for sharing data between different systems, and systems that implement REST are known as RESTful. REST is an abstract concept, not a language, framework, or type of software.

代表性状态转移(REST)描述了Web服务的体系结构样式。REST由一组用于在不同系统之间共享数据的标准或约束组成,实现REST的系统称为RESTful。REST是一个抽象概念,不是语言,框架或软件类型

An API is an Application Programming Interface, which is an interface that allows software programs to communicate with each other. A RESTful API is simply an API that adheres to the principles and constraints of REST. In a Web API, a server receives a request through a URL endpoint and sends a response in return, which is often data in a format such as JSON.

API是应用程序编程接口,它是允许软件程序相互通信的接口。RESTful API只是遵循REST原理和约束的API。在Web API中,服务器通过URL端点接收请求并返回响应,该响应通常是JSON等格式的数据

一、起源

REST这个词,是Roy Thomas Fielding在他2000年的博士论文中提出的。REST全称是Representational State Transfer,中文意思是表述性状态转移。 它首次出现在2000年Roy Fielding的博士论文中,Roy Fielding是HTTP规范的主要编写者之一。 他在论文中提到:"我这篇文章的写作目的,就是想在符合架构原理的前提下,理解和评估以网络为基础的应用软件的架构设计,得到一个功能强、性能好、适宜通信的架构。REST指的是一组架构约束条件和原则。" 如果一个架构符合REST的约束条件和原则,我们就称它为RESTful架构。

REST本身并没有创造新的技术、组件或服务,而隐藏在RESTful背后的理念就是使用Web的现有特征和能力, 更好地使用现有Web标准中的一些准则和约束。虽然REST本身受Web技术的影响很深, 但是理论上REST架构风格并不是绑定在HTTP上,只不过目前HTTP是唯一与REST相关的实例。 所以我们这里描述的REST也是通过HTTP实现的REST

REST Principles

Six guiding constraints define the REST architecture, outlined below.

六个指导性约束定义了REST体系结构,概念如下

  1. Uniform Interface: The interface of components must be the same. This means using the URI standard to identify resources—in other words, paths that could be entered into the browser's location bar.

    统一接口:组件的接口必须相同。这意味着使用URI标准来标识资源,即可以输入到浏览器位置栏中的路径

  2. Client-Server: There is a separation of concerns between the server, which stores and manipulates data, and the client, which requests and displays the response.

    客户端服务:在存储和处理数据的服务器与请求和显示响应的客户端之间存在关注点分离

  3. Stateless Interactions: All information about each request is contained in each individual request and does not depend on session state.

    无状态互动:有关每个请求的所有信息都包含在每个单独的请求中,并且不依赖于会话状态

  4. Cacheable: The client and server can cache resources.

    可缓存的:客户端和服务器可以缓存资源

  5. Layered System: The client can be connected to the end server, or an intermediate layer such as a load-balancer.

    分层系统:客户端可以连接到最终服务器,也可以连接到中间层(例如负载平衡器)

  6. Code on Demand (Optional): A client can download code, which reduces visibility from the outside.

    按需编码(可选)客户端可以下载代码,从而减少了外部可见性

Request and Response

You will already be familiar with the fact that all websites have URLs that begin with http (or https for the secure version). HyperText Transfer Protocol, or HTTP, is the method of communication between clients and servers on the internet.

您已经熟悉以下事实:所有网站都具有以http(对于安全版本为https)开头的URL。超文本传输协议或HTTP是Internet上客户端与服务器之间进行通信的方法

We see it most obviously in the URL bar of our browsers, but HTTP can be used for more than just requesting websites from servers. When you go to a URL on the web, you are actually doing a GET request on that specific resource, and the website you see is the body of the response. We will go over GET and other types of requests shortly.

我们在浏览器的URL栏中会很明显地看到它,但是HTTP不仅可以用于从服务器请求网站,还可以用于其他用途。当您访问Web上的URL时,实际上是在对该特定资源执行GET请求,并且您看到的网站是响应的主体。我们将很快处理GET和其他类型的请求

HTTP works by opening a TCP (Transmission Control Protocol) connection to a server port (80 for http, 443 for https) to make a request, and the listening server responds with a status and a body.

HTTP的工作方式是打开与服务器端口的TCP(传输控制协议)连接(HTTP为80,HTTPS为443)以发出请求,侦听服务器以状态和正文进行响应。

A request must consist of a URL, a method, header information, and a body.

请求必须包含URL,方法,标头信息和正文

Request Methods

There are four major HTTP methods, also referred to as HTTP verbs, that are commonly used to interact with web APIs. These methods define the action that will be performed with any given resource.

有四种主要的HTTP方法,也称为HTTP动词,通常用于与Web API进行交互。这些方法定义将对任何给定资源执行相应操作

HTTP request methods loosely correspond to the paradigm of CRUD, which stands for Create, Update, Read, Delete. Although CRUD refers to functions used in database operations, we can apply those design principles to HTTP verbs in a RESTful API.

HTTP请求方法大致对应于CRUD的范例,CRUD代表创建,更新,读取,删除。尽管CRUD指的是数据库操作中使用的功能,但是我们可以将这些设计原理应用于RESTful API中的HTTP动词

Action Request Method Definition
Read GET Retrieves a resource
Create POST Creates a new resource
Update PUT Updates an existing resource
Delete DELETE Deletes a resource

GET is a safe, read-only operation that will not alter the state of a server. Every time you hit a URL in your browser, such as https://www.google.com, you are sending a GET request to Google's servers.

GET是一种安全的只读操作,不会更改服务器的状态。每次您在浏览器中点击一个URL(例如https://www.google.com)时,您都会向Google的服务器发送GET请求

POST is used to create a new resource. A familiar example of POST is signing up as a user on a website or app. After submitting the form, a POST request with the user data might be sent to the server, which will then write that information into a database.

POST用于创建新资源。POST的一个常见示例是在网站或应用程序上以用户身份注册。提交表单后,带有用户数据的POST请求可能会发送到服务器,然后服务器会将信息写入数据库

PUT updates an existing resource, which might be used to edit the settings of an existing user. Unlike POST, PUT is idempotent, meaning the same call can be made multiple times without producing a different result. For example, if you sent the same POST request to create a new user in a database multiple times, it would create a new user with the same data for each request you made. However, using the same PUT request on the same user would continuously produce the same result.

PUT更新现有资源,该资源可用于编辑现有用户的设置。与POST不同,PUT是幂等的,这意味着可以多次进行同一调用,而不会产生不同的结果。例如,如果您多次发送相同的POST请求以在数据库中创建一个新用户,则它将为您发出的每个请求创建一个具有相同数据的新用户。但是,在同一用户上使用相同的PUT请求将连续产生相同的结果

DELETE, as the name suggests, will simply delete an existing resource.

顾名思义,DELETE只会删除现有资源

Response Codes

Once a request goes through from the client to the server, the server will send back an HTTP response, which will include metadata about the response known as headers, as well as the body. The first and most important part of the response is the status code, which indicates if a request was successful, if there was an error, or if another action must be taken.

一旦请求从客户端发送到服务器,服务器将发送回HTTP响应,该响应将包含有关响应的元数据(称为标头)以及正文。响应的第一个也是最重要的部分是状态码,它指示请求是否成功,是否存在错误或是否必须执行其他操作

The most well-known response code you will be familiar with is 404, which means Not Found. 404 is part of the 4xx class of status codes, which indicate client errors. There are five classes of status codes that each contain a range of responses.

您将最熟悉的响应代码是404,表示未找到。404是4xx类状态代码的一部分,它指示客户端错误。有五种状态代码,每类包含一系列响应

  • 1xx: Information 信息
  • 2xx: Success 成功
  • 3xx: Redirection 重定向
  • 4xx: Client Error 客户端错误
  • 5xx: Server Error 服务端错误

Other common responses you may be familiar with are 301 Moved Permanently, which is used to redirect websites to new URLs, and 500 Internal Server Error, which is an error that comes up frequently when something unexpected has happened on a server that makes it impossible to fulfil the intended request.

您可能熟悉的其他常见响应包括301已永久移动(用于将网站重定向到新的URL)和500内部服务器错误(当服务器上发生意外情况而导致无法执行以下操作时经常发生的错误)完成预期的要求

With regards to RESTful APIs and their corresponding HTTP verbs, all the responses should be in the 2xx range.

关于RESTful API及其对应的HTTP动词,所有响应都应在2xx范围内

Request Response
GET 200 (OK)
POST 201 (Created)
PUT 200 (OK)
DELETE 200 (OK), 202 (Accepted), or 204 (No Content)

200 OK is the response that indicates that a request is successful. It is used as a response when sending a GET or PUT request. POST will return a 201 Created to indicate that a new resource has been created, and DELETE has a few acceptable responses, which convey that either the request has been accepted (202), or there is no content to return because the resource no longer exists (204).

200 OK是指示请求成功的响应。发送GET或PUT请求时用作响应。POST将返回201 Created,指示已创建新资源,并且DELETE有一些可接受的响应,表明该请求已被接受(202),或者由于该资源不再存在而没有内容要返回(204)

We can test the status code of a resource request using cURL, which is a command-line tool used for transferring data via URLs. Using curl, followed by the -i or --include flag, will send a GET request to a URL and display the headers and body. We can test this by opening the command-line program and testing cURL with Google.

我们可以使用cURL测试资源请求的状态代码,cURL是用于通过URL传输数据的命令行工具。使用curl以及-i或--include标志,将向URL发送GET请求并显示标题和正文。我们可以通过打开命令行程序并使用Google测试cURL来进行测试

curl -i https://www.google.com

Google's server will respond with the following.

HTTP/2 200 
date: Tue, 14 Aug 2018 05:15:40 GMT 
expires: -1 
cache-control: private, max-age=0 
content-type: text/html; charset=ISO-8859-1 
...

As we can see, the curl request returns multiple headers and the entire HTML body of the response. Since the request went through successfully, the first part of the response is the 200 status code, along with the version of HTTP (this will either be HTTP/1.1 or HTTP/2).

如我们所见,curl请求返回多个标头和响应的整个HTML主体。由于请求已成功通过,因此响应的第一部分是200状态代码以及HTTP版本(HTTP / 1.1或HTTP / 2)

Since this particular request is returning a website, the content-type (MIME type) being returned is text/html. In a RESTful API, you will likely see application/json to indicate the response is JSON.

由于此特定请求正在返回网站,因此返回的内容类型(MIME类型)为text / html。在RESTful API中,您可能会看到application / json表示响应为JSON

Interestingly, we can see another type of response by inputting a slightly different URL. Do a curl on Google without the www.

有趣的是,通过输入略有不同的URL,我们可以看到另一种类型的响应。在没有www的情况下在Google上进行卷曲

curl -i https://google.com
HTTP/2 301 ``location: https://www.google.com/ ``content-type: text/html; ``charset=UTF-8

Google redirects google.com to www.google.com, and uses a 301 response to indicate that the resource should be redirected.

Google将google.com重定向到www.google.com,并使用301响应指示应重定向资源

REST API Endpoints

When an API is created on a server, the data it contains is accessible via endpoints. An endpoint is the URL of the request that can accept and process the GET, POST, PUT, or DELETE request.

在服务器上创建API后,可通过端点访问其中包含的数据。端点是可以接受和处理GET,POST,PUT或DELETE请求的URL

An API URL will consist of the root, path, and optional query string.

API URL将包含根,路径和可选查询字符串

  • Root e.g. https://api.example.com or https://api.example.com/v2: The root of the API, which may consist of the protocol, domain, and version.

    根例如https://api.example.com或https://api.example.com/v2:API的根,可以由协议,域和版本组成

  • Path e.g. /users/or /users/5: Unique location of the specific resource.

    路径例如/users/ 或 /users/5:特定资源的唯一位置

  • Query Parameters (optional) e.g. ?location=chicago&age=29: Optional key value pairs used for sorting, filtering, and pagination.

    查询参数(可选),例如?location=chicago&age=29:用于排序,过滤和分页的可选键值对

    We can put them all together to implement something such as the example below, which would return a list of all users and use a query parameter of limit to filter the responses to only include ten results.

    我们可以将它们放在一起以实现诸如以下之类的示例,该示例将返回所有用户的列表,并使用limit的查询参数过滤响应以仅包含十个结果

https://api.example.com/users?limit=10

Generally, when people refer to an API as a RESTful API, they are referring to the naming conventions that go into building API URL endpoints. A few important conventions for a standard RESTful API are as follows:

通常,当人们将API称为RESTful API时,他们所指的是建立API URL端点的命名约定。标准RESTful API的一些重要约定如下:

  • Paths should be plural: For example, to get the user with an id of 5, we would use /users/5, not /user/5.

    路径应为复数形式:例如,要获得ID为5的用户,我们将使用/users/5,而不是/user/5

  • Endpoints should not display the file extension: Although an API will most likely be returning JSON, the URL should not end in .json.

    端点不应显示文件扩展名:尽管API很可能会返回JSON,但URL不应以.json结尾

  • Endpoints should use nouns, not verbs: Words like add and delete should not appear in a REST URL. In order to add a new user, you would simply send a POST request to /users, not something like /users/add. The API should be developed to handle multiple types of requests to the same URL.

    端点应该使用名词,而不是动词:诸如add和delete之类的词不应出现在REST URL中。为了添加新用户,您只需将POST请求发送到/users,而不是/users/add之类的东西。应该开发API以处理对同一URL的多种类型的请求

  • Paths are case sensitive, and should be written in lowercase with hyphens as opposed to underscores.

    路径区分大小写,并且应使用小写字母(带下划线)而不是下划线

    All of these conventions are guidelines, as there are no strict REST standards to follow. However, using these guidelines will make your API consistent, familiar, and easy to read and understand.

    所有这些约定都是指南,因为没有严格的REST标准可遵循。但是,使用这些准则将使您的API一致,熟悉并且易于阅读和理解

Conclusion

In this article, we learned what REST and RESTful APIs are, how HTTP request methods and response codes work, the structure of an API URL, and common RESTful API conventions. In the next tutorial, we will learn how to put all this theory to use by setting up an Express server with Node.js and building our own API.

在本文中,我们了解了什么是REST和RESTful API,HTTP请求方法和响应代码如何工作,API URL的结构以及常见的RESTful API约定。在下一个教程中,我们将通过使用Node.js设置Express服务器并构建我们自己的API,学习如何使用所有这些理论

原文地址:https://www.cnblogs.com/PrimerPlus/p/12895703.html