api restful_构建RESTful API的13种最佳实践

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。

什么是RESTful API? (What is a RESTful API?)

A RESTful API needs to meet the following constraints for it to be called a RESTful API.

RESTful API需要满足以下约束才能被称为RESTful API。

  1. 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)请求进行的,该请求传输了请求的数据。

  2. 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应该是无状态的。 每个请求都被视为独立请求。 服务器不应跟踪可能影响将来请求结果的任何内部状态。

  3. 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操作:

    • GET request: retrieve a resource

      GET请求:检索资源
    • POST request: create a resource or send information to the API

      POST请求:创建资源或将信息发送到API
    • PUT request: create or replace a resource

      PUT请求:创建或替换资源
    • PATCH request: update an existing resource

      PATCH请求:更新现有资源
    • DELETE request: delete a resource

      删除请求:删除资源

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最佳实践的更多信息了。

设计第一个RESTful API的最佳做法 (Best Practices For Designing Your First RESTful API)

This article presents you with an actionable list of 13 best practices. Let’s explore!

本文为您提供了13种最佳实践的可行清单。 让我们来探索!

1.正确使用HTTP方法 (1. Use HTTP methods correctly)

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的开发人员感到困惑。 最好遵循预期的准则。

2.命名约定 (2. Naming conventions)

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的作者。 您可以设计以下路线来实现此目的:

  • api.com/addNewAuthor

    api.com/addNewAuthor
  • api.com/getAuthorByID/3

    api.com/getAuthorByID/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操作则描述操作。 现在我们得到:

  • POST api.com/authors

    POST api.com/authors
  • GET api.com/authors/3

    GET api.com/authors/3

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有一个解决方案:

  • GET api.com/authors/3/books

    GET api.com/authors/3/books

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的书,该怎么办。 同样,让我们​​遵循相同的结构化方法来形成以下端点:

  • DELETE api.com/authors/3/books/5

    删除api.com/authors/3/books/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​​,而不必阅读每个端点上的文档。

3.使用多种资源 (3. Use plural resources)

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端点应使用多个资源。

4.正确使用状态码 (4. Correct use of status codes)

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:

最常见的状态码类别包括:

  • 200 (OK): The request has been successfully handled and completed.

    200(OK):请求已成功处理并完成。
  • 201 (Created): Indicates the successful creation of a resource.

    201(已创建):指示成功创建资源。
  • 400 (Bad Request): Represents a client-side error. That is, the request has been malformed or missing request parameters.

    400(错误请求):代表客户端错误。 也就是说,请求的格式不正确或缺少请求参数。
  • 401 (Unauthorized): You tried accessing a resource for which you don’t have permission.

    401(未经授权):您尝试访问没有权限的资源。
  • 404 (Not Found): The requested resource doesn’t exist.

    404(未找到):请求的资源不存在。
  • 500 (Internal Server Error): Whenever the server raises an exception during the request execution.

    500(内部服务器错误):服务器在执行请求期间引发异常。

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)。

5.遵守包装惯例 (5. Follow casing conventions)

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大小写惯例。 但是,不同的编程语言使用不同的命名约定

6.如何处理搜索,分页,过滤和排序 (6. How to handle searching, pagination, filtering, and sorting)

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项目都具有内置的搜索,分页,过滤和排序功能。 这样可以节省您很多时间。

7. API版本控制 (7. API versioning)

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

8.通过HTTP标头发送元数据 (8. Send metadata via HTTP headers)

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标头的完整列表。

9.速率限制 (9. Rate Limiting)

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:

速率限制是控制每个客户端请求数量的一种有趣方法。 这些是服务器可能返回的速率限制标头:

  • X-Rate-Limit-Limit: Tells the number of requests a client can send within a specified time interval.

    X-Rate-Limit-Limit:告诉客户端在指定时间间隔内可以发送的请求数。
  • X-Rate-Limit-Remaining: Tells how many requests the client can still send within the current time interval.

    X-Rate-Limit-Remaining:告诉客户端在当前时间间隔内仍可以发送多少个请求。
  • X-Rate-Limit-Reset: Tells the client when the rate limit will reset.

    X-Rate-Limit-Reset:告诉客户端速率限制何时重置。

10.有意义的错误处理 (10. Meaningful error handling)

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.

在此示例中,服务器返回状态代码和人类可读的消息。 此外,还返回内部错误代码,供开发人员查找特定错误。 这使开发人员可以快速查找有关该错误的更多信息。

11.选择正确的API框架 (11. Choose the right API framework)

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是一个不错的选择。

12.记录您的API (12. Document your API)

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所需的时间。

13.保持简单! (13. Keep it simple!)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值