Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions README-es.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
[English](./README.md) | [简中版](./README-zh-Hans.md) | [Español](./README-es.md)

### Consulta también: [Guía Rápida para Construcción de Plataformas](https://github.com/RestCheatSheet/platform-cheat-sheet#platform-building-cheat-sheet)

# Guía Rápida para Diseño de APIs

1. **Diseña la API pensando en los consumidores, como si fuera un producto en sí mismo.**
* No para una interfaz de usuario específica.
* Fomenta la flexibilidad y adaptabilidad de cada endpoint (ver puntos #5, #6 y #7).
* Usa tu propia API ("eat your own dogfood"), incluso si necesitas crear un prototipo de una interfaz de usuario de ejemplo.

2. **Utiliza la metáfora de Colección.**
* Define dos URLs (endpoints) por recurso:
* La colección de recursos (por ejemplo, `/orders`).
* Un recurso individual dentro de la colección (por ejemplo, `/orders/{orderId}`).
* Usa formas plurales (por ejemplo, ‘orders’ en lugar de ‘order’).
* Alterna nombres de recursos con IDs como nodos en la URL (por ejemplo, `/orders/{orderId}/items/{itemId}`).
* Mantén las URLs lo más cortas posible. Preferiblemente, no más de tres nodos por URL.

3. **Usa sustantivos como nombres de recursos** (por ejemplo, no uses verbos en las URLs).

4. **Haz que las representaciones de los recursos sean significativas.**
* “¡No IDs desnudos!” No incluyas IDs simples en las respuestas. Usa enlaces y objetos de referencia.
* Diseña representaciones de recursos. No te limites a representar tablas de la base de datos.
* Combina representaciones. No expongas tablas de relaciones como dos IDs separados.

5. **Admite filtrado, ordenamiento y paginación en las colecciones.**

6. **Admite la expansión de enlaces en relaciones.** Permite que los clientes expandan los datos incluidos en la respuesta mediante representaciones adicionales, además de, o en lugar de, enlaces.

7. **Admite proyecciones de campos en recursos.** Permite a los clientes reducir la cantidad de campos devueltos en la respuesta.

8. **Usa los nombres de los métodos HTTP con significado:**
* `POST`: para crear y otras operaciones no idempotentes.
* `PUT`: para actualizar.
* `GET`: para leer un recurso o colección.
* `DELETE`: para eliminar un recurso o colección.

9. **Usa códigos de estado HTTP con significado:**
* `200`: Éxito.
* `201`: Creado. Devuelve este código al crear un recurso nuevo exitosamente. Incluye un encabezado 'Location' con un enlace al recurso recién creado.
* `400`: Solicitud incorrecta. Por ejemplo, problemas con los datos como JSON no válido.
* `404`: No encontrado. Recurso no encontrado al usar `GET`.
* `409`: Conflicto. Datos duplicados o estado de datos no válido.

10. **Usa formatos de fecha en representaciones conforme a ISO 8601.**

11. **Considera la conectividad utilizando una estrategia de enlace.** Algunos ejemplos populares son:
* [HAL](http://stateless.co/hal_specification.html)
* [Siren](https://github.com/kevinswiber/siren)
* [JSON-LD](http://json-ld.org/)
* [Collection+JSON](http://amundsen.com/media-types/collection/)

12. **Usa [OAuth2](http://oauth.net/2/) para proteger tu API.**
* Usa un token Bearer para autenticación.
* Requiere HTTPS / TLS / SSL para acceder a tus APIs. Los tokens Bearer de OAuth2 lo exigen. La comunicación no encriptada a través de HTTP permite interceptaciones e impersonaciones simples.

13. **Usa la negociación de Content-Type para describir los payloads de las solicitudes.**

Por ejemplo, si manejas calificaciones (como "pulgar arriba/abajo" y calificaciones de cinco estrellas), puedes usar una única ruta para crear una calificación: **POST /ratings**.
En lugar de crear rutas separadas como **POST /ratings/five_star** o **POST /ratings/thumbs_up**, usa el encabezado `Content-Type` para distinguir los tipos de calificación:
* `Content-Type: application/vnd.company.rating.thumbsup`
* `Content-Type: application/vnd.company.rating.fivestar`

14. **Evolución sobre versionado.** Sin embargo, si necesitas versionar, usa el encabezado `Accept` en lugar de versionar en la URL.
* El versionado en la URL representa una versión "plataforma".
* El versionado mediante el encabezado `Accept` versiona el recurso individual.
* Los cambios en respuestas JSON no requieren versionado, pero los cambios en solicitudes que sean obligatorios sí podrían necesitarlo.

15. **Considera la capacidad de caché.** Usa los siguientes encabezados de respuesta:
* `ETag`: Cadena arbitraria para la versión de una representación.
* `Date`: Fecha y hora en que se devolvió la respuesta.
* `Cache-Control`: Controla la edad máxima o si la respuesta no se debe almacenar en caché.
* `Expires`: Fecha en que expira la respuesta.
* `Pragma`: Indica "no-cache" si se requiere.
* `Last-Modified`: Fecha y hora de la última modificación del recurso.

16. **Asegúrate de que las operaciones `GET`, `PUT` y `DELETE` sean [idempotentes](http://www.restapitutorial.com/lessons/idempotency.html).** No debe haber efectos secundarios adversos de estas operaciones.
32 changes: 17 additions & 15 deletions README-zh-Hans.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[English](./README.md) | [简中版](./README-zh-Hans.md) | [Español](./README-es.md)

See also: [Platform Building Cheat Sheet][1]

# API 设计参考手册
Expand All @@ -6,59 +8,59 @@ See also: [Platform Building Cheat Sheet][1]
* 拥抱变化,针对每一个接口尽量满足灵活性和可调性。(参见 5,6 和 7);
* 吃自己的狗粮,即使你必须模拟一些示例界面。

1. 使用资源集合的概念;
2. 使用资源集合的概念;
* 每种资源有两类网址(接口):
* 资源集合(例如,/orders);
* 集合中的单个资源(例如,/orders/{orderId})。
* 使用复数形式 (使用 ‘orders’ 而不是 ‘order’);
* 资源名称和 ID 组合可以作为一个网址的节点(例如,/orders/{orderId}/items/{itemId});
* 尽可能的让网址越短越好,单个网址最好不超过三个节点。

1. 使用名词作为资源名称 (例如,不要在网址中使用动词);
3. 使用名词作为资源名称 (例如,不要在网址中使用动词);

1. 使用有意义的资源描述;
4. 使用有意义的资源描述;
* “禁止单纯的使用 ID!” 响应信息中不应该存在单纯的 ID,应使用链接或是引用的对象;
* 设计资源的描述信息,而不是简简单单的做数据库表的映射;
* 合并描述信息,不要通过两个 ID 直接表示两个表的关系;

1. 资源的集合应支持过滤,排序和分页;
5. 资源的集合应支持过滤,排序和分页;

1. 支持通过链接扩展关系,允许客户端通过添加链接扩展响应中的数据;
6. 支持通过链接扩展关系,允许客户端通过添加链接扩展响应中的数据;

1. 支持资源的字段裁剪,运行客户端减少响应中返回的字段数量;
7. 支持资源的字段裁剪,运行客户端减少响应中返回的字段数量;

1. 使用 HTTP 方法名来表示对应的行为:
8. 使用 HTTP 方法名来表示对应的行为:
* POST - 创建资源,非幂等性操作;
* PUT - 更新资源;
* GET - 获取单个资源或资源集合;
* DELETE - 删除单个资源或资源集合;

1. 合理使用 HTTP 状态码;
9. 合理使用 HTTP 状态码;
* 200 - 成功;
* 201 - 创建成功,成功创建一个新资源时返回。 返回信息中将包含一个 'Location' 报头,他通过一个链接指向新创建的资源地址;
* 400 - 错误的请求,数据问题,如不正确的 JSON 等;
* 404 - 未找到,通过 GET 请求未找到对应的资源;
* 409 - 冲突,将出现重复的数据或是无效的数据状态。

1. 使用 ISO 8601 时间戳格式来表示日期;
10. 使用 ISO 8601 时间戳格式来表示日期;

1. 利用链接策略来处理关联关系,一些流行的例子如下:
11. 利用链接策略来处理关联关系,一些流行的例子如下:
* [HAL][2]
* [Siren][3]
* [JSON-LD][4]
* [Collection+JSON][5]

1. 使用 [OAuth2][6] 来确保 API 的安全性;
12. 使用 [OAuth2][6] 来确保 API 的安全性;
* 使用 Bearer Token 进行身份验证;
* OAuth2 的 Bearer token 要求必须通过 HTTPS / TLS / SSL 来访问你的 API。通过 HTTP 进行的未加密通信将导致窃听和重放。

1. Use Content-Type negotiation to describe incoming request payloads.
13. Use Content-Type negotiation to describe incoming request payloads.

1. Evolution over versioning. However, if versioning, use the Accept header instead of versioning in the URL.
14. Evolution over versioning. However, if versioning, use the Accept header instead of versioning in the URL.

1. Consider Cache-ability. At a minimum, use the following response headers:
15. Consider Cache-ability. At a minimum, use the following response headers:

1. 确保你的 GET,PUT,DELETE 请求是[幂等的][7],这些请求多次操作不应该有副作用。
16. 确保你的 GET,PUT,DELETE 请求是[幂等的][7],这些请求多次操作不应该有副作用。

[1]: https://github.com/RestCheatSheet/platform-cheat-sheet#platform-building-cheat-sheet
[2]: http://stateless.co/hal_specification.html
Expand Down
32 changes: 17 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
[English](./README.md) | [简中版](./README-zh-Hans.md) | [Español](./README-es.md)

See also: [Platform Building Cheat Sheet](https://github.com/RestCheatSheet/platform-cheat-sheet#platform-building-cheat-sheet)

# API Design Cheat Sheet
Expand All @@ -6,53 +8,53 @@ See also: [Platform Building Cheat Sheet](https://github.com/RestCheatSheet/plat
* Embrace flexibility / tunability of each endpoint (see #5, 6 & 7).
* Eat your own dogfood, even if you have to mockup an example UI.

1. Use the Collection Metaphor.
2. Use the Collection Metaphor.
* Two URLs (endpoints) per resource:
* The resource collection (e.g. /orders)
* Individual resource within the collection (e.g. /orders/{orderId}).
* Use plural forms (‘orders’ instead of ‘order’).
* Alternate resource names with IDs as URL nodes (e.g. /orders/{orderId}/items/{itemId})
* Keep URLs as short as possible. Preferably, no more-than three nodes per URL.

1. Use nouns as resource names (e.g. don’t use verbs in URLs).
3. Use nouns as resource names (e.g. don’t use verbs in URLs).

1. Make resource representations meaningful.
4. Make resource representations meaningful.
* “No Naked IDs!” No plain IDs embedded in responses. Use links and reference objects.
* Design resource representations. Don’t simply represent database tables.
* Merge representations. Don’t expose relationship tables as two IDs.

1. Support filtering, sorting, and pagination on collections.
5. Support filtering, sorting, and pagination on collections.

1. Support link expansion of relationships. Allow clients to expand the data contained in the response by including additional representations instead of, or in addition to, links.
6. Support link expansion of relationships. Allow clients to expand the data contained in the response by including additional representations instead of, or in addition to, links.

1. Support field projections on resources. Allow clients to reduce the number of fields that come back in the response.
7. Support field projections on resources. Allow clients to reduce the number of fields that come back in the response.

1. Use the HTTP method names to mean something:
8. Use the HTTP method names to mean something:
* POST - create and other non-idempotent operations.
* PUT - update.
* GET - read a resource or collection.
* DELETE - remove a resource or collection.

1. Use HTTP status codes to be meaningful.
9. Use HTTP status codes to be meaningful.
* 200 - Success.
* 201 - Created. Returned on successful creation of a new resource. Include a 'Location' header with a link to the newly-created resource.
* 400 - Bad request. Data issues such as invalid JSON, etc.
* 404 - Not found. Resource not found on GET.
* 409 - Conflict. Duplicate data or invalid data state would occur.

1. Use ISO 8601 timepoint formats for dates in representations.
10. Use ISO 8601 timepoint formats for dates in representations.

1. Consider connectedness by utilizing a linking strategy. Some popular examples are:
11. Consider connectedness by utilizing a linking strategy. Some popular examples are:
* [HAL](http://stateless.co/hal_specification.html)
* [Siren](https://github.com/kevinswiber/siren)
* [JSON-LD](http://json-ld.org/)
* [Collection+JSON](http://amundsen.com/media-types/collection/)

1. Use [OAuth2](http://oauth.net/2/) to secure your API.
12. Use [OAuth2](http://oauth.net/2/) to secure your API.
* Use a Bearer token for authentication.
* Require HTTPS / TLS / SSL to access your APIs. OAuth2 Bearer tokens demand it. Unencrypted communication over HTTP allows for simple eavesdroppping and impersonation.

1. Use Content-Type negotiation to describe incoming request payloads.
13. Use Content-Type negotiation to describe incoming request payloads.

For example, let's say you're doing ratings, including a thumbs-up/thumbs-down and five-star rating. You have one route to create a rating: **POST /ratings**

Expand All @@ -62,19 +64,19 @@ See also: [Platform Building Cheat Sheet](https://github.com/RestCheatSheet/plat

However, by using Content-Type negotiation we can use our same **POST /ratings** route for both types. By setting the *Content-Type* header on the request to something like **Content-Type: application/vnd.company.rating.thumbsup** or **Content-Type: application/vnd.company.rating.fivestar** the server can determine how to process the incoming rating data.

1. Evolution over versioning. However, if versioning, use the Accept header instead of versioning in the URL.
14. Evolution over versioning. However, if versioning, use the Accept header instead of versioning in the URL.
* Versioning via the URL signifies a 'platform' version and the entire platform must be versioned at the same time to enable the linking strategy.
* Versioning via the Accept header is versioning the resource.
* Additions to a JSON response do not require versioning. However, additions to a JSON request body that are 'required' are troublesome--and may require versioning.
* Hypermedia linking and versioning is troublesome no matter what--minimize it.
* Note that a version in the URL, while discouraged, can be used as a 'platform' version. It should appear as the first node in the path and not version individual endpoints differently (e.g. api.example.com/v1/...).

1. Consider Cache-ability. At a minimum, use the following response headers:
15. Consider Cache-ability. At a minimum, use the following response headers:
* ETag - An arbitrary string for the version of a representation. Make sure to include the media type in the hash value, because that makes a different representation. (ex: ETag: "686897696a7c876b7e")
* Date - Date and time the response was returned (in RFC1123 format). (ex: Date: Sun, 06 Nov 1994 08:49:37 GMT)
* Cache-Control - The maximum number of seconds (max age) a response can be cached. However, if caching is not supported for the response, then no-cache is the value. (ex: Cache-Control: 360 or Cache-Control: no-cache)
* Expires - If max age is given, contains the timestamp (in RFC1123 format) for when the response expires, which is the value of Date (e.g. now) plus max age. If caching is not supported for the response, this header is not present. (ex: Expires: Sun, 06 Nov 1994 08:49:37 GMT)
* Pragma - When Cache-Control is 'no-cache' this header is also set to 'no-cache'. Otherwise, it is not present. (ex: Pragma: no-cache)
* Last-Modified - The timestamp that the resource itself was modified last (in RFC1123 format). (ex: Last-Modified: Sun, 06 Nov 1994 08:49:37 GMT)

1. Ensure that your GET, PUT, and DELETE operations are all [idempotent](http://www.restapitutorial.com/lessons/idempotency.html). There should be no adverse side affects from operations.
16. Ensure that your GET, PUT, and DELETE operations are all [idempotent](http://www.restapitutorial.com/lessons/idempotency.html). There should be no adverse side affects from operations.