RESTful API设计。最佳实践简述。

Posted on Mar 4, 2015. Updated on Jun 12, 2022

发布于2015年3月4日。更新于2022年6月12日

Designing HTTP and RESTful APIs can be tricky as there is no official and enforced standard. Basically, there are many ways of implementing an API but some of them have proven in practice and are widley adopted. This post covers best practices for building HTTP and RESTful APIs. We’ll talk about URL structure, HTTP methods, creating and updating resources, designing relationships, payload formats, pagination, versioning and many more.

设计HTTP和RESTful API是很棘手的,因为没有正式的和强制的标准。基本上,有许多实现API的方法,但其中一些方法已经在实践中得到证明,并被广泛采用。这篇文章涵盖了构建HTTP和RESTful APIs的最佳实践。我们将讨论URL结构、HTTP方法、创建和更新资源、设计关系、有效载荷格式、分页、版本等问题。

RESTful API Design. Best Practices in a Nutshell.

I completely reworked this post. I revisited and extended existing sections and added many new ones: New overviews over HTTP methods and status codes, PATCH, clearify semantics of PUT and POST, data field, designing relationships, REST vs RPC-style APIs, evolvability, versioning approaches, keyset-based pagination, JSON:API, JSON:API-inspired payload formats.

我完全重写了这个帖子。我重新审视和扩展了现有的部分,并增加了许多新的部分:对HTTP方法和状态码、PATCH、明确PUT和POST的语义、data 字段、设计关系、REST与RPC风格的API、可进化性、版本方法、基于键集的分页、JSON:API、JSON:API启发的有效载荷格式的新概述。

Use Two URLs per Resource

每个资源使用两个URL

One URL for the collection and one for a single resource:

一个是集合的URL,一个是单一资源的URL:

# URL that represents a collection of resources
/employees          
# URL that represents a single resource
/employees/56       

Use Consistently Plural Nouns

始终如一地使用复数名词

Prefer

倾向于

/employees
/employees/21

over

/employee
/employee/21

Indeed, it’s a matter of taste, but the plural form is more common. Moreover, it’s more intuitive, especially when using GET on the collection URL (GET /employee returning multiple employees). But most important: avoid mixing plural and singular nouns, which is confusing and error-prone.

的确,这是一个品味问题,但复数形式更常见。此外,它更直观,特别是在集合URL上使用GET时(GET /employee 返回多个雇员)。但最重要的是:避免混用复数和单数名词,这很混乱,而且容易出错。

Use Nouns instead of Verbs for Resources

使用名词而不是动词的资源

This will keep you API simple and the number of URLs low. Don’t do thi...

开通本站会员,查看完整译文。

Home - Wiki
Copyright © 2011-2024 iteam. Current version is 2.139.0. UTC+08:00, 2024-12-23 05:49
浙ICP备14020137号-1 $Map of visitor$