api restful
Facebook, GitHub, Google, and many other giants need a way to serve and consume data. A RESTful API is still one of the best choices in today’s dev landscape to serve and consume data.
Facebook,GitHub,Google和许多其他巨头需要一种服务和使用数据的方式。 RESTful API仍然是当今开发环境中服务和使用数据的最佳选择之一。
But have you ever considered learning about industry standards? What are the best practices for designing a RESTful API? In theory, anyone can quickly spin up a data API in less than five minutes — whether it be Node.js, Golang, or Python.
但是您是否考虑过学习行业标准? 设计RESTful API的最佳实践是什么? 从理论上讲,任何人都可以在不到五分钟的时间内快速启动数据API —无论是Node.js,Golang还是Python。
We’ll explore 13 best practices you should consider when building a RESTful API. But first, let’s clarify a RESTful API quickly.
我们将探讨构建RESTful API时应考虑的13种最佳实践。 但是首先,让我们快速阐明RESTful API。
A RESTful API needs to meet the following constraints for it to be called a RESTful API.
RESTful API需要满足以下约束才能被称为RESTful API。
Client-server: A RESTful API follows the client-server model where the server serves data and clients connect to the server to consume data. The interaction between client and server occurs through HTTP(S) requests that transfer the requested data.
客户端-服务器 :RESTful API遵循客户端-服务器模型,其中服务器为数据提供服务,客户端连接到服务器以使用数据。 客户端和服务器之间的交互是通过HTTP(S)请求进行的,该请求传输了请求的数据。
Stateless: More importantly, a RESTful API should be stateless. Each request is treated as a standalone request. The server should not keep track of any internal state that might influence the result of future requests.
无状态的 :更重要的是,RESTful API应该是无状态的。 每个请求都被视为独立请求。 服务器不应跟踪可能影响将来请求结果的任何内部状态。
Uniform interface: Lastly, uniformity defines how the client and server interact. RESTful APIs define best practices for naming resources but define fixed HTTP operations that allow you to modify/interact with resources. The following HTTP operations can be accessed in RESTful APIs:
统一接口 :最后,统一性定义客户端和服务器之间的交互方式。 RESTful API定义了资源命名的最佳实践,但定义了固定的HTTP操作,使您可以修改/与资源交互。 可以在RESTful API中访问以下HTTP操作:
With this deeper understanding of the characteristics of a RESTful API, it’s time to learn more about RESTful API best practices.
通过对RESTful API的特征有更深入的了解,是时候了解有关RESTful API最佳实践的更多信息了。
This article presents you with an actionable list of 13 best practices. Let’s explore!
本文为您提供了13种最佳实践的可行清单。 让我们来探索!
We’ve already discussed the possible HTTP methods you can use to modify resources: GET, POST, PUT, PATCH, and DELETE.
我们已经讨论了可用于修改资源的HTTP方法:GET,POST,PUT,PATCH和DELETE。
Still, many developers tend to abuse GET and POST, or PUT and PATCH. Often, we see developers use a POST request to retrieve data. Furthermore, we see developers use a PUT request which replaces the resource while they only wanted to update a single field for that resource.
尽管如此,许多开发人员还是倾向于滥用GET和POST或PUT和PATCH。 通常,我们看到开发人员使用POST请求来检索数据。 此外,我们看到开发人员使用PUT请求来替换资源,而他们只想更新该资源的单个字段。
Make sure to use the correct HTTP method as this will add a lot of confusion for developers using your RESTful API. It’s better to stick to the intended guidelines.
确保使用正确的HTTP方法,因为这会使使用RESTful API的开发人员感到困惑。 最好遵循预期的准则。
Understanding the RESTful API naming conventions will help you a lot with designing your API in an organized manner. Design a RESTful API according to the resources you serve.
了解RESTful API命名约定将有助于您以有组织的方式设计API。 根据您服务的资源设计一个RESTful API。
For example, your API manages authors and books (yes, a classic example). Now, we want to add a new author or access an author with ID 3
. You could design the following routes to serve this purpose:
例如,您的API管理作者和书籍(是的,这是一个经典示例)。 现在,我们要添加一个新作者或访问ID为3
的作者。 您可以设计以下路线来实现此目的:
Imagine an API that hosts many resources that each have many properties. The list of possible endpoints will become endless and not very user-friendly. So we need a more organized and standardized way of designing API endpoints.
想象一下一个API,该API承载着许多具有许多属性的资源。 可能的端点列表将变得无穷无尽,并且不太友好。 因此,我们需要一种更加组织化和标准化的API端点设计方法。
RESTful API best practices describe that an endpoint should start with the resource name, while the HTTP operation describes the action. Now we get:
RESTful API最佳实践描述了端点应以资源名称开头,而HTTP操作则描述操作。 现在我们得到:
What if we want to access all books author with ID 3
has ever written? Also for this case, RESTful APIs have a solution:
如果我们要访问所有ID为3
作者,该怎么办? 同样对于这种情况,RESTful API有一个解决方案:
Lastly, what if you want to delete a book with ID 5
for an author with ID 3
. Again, let’s follow the same structured approach to form the following endpoint:
最后,如果您要为ID为3
的作者删除ID为5
的书,该怎么办。 同样,让我们遵循相同的结构化方法来形成以下端点:
In short, make use of HTTP operations and the structured way of resource mapping to form a readable and understandable endpoint path. The big advantage of this approach is that every developer understands how RESTful APIs are designed and they can immediately use the API without having to read your documentation on each endpoint.
简而言之,利用HTTP操作和资源映射的结构化方式来形成易于理解的端点路径。 这种方法的最大优点是,每个开发人员都了解RESTful API的设计方式,并且他们可以立即使用API,而不必阅读每个端点上的文档。
Resources should always use their plural form. Why? Imagine you want to retrieve all authors. Therefore, you would call the following endpoint: GET api.com/authors
.
资源应始终使用其复数形式。 为什么? 假设您要检索所有作者。 因此,您将调用以下端点: GET api.com/authors
。
When you read the request, you can’t tell if the API response will contain only one or all authors. For that reason, API endpoints should use plural resources.
阅读请求时,您无法确定API响应是否仅包含一位或全部作者。 因此,API端点应使用多个资源。
Status codes aren’t here just for fun. They have a clear purpose. A status code notifies the client about the success of its request.
状态代码不只是为了好玩而已。 他们有明确的目的。 状态代码通知客户端其请求成功。
The most common status code categories include:
最常见的状态码类别包括:
A full list of status codes can be found at Mozilla Developers. Don’t forget to check out the “I’m a teapot” status code (418).
可以在Mozilla Developers中找到状态代码的完整列表。 不要忘记查看“我是茶壶”状态码(418)。
Most commonly, a RESTful API serves JSON data. Therefore, the camelCase casing convention should be practiced. However, different programming languages use different naming conventions.
最常见的是,RESTful API提供JSON数据。 因此,应遵循camelCase大小写惯例。 但是,不同的编程语言使用不同的命名约定 。
Actions such as searching, pagination, filtering, and sorting don’t represent separate endpoints. These actions can be accomplished through the use of query parameters that are provided with the API request.
搜索,分页,过滤和排序等操作不代表单独的端点。 这些操作可以通过使用API请求随附的查询参数来完成。
For example, let’s retrieve all authors sorted by name in ascending order. Your API request should look like this: api.com/authors?sort=name_asc
.
例如,让我们检索按名称升序排列的所有作者。 您的API请求应如下所示: api.com/authors?sort=name_asc
。
Furthermore, I want to retrieve an author with the name ‘Michiel’. The request looks like this api.com/authors?search=Michiel
.
此外,我想检索一个名为“ Michiel”的作者。 该请求看起来像这样api.com/authors?search=Michiel
。
Luckily, many API projects come with built-in searching, pagination, filtering, and sorting capabilities. This will save you a lot of time.
幸运的是,许多API项目都具有内置的搜索,分页,过滤和排序功能。 这样可以节省您很多时间。
I don’t see this very often, but it’s a best practice to version your API. It’s an effective way of communicating breaking changes to your users.
我很少看到这种情况,但这是对API进行版本控制的最佳做法。 这是向用户传达重大更改的有效方法。
Frequently, the version number of the API is incorporated in the API URL, like this: api.com/v1/authors/3/books
.
通常,API的版本号包含在API URL中,例如: api.com/v1/authors/3/books
。
HTTP headers allow a client to send additional information with their request. For example, the Authorization
header is commonly used for sending authentication data to access the API.
HTTP标头允许客户端随其请求发送其他信息。 例如, Authorization
标头通常用于发送身份验证数据以访问API。
A full list of all possible HTTP headers can be found here.
可在此处找到所有可能的HTTP标头的完整列表。
Rate limiting is an interesting approach to control the number of requests per client. These are the possible rate limiting headers your server can return:
速率限制是控制每个客户端请求数量的一种有趣方法。 这些是服务器可能返回的速率限制标头:
In case something goes wrong, it’s important that you provide a meaningful error message to the developer. For example, the Twilio API returns the following error format:
万一出了问题,向开发人员提供有意义的错误消息很重要。 例如,Twilio API返回以下错误格式:
{
"status": 400,
"message": "Resource books does not exist",
"code": 24801,
"more_info": "api.com/docs/errors/24801"
}
In this example, the server returns the status code and a human-readable message. Further, an internal error code is also returned for the developer to look up the specific error. This allows the developer to quickly look up more information about the error.
在此示例中,服务器返回状态代码和人类可读的消息。 此外,还返回内部错误代码,供开发人员查找特定错误。 这使开发人员可以快速查找有关该错误的更多信息。
Many frameworks exist for different programming languages. It’s important to pick a framework that supports the RESTful API best practices.
存在许多用于不同编程语言的框架。 选择支持RESTful API最佳实践的框架很重要。
For Node.js, back-end developers love to use Express.js, whereas for Python, Falcon is a great option.
对于Node.js,后端开发人员喜欢使用Express.js ,而对于Python, Falcon是一个不错的选择。
Lastly, write documentation! I’m not joking; it’s still one of the easiest ways to transfer knowledge about your newly developed API.
最后,编写文档! 我不是在开玩笑; 仍然是转移有关新开发的API的知识的最简单方法之一。
Although your API follows all best practices outlined for RESTful APIs, it’s still worth your time to document various elements such as the resources your API handles or what rate limits apply to your server.
尽管您的API遵循针对RESTful API概述的所有最佳实践,但是仍然值得您花时间记录各种要素,例如API处理的资源或适用于服务器的速率限制。
Think about your fellow developers. Documentation drastically reduces the time needed to learn about your API.
考虑一下您的其他开发人员。 文档大大减少了学习API所需的时间。
Don’t overcomplicate your API and keep resources simple. A proper definition of the different resources your API handles will help you to avoid resource-related problems in the future. Define your resources, but also accurately define its properties and the relationships between resources. This way, there’s no room for dispute on how to connect the different resources.
不要过于复杂化您的API并保持资源简单。 API处理的不同资源的正确定义将有助于您避免将来与资源相关的问题。 定义您的资源,还要准确定义其属性以及资源之间的关系。 这样,对于如何连接不同的资源就没有争议的余地。
If you liked this article explaining API best practices, you might also enjoy learning about building a RESTful API from scratch.
如果您喜欢这篇介绍API最佳实践的文章,那么您可能还喜欢从头开始学习构建RESTful API 。
翻译自: https://www.sitepoint.com/build-restful-apis-best-practices/
api restful