1
0
mirror of https://github.com/twirl/The-API-Book.git synced 2025-07-12 22:50:21 +02:00

Merge pull request #53 from taksedo/bugfix/change-introduction-example

Приведение примера API во введении к более конвенциональному виду
This commit is contained in:
Sergey Konstantinov
2024-08-21 00:30:01 +03:00
committed by GitHub
2 changed files with 9 additions and 9 deletions

View File

@ -10,7 +10,7 @@ Let's take a look at the following example:
```json
// Method description
POST /v1/bucket/{id}/some-resource↵
POST /v1/buckets/{id}/some-resources
/{resource_id}
X-Idempotency-Token: <idempotency token>
{
@ -33,7 +33,7 @@ Cache-Control: no-cache
```
It should be read like this:
* A client performs a `POST` request to a `/v1/bucket/{id}/some-resource` resource, where `{id}` is to be replaced with some `bucket`'s identifier (`{something}` notation refers to the nearest term from the left unless explicitly specified otherwise).
* A client performs a `POST` request to a `/v1/buckets/{id}/some-resources` resource, where `{id}` is to be replaced with some `bucket`'s identifier (`{something}` notation refers to the nearest term from the left unless explicitly specified otherwise).
* A specific `X-Idempotency-Token` header is added to the request alongside standard headers (which we omit).
* Terms in angle brackets (`<idempotency token>`) describe the semantics of an entity value (field, header, parameter).
* A specific JSON, containing a `some_parameter` field and some other unspecified fields (indicated by ellipsis) is being sent as a request body payload.
@ -46,8 +46,8 @@ The term “client” here stands for an application being executed on a user's
Some request and response parts might be omitted if they are irrelevant to the topic being discussed.
Simplified notation might be used to avoid redundancies, like `POST /some-resource` `{…, "some_parameter", …}``{ "operation_id" }`; request and response bodies might also be omitted.
Simplified notation might be used to avoid redundancies, like `POST /some-resources` `{…, "some_parameter", …}``{ "operation_id" }`; request and response bodies might also be omitted.
We will use sentences like “`POST /v1/bucket/{id}/some-resource` method” (or simply “`bucket/some-resource` method,” “`some-resource`” method — if there are no other `some-resource`s in the chapter, so there is no ambiguity) to refer to such endpoint definitions.
We will use sentences like “`POST /v1/buckets/{id}/some-resources` method” (or simply “`buckets/some-resources` method,” “`some-resources`” method — if there are no other `some-resources`s in the chapter, so there is no ambiguity) to refer to such endpoint definitions.
Apart from HTTP API notation, we will employ C-style pseudocode, or, to be more precise, JavaScript-like or Python-like one since types are omitted. We assume such imperative structures are readable enough to skip detailed grammar explanations. HTTP API-like samples intend to illustrate the *contract*, i.e., how we would design an API. Samples in pseudocode are intended to illustrate how developers might work with the API in their code, or how we would implement SDKs based on the contract.
Apart from HTTP API notation, we will employ C-style pseudocode, or, to be more precise, JavaScript-like or Python-like one since types are omitted. We assume such imperative structures are readable enough to skip detailed grammar explanations. HTTP API-like samples intend to illustrate the *contract*, i.e., how we would design an API. Samples in pseudocode are intended to illustrate how developers might work with the API in their code, or how we would implement SDKs based on the contract.

View File

@ -10,7 +10,7 @@
```json
// Описание метода
POST /v1/bucket/{id}/some-resource↵
POST /v1/buckets/{id}/some-resources
/{resource_id}
X-Idempotency-Token: <токен идемпотентности>
{
@ -32,7 +32,7 @@ Cache-Control: no-cache
```
Её следует читать так:
* клиент выполняет POST-запрос к ресурсу `/v1/bucket/{id}/some-resource`, где `{id}` заменяется на некоторый идентификатор `bucket`-а (при отсутствии уточнений подстановки вида `{something}` следует относить к ближайшему термину слева);
* клиент выполняет POST-запрос к ресурсу `/v1/buckets/{id}/some-resources`, где `{id}` заменяется на некоторый идентификатор `bucket`-а (при отсутствии уточнений подстановки вида `{something}` следует относить к ближайшему термину слева);
* запрос сопровождается (помимо стандартных заголовков, которые мы опускаем) дополнительным заголовком `X-Idempotency-Token`;
* фразы в угловых скобках (`<токен идемпотентности>`) описывают семантику значения сущности (поля, заголовка, параметра);
* в качестве тела запроса передаётся JSON, содержащий поле `some_parameter` со значением `value` и ещё какие-то поля, которые для краткости опущены (что показано многоточием);
@ -45,8 +45,8 @@ Cache-Control: no-cache
Ответ (частично или целиком) и тело запроса могут быть опущены, если в контексте обсуждаемого вопроса их содержание не имеет значения.
Возможна сокращённая запись вида: `POST /some-resource` `{…,"some_parameter",…}``{ "operation_id" }`; тело запроса и/или ответа может опускаться аналогично полной записи.
Возможна сокращённая запись вида: `POST /some-resources` `{…,"some_parameter",…}``{ "operation_id" }`; тело запроса и/или ответа может опускаться аналогично полной записи.
Чтобы сослаться на это описание будут использоваться выражения типа «метод `POST /v1/bucket/{id}/some-resource`» или, для простоты, «метод `some-resource`» или «метод `bucket/some-resource`» (если никаких других `some-resource` в контексте главы не упоминается и перепутать не с чем).
Чтобы сослаться на это описание будут использоваться выражения типа «метод `POST /v1/buckets/{id}/some-resources`» или, для простоты, «метод `some-resources`» или «метод `buckets/some-resources`» (если никаких других `some-resources` в контексте главы не упоминается и перепутать не с чем).
Помимо HTTP API-нотации мы будем активно использовать C-подобный псевдокод — точнее будет сказать, JavaScript или Python-подобный, поскольку нотации типов мы будем опускать. Мы предполагаем, что подобного рода императивные конструкции достаточно читабельны, и не будем здесь описывать грамматику подробно. Примеры в виде HTTP API-нотации призваны иллюстрировать дизайн *контрактов*, т.е. показывать, как мы разрабатываем API. Примеры в псевдокоде обычно отражают, какой код напишут разработчики для работы с API, или как бы мы сами написали SDK на основе такого контракта.