mirror of
https://github.com/twirl/The-API-Book.git
synced 2025-02-22 18:42:09 +02:00
Introduction refactoring begin
This commit is contained in:
parent
a28650acff
commit
e679fed5cf
35
README.md
35
README.md
@ -1,34 +1,25 @@
|
||||
# Read [‘The API’ Book by Sergey Konstantinov](https://twirl.github.io/The-API-Book) in English
|
||||
# Читать [книгу ‘The API’ Сергея Константинова](https://twirl.github.io/The-API-Book/index.ru.html) по-русски
|
||||
|
||||
This is the working repository for ‘The API’ book written by Sergey Konstantinov ([email](mailto:twirl-team@yandex.ru), [Linkedin profile](https://linkedin.com/in/twirl)).
|
||||
This is the working repository for ‘The API’ book written by Sergey Konstantinov ([email](mailto:twirl-team@yandex.ru), [Linkedin profile](https://linkedin.com/in/twirl), [Medium blog](https://twirl.medium.com)).
|
||||
|
||||
The API-first development is one of the hottest technical topics nowadays, since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.
|
||||
API-first development is one of the hottest technical topics nowadays since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.
|
||||
|
||||
This book is written to share the expertise and describe the best practices in designing and developing APIs. In Section I, we'll discuss the API architecture as a concept: how to build the hierarchy properly, from high-level planning down to final interfaces. Section II is dedicated to expanding existing APIs in a backwards-compatible manner. Finally, in Section III we will talk about the API as a product.
|
||||
This book is written to share the expertise and describe the best practices in designing and developing APIs. It comprises six sections dedicated to:
|
||||
* the API design
|
||||
* API patterns
|
||||
* backwards compatibility
|
||||
* HTTP API & REST
|
||||
* SDK and UI libraries
|
||||
* API product management.
|
||||
|
||||
This is an open-source book distributed under the [Creative Commons Attribution-NonCommercial 4.0 International](/LICENSE.md) license.
|
||||
|
||||
## Current State and the Roadmap
|
||||
|
||||
Right now all three section (‘The API Design’, ‘The Backwards Compatibility’, and ‘The API Product’) are finished. So the book is basically ready. However, after some beta-testing I understood there were several important problems.
|
||||
1. 'Describing final interfaces' chapter is way too overloaded; many concepts explained there deserve a separate chapter, and being minimized to fit the format, they arise a lot of controversy.
|
||||
2. Though I've tried to avoid talking about any specific paradigm (REST in particular), it's often being read as such, thus igniting discussions on whether the samples are proper REST.
|
||||
Right now three sections (‘The API Design’, ‘The Backwards Compatibility’, and ‘The API Product’) are finished, comprising the [first edition of the book](/docs/v1/). Three other sections are drafted and are now being added to the clean copy chapter after chapter.
|
||||
|
||||
So the current plan is:
|
||||
1. To split Chapter 11 into a full Section III (work title: 'API Patterns') comprising:
|
||||
* defining API-first approach in a technical sense;
|
||||
* the review of API-describing paradigms (OpenAPI/REST, GraphQL, GRPC, JSON-RPC, SOAP);
|
||||
* working with default values, backwards compatibility-wise;
|
||||
* (a)synchronous interaction;
|
||||
* strong and weak consistency;
|
||||
* push and poll models;
|
||||
* machine-readable APIs: iterable lists, cursors, observability;
|
||||
* an amount of traffic and data compression;
|
||||
* API errors: resolvability, reduction to defaults;
|
||||
* degrading properly.
|
||||
2. To compile Section IV ‘HTTP API & JSON’ from current drafts + HTTP general knowledge + codestyle.
|
||||
3. Maybe, try to compile Section V ‘SDK’ (much harder as there are very few drafts).
|
||||
|
||||
Also, the book still lacks the readable schemes which I'm still planning to plot with mermaid.
|
||||
Also, the book still lacks readable schemes which I'm still planning to plot with mermaid.
|
||||
|
||||
## Translation
|
||||
|
||||
|
BIN
docs/API.en.epub
BIN
docs/API.en.epub
Binary file not shown.
114
docs/API.en.html
114
docs/API.en.html
File diff suppressed because one or more lines are too long
BIN
docs/API.en.pdf
BIN
docs/API.en.pdf
Binary file not shown.
BIN
docs/API.ru.epub
BIN
docs/API.ru.epub
Binary file not shown.
114
docs/API.ru.html
114
docs/API.ru.html
File diff suppressed because one or more lines are too long
BIN
docs/API.ru.pdf
BIN
docs/API.ru.pdf
Binary file not shown.
@ -10,7 +10,7 @@
|
||||
</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Designing APIs is a very special skill: API is a multiplier to both your opportunities and mistakes. This book is written to share the expertise and describe the best practices in designing and developing APIs. In Section I, we'll discuss the API architecture as a concept: how to build the hierarchy properly, from high-level planning down to final interfaces. Section II is dedicated to expanding existing APIs in a backwards-compatible manner. Finally, in Section III we will talk about the API as a product."
|
||||
content="API-first development is one of the hottest technical topics nowadays since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well. This book is written to share the expertise and describe the best practices in designing and developing APIs. It comprises six sections dedicated to: the API design, API patterns, maintaining backwards compatibility, HTTP API & REST, SDK and UI libraries, API product management."
|
||||
/>
|
||||
<meta property="og:type" content="article" />
|
||||
<meta
|
||||
@ -19,7 +19,7 @@
|
||||
/>
|
||||
<meta
|
||||
property="og:description"
|
||||
content="Designing APIs is a very special skill: API is a multiplier to both your opportunities and mistakes. This book is written to share the expertise and describe the best practices in designing and developing APIs. In Section I, we'll discuss the API architecture as a concept: how to build the hierarchy properly, from high-level planning down to final interfaces. Section II is dedicated to expanding existing APIs in a backwards-compatible manner. Finally, in Section III we will talk about the API as a product."
|
||||
content="API-first development is one of the hottest technical topics nowadays since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well. This book is written to share the expertise and describe the best practices in designing and developing APIs. It comprises six sections dedicated to: the API design, API patterns, maintaining backwards compatibility, HTTP API & REST, SDK and UI libraries, API product management."
|
||||
/>
|
||||
<meta property="og:image" content="assets/header.png" />
|
||||
<meta
|
||||
@ -39,11 +39,17 @@
|
||||
<h2>Free e-book</h2>
|
||||
<br />Subscribe for updates on <a class="github" href="https://github.com/twirl/The-API-Book"></a>
|
||||
<br/>Follow me on <a class="linkedin" href="https://www.linkedin.com/in/twirl/"></a> · <a class="twitter" href="https://twitter.com/blogovodoved"></a> · <a class="medium" href="https://twirl.medium.com/">Medium</a>
|
||||
<br />Support this work on <a class="patreon" href="https://www.patreon.com/yatwirl">Patreon</a> · <a class="kindle" href="https://www.amazon.com/gp/product/B09RHH44S5/ref=dbs_a_def_rwt_hsch_vapi_tkin_p1_i0">buy Kindle version</a>
|
||||
<br />Support this work on <a class="patreon" href="https://www.patreon.com/yatwirl">Patreon</a> · <a class="kindle" href="https://www.amazon.com/gp/product/B09RHH44S5/ref=dbs_a_def_rwt_hsch_vapi_tkin_p1_i0">buy Kindle version [1st edition]</a>
|
||||
<br />Share: <a class="share share-facebook" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank"></a> · <a class="share share-twitter" href="https://twitter.com/intent/tweet?text=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market&url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&hashtags=API%2CTheAPIBook&via=blogovodoved" target="_blank"></a> · <a class="share share-linkedin" href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank"></a> · <a class="share share-reddit" href="http://www.reddit.com/submit?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&title=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market" target="_blank"></a><br/>⚙️⚙️⚙️
|
||||
</nav>
|
||||
<p>The API-first development is one of the hottest technical topics nowadays, since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.</p>
|
||||
<p>This book is written to share the expertise and describe the best practices in designing and developing APIs. In Section I, we'll discuss the API architecture as a concept: how to build the hierarchy properly, from high-level planning down to final interfaces. Section II is dedicated to expanding existing APIs in a backwards-compatible manner. Finally, in Section III we will talk about the API as a product.</p>
|
||||
<p>API-first development is one of the hottest technical topics nowadays since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.</p>
|
||||
<p>This book is written to share the expertise and describe the best practices in designing and developing APIs. It comprises six sections dedicated to:</p>
|
||||
<ul><li>— the API design</li>
|
||||
<li>— API patterns</li>
|
||||
<li>— backwards compatibility</li>
|
||||
<li>— HTTP API & REST</li>
|
||||
<li>— SDK and UI libraries</li>
|
||||
<li>— API product management.</ul>
|
||||
<p>Illustration & inspiration: <a href="https://www.instagram.com/art.mari.ka/">art.mari.ka</a>.</p>
|
||||
<p>You might download ‘The API’ in <a href="API.en.pdf">PDF</a>, <a href="API.en.epub">EPUB</a>, or <a href="API.en.html">read it online</a>.
|
||||
</p>
|
||||
@ -71,7 +77,7 @@
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><a href="API.en.html#section-3">Section II. The API Patterns</a></h4>
|
||||
<h4><a href="API.en.html#section-3">[Work in Progress] Section II. The API Patterns</a></h4>
|
||||
<ul>
|
||||
<li><a href="API.en.html#chapter-13">Chapter 13. On Design Patterns in the API Context</a></li>
|
||||
<li><a href="API.en.html#chapter-14">Chapter 14. Authenticating Partners and Authorizing API Calls</a></li>
|
||||
@ -99,7 +105,7 @@
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><a href="API.en.html#section-5">Section IV. The HTTP API & REST</a></h4>
|
||||
<h4><a href="API.en.html#section-5">[Work in Progress] Section IV. The HTTP API & REST</a></h4>
|
||||
<ul>
|
||||
<li><a href="API.en.html#chapter-31">Chapter 31. On HTTP API Concept and Terminology</a></li>
|
||||
<li><a href="API.en.html#chapter-32">Chapter 32. The REST Myth</a></li>
|
||||
@ -112,7 +118,7 @@
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><a href="API.en.html#section-6">Section V. The SDK & UI Libraries</a></h4>
|
||||
<h4><a href="API.en.html#section-6">[Work in Progress] Section V. The SDK & UI Libraries</a></h4>
|
||||
<ul>
|
||||
<li><a href="API.en.html#chapter-39">Chapter 39. On the Content of This Section</a></li>
|
||||
<li><a href="API.en.html#chapter-40">Chapter 40. The SDK: Problems and Solutions</a></li>
|
||||
@ -141,7 +147,7 @@
|
||||
<li><a href="API.en.html#api-product-customer-support">Chapter 58. Supporting customers</a></li>
|
||||
<li><a href="API.en.html#api-product-documentation">Chapter 59. The Documentation</a></li>
|
||||
<li><a href="API.en.html#api-product-testing">Chapter 60. The Testing Environment</a></li>
|
||||
<li><a href="API.en.html#api-product-expectations">Chapter 61. Managing expectations</a></li>
|
||||
<li><a href="API.en.html#api-product-expectations">Chapter 61. Managing Expectations</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
@ -10,7 +10,7 @@
|
||||
</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Разработка API — особый навык: API является как мультипликатором ваших возможностей, так и мультипликатором ваших ошибок. Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. В первом разделе мы поговорим о проектировании API: как грамотно выстроить архитектуру, от крупноблочного планирования до конечных интерфейсов. Второй раздел посвящён развитию существующих API с сохранением обратной совместимости. Наконец, в третьем разделе мы поговорим об API как о продукте."
|
||||
content="Разработка API — особый навык: API является как мультипликатором ваших возможностей, так и мультипликатором ваших ошибок. Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. Книга состоит из шести разделов, посвящённых проектированию API, паттернам дизайна API, поддержанию обратной совместимости, HTTP API и REST, SDK и UI-библиотекам, продуктовому управлению API."
|
||||
/>
|
||||
<meta property="og:type" content="article" />
|
||||
<meta
|
||||
@ -19,7 +19,7 @@
|
||||
/>
|
||||
<meta
|
||||
property="og:description"
|
||||
content="Разработка API — особый навык: API является как мультипликатором ваших возможностей, так и мультипликатором ваших ошибок. Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. В первом разделе мы поговорим о проектировании API: как грамотно выстроить архитектуру, от крупноблочного планирования до конечных интерфейсов. Второй раздел посвящён развитию существующих API с сохранением обратной совместимости. Наконец, в третьем разделе мы поговорим об API как о продукте."
|
||||
content="Разработка API — особый навык: API является как мультипликатором ваших возможностей, так и мультипликатором ваших ошибок. Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. Книга состоит из шести разделов, посвящённых проектированию API, паттернам дизайна API, поддержанию обратной совместимости, HTTP API и REST, SDK и UI-библиотекам, продуктовому управлению API."
|
||||
/>
|
||||
<meta property="og:image" content="assets/header.png" />
|
||||
<meta
|
||||
@ -43,7 +43,13 @@
|
||||
<br />Поделиться: <a class="share share-vk" href="https://vk.com/share.php?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2Findex.ru.html" target="_blank"></a> · <a class="share share-facebook" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2Findex.ru.html" target="_blank"></a> · <a class="share share-twitter" href="https://twitter.com/intent/tweet?text=%C2%ABAPI%C2%BB%20%D0%A1%D0%B5%D1%80%D0%B3%D0%B5%D1%8F%20%D0%9A%D0%BE%D0%BD%D1%81%D1%82%D0%B0%D0%BD%D1%82%D0%B8%D0%BD%D0%BE%D0%B2%D0%B0%20%E2%80%94%20%D0%BA%D0%BD%D0%B8%D0%B3%D0%B0%20%D0%BE%20%D0%B4%D0%B8%D0%B7%D0%B0%D0%B9%D0%BD%D0%B5%20API%20%D0%B8%20%D0%B5%D0%B3%D0%BE%20%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D0%BE%D0%B2%D0%BE%D0%BC%20%D0%B8%20%D1%82%D0%B5%D1%85%D0%BD%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%BC%20%D1%80%D0%B0%D0%B7%D0%B2%D0%B8%D1%82%D0%B8%D0%B8&url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2Findex.ru.html&hashtags=API%2CTheAPIBook&via=blogovodoved" target="_blank"></a> · <a class="share share-linkedin" href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2Findex.ru.html" target="_blank"></a> · <a class="share share-reddit" href="http://www.reddit.com/submit?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2Findex.ru.html&title=%C2%ABAPI%C2%BB%20%D0%A1%D0%B5%D1%80%D0%B3%D0%B5%D1%8F%20%D0%9A%D0%BE%D0%BD%D1%81%D1%82%D0%B0%D0%BD%D1%82%D0%B8%D0%BD%D0%BE%D0%B2%D0%B0%20%E2%80%94%20%D0%BA%D0%BD%D0%B8%D0%B3%D0%B0%20%D0%BE%20%D0%B4%D0%B8%D0%B7%D0%B0%D0%B9%D0%BD%D0%B5%20API%20%D0%B8%20%D0%B5%D0%B3%D0%BE%20%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D0%BE%D0%B2%D0%BE%D0%BC%20%D0%B8%20%D1%82%D0%B5%D1%85%D0%BD%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%BC%20%D1%80%D0%B0%D0%B7%D0%B2%D0%B8%D1%82%D0%B8%D0%B8" target="_blank"></a><br/>⚙️⚙️⚙️
|
||||
</nav>
|
||||
<p>«API-first» подход — одна из самых горячих горячих тем в разработке программного обеспечения в наше время. Многие компании начали понимать, что API выступает мультипликатором их возможностей — но также умножает и допущенные ошибки.</p>
|
||||
<p>Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. В первом разделе мы поговорим о проектировании API: как грамотно выстроить архитектуру, от крупноблочного планирования до конечных интерфейсов. Второй раздел посвящён развитию существующих API с сохранением обратной совместимости. Наконец, в третьем разделе мы поговорим об API как о продукте.</p>
|
||||
<p>Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. Книга состоит из шести разделов, посвящённых:</p>
|
||||
<ul><li>— проектированию API,</li>
|
||||
<li>— паттернам дизайна API,</li>
|
||||
<li>— поддержанию обратной совместимости,</li>
|
||||
<li>— HTTP API и REST,</li>
|
||||
<li>— SDK и UI-библиотекам,</li>
|
||||
<li>— продуктовому управлению API.</li></ul>
|
||||
<p>Иллюстрации и вдохновение: Maria Konstantinova · <a href="https://www.instagram.com/art.mari.ka/">art.mari.ka</a>.</p>
|
||||
<p>Вы можете скачать книгу «API» в формате <a href="API.ru.pdf">PDF</a>, <a href="API.ru.epub">EPUB</a>, или <a href="API.ru.html">прочитать её онлайе</a>.
|
||||
</p>
|
||||
@ -71,7 +77,7 @@
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><a href="API.ru.html#section-3">Раздел II. Паттерны дизайна API</a></h4>
|
||||
<h4><a href="API.ru.html#section-3">[В разработке] Раздел II. Паттерны дизайна API</a></h4>
|
||||
<ul>
|
||||
<li><a href="API.ru.html#chapter-13">Глава 13. О паттернах проектирования в контексте API</a></li>
|
||||
<li><a href="API.ru.html#chapter-14">Глава 14. Аутентификация партнёров и авторизация вызовов API</a></li>
|
||||
@ -99,7 +105,7 @@
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><a href="API.ru.html#section-5">Раздел IV. HTTP API и REST</a></h4>
|
||||
<h4><a href="API.ru.html#section-5">[В разработке] Раздел IV. HTTP API и REST</a></h4>
|
||||
<ul>
|
||||
<li><a href="API.ru.html#chapter-31">Глава 31. О концепции HTTP API и терминологии</a></li>
|
||||
<li><a href="API.ru.html#chapter-32">Глава 32. Мифология REST</a></li>
|
||||
@ -112,7 +118,7 @@
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<h4><a href="API.ru.html#section-6">Раздел V. SDK и UI</a></h4>
|
||||
<h4><a href="API.ru.html#section-6">[В разработке] Раздел V. SDK и UI</a></h4>
|
||||
<ul>
|
||||
<li><a href="API.ru.html#chapter-39">Глава 39. О содержании раздела</a></li>
|
||||
<li><a href="API.ru.html#chapter-40">Глава 40. SDK: проблемы и решения</a></li>
|
||||
|
Binary file not shown.
@ -581,7 +581,7 @@ ul.references li p a.back-anchor {
|
||||
<li><a class="share share-facebook" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank"> </a></li><li><a class="share share-twitter" href="https://twitter.com/intent/tweet?text=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market&url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&hashtags=API%2CTheAPIBook&via=blogovodoved" target="_blank"> </a></li><li><a class="share share-linkedin" href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank"> </a></li><li><a class="share share-reddit" href="http://www.reddit.com/submit?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&title=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market" target="_blank"> </a></li>
|
||||
<li class="copy-link">Link: <input type="text" value="https://twirl.github.io/The-API-Book/"><button type="button" class="copy-button"></button></li>
|
||||
</ul>
|
||||
<section class="side-toc"><nav><h2 class="toc">Table of Contents</h2><ul class="table-of-contents"><li><a href="#section-1">Introduction</a><ul><li><a href="#intro-structure">Chapter 1. On the Structure of This Book</a></li><li><a href="#intro-api-definition">Chapter 2. The API Definition</a></li><li><a href="#intro-api-quality">Chapter 3. API Quality Criteria</a></li><li><a href="#intro-back-compat">Chapter 4. On Backwards Compatibility</a></li><li><a href="#intro-versioning">Chapter 5. On Versioning</a></li><li><a href="#intro-terms-notation">Chapter 6. Terms and Notation Keys</a></li></ul></li><li><a href="#section-2">Section I. The API Design</a><ul><li><a href="#api-design-context-pyramid">Chapter 7. The API Contexts Pyramid</a></li><li><a href="#api-design-defining-field">Chapter 8. Defining an Application Field</a></li><li><a href="#api-design-separating-abstractions">Chapter 9. Separating Abstraction Levels</a></li><li><a href="#api-design-isolating-responsibility">Chapter 10. Isolating Responsibility Areas</a></li><li><a href="#api-design-describing-interfaces">Chapter 11. Describing Final Interfaces</a></li><li><a href="#api-design-annex">Chapter 12. Annex to Section I. Generic API Example</a></li></ul></li><li><a href="#section-3">Section II. The Backwards Compatibility</a><ul><li><a href="#back-compat-statement">Chapter 13. The Backwards Compatibility Problem Statement</a></li><li><a href="#back-compat-iceberg-waterline">Chapter 14. On the Waterline of the Iceberg</a></li><li><a href="#back-compat-abstracting-extending">Chapter 15. Extending through Abstracting</a></li><li><a href="#back-compat-strong-coupling">Chapter 16. Strong Coupling and Related Problems</a></li><li><a href="#back-compat-weak-coupling">Chapter 17. Weak Coupling</a></li><li><a href="#back-compat-universal-interfaces">Chapter 18. Interfaces as a Universal Pattern</a></li><li><a href="#back-compat-serenity-notepad">Chapter 19. The Serenity Notepad</a></li></ul></li><li><a href="#section-4">Section III. The API Product</a><ul><li><a href="#api-product">Chapter 20. API as a Product</a></li><li><a href="#api-product-business-models">Chapter 21. The API Business Models</a></li><li><a href="#api-product-vision">Chapter 22. Developing a Product Vision</a></li><li><a href="#api-product-devrel">Chapter 23. Communicating with Developers</a></li><li><a href="#api-product-business-comms">Chapter 24. Communicating with Business Owners</a></li><li><a href="#api-product-range">Chapter 25. The API Services Range</a></li><li><a href="#api-product-kpi">Chapter 26. The API Key Performance Indicators</a></li><li><a href="#api-product-antifraud">Chapter 27. Identifying Users and Preventing Fraud</a></li><li><a href="#api-product-tos-violations">Chapter 28. The Technical Means of Preventing ToS Violations</a></li><li><a href="#api-product-customer-support">Chapter 29. Supporting customers</a></li><li><a href="#api-product-documentation">Chapter 30. The Documentation</a></li><li><a href="#api-product-testing">Chapter 31. The Testing Environment</a></li><li><a href="#api-product-expectations">Chapter 32. Managing expectations</a></li></ul></li></ul></nav><div style="page-break-after: always;"></div></section>
|
||||
<section class="side-toc"><nav><h2 class="toc">Table of Contents</h2><ul class="table-of-contents"><li><a href="#section-1">Introduction</a><ul><li><a href="#intro-structure">Chapter 1. On the Structure of This Book</a></li><li><a href="#intro-api-definition">Chapter 2. The API Definition</a></li><li><a href="#intro-api-quality">Chapter 3. API Quality Criteria</a></li><li><a href="#intro-back-compat">Chapter 4. On Backwards Compatibility</a></li><li><a href="#intro-versioning">Chapter 5. On Versioning</a></li><li><a href="#intro-terms-notation">Chapter 6. Terms and Notation Keys</a></li></ul></li><li><a href="#section-2">Section I. The API Design</a><ul><li><a href="#api-design-context-pyramid">Chapter 7. The API Contexts Pyramid</a></li><li><a href="#api-design-defining-field">Chapter 8. Defining an Application Field</a></li><li><a href="#api-design-separating-abstractions">Chapter 9. Separating Abstraction Levels</a></li><li><a href="#api-design-isolating-responsibility">Chapter 10. Isolating Responsibility Areas</a></li><li><a href="#api-design-describing-interfaces">Chapter 11. Describing Final Interfaces</a></li><li><a href="#api-design-annex">Chapter 12. Annex to Section I. Generic API Example</a></li></ul></li><li><a href="#section-3">Section II. The Backwards Compatibility</a><ul><li><a href="#back-compat-statement">Chapter 13. The Backwards Compatibility Problem Statement</a></li><li><a href="#back-compat-iceberg-waterline">Chapter 14. On the Waterline of the Iceberg</a></li><li><a href="#back-compat-abstracting-extending">Chapter 15. Extending through Abstracting</a></li><li><a href="#back-compat-strong-coupling">Chapter 16. Strong Coupling and Related Problems</a></li><li><a href="#back-compat-weak-coupling">Chapter 17. Weak Coupling</a></li><li><a href="#back-compat-universal-interfaces">Chapter 18. Interfaces as a Universal Pattern</a></li><li><a href="#back-compat-serenity-notepad">Chapter 19. The Serenity Notepad</a></li></ul></li><li><a href="#section-4">Section III. The API Product</a><ul><li><a href="#api-product">Chapter 20. API as a Product</a></li><li><a href="#api-product-business-models">Chapter 21. The API Business Models</a></li><li><a href="#api-product-vision">Chapter 22. Developing a Product Vision</a></li><li><a href="#api-product-devrel">Chapter 23. Communicating with Developers</a></li><li><a href="#api-product-business-comms">Chapter 24. Communicating with Business Owners</a></li><li><a href="#api-product-range">Chapter 25. The API Services Range</a></li><li><a href="#api-product-kpi">Chapter 26. The API Key Performance Indicators</a></li><li><a href="#api-product-antifraud">Chapter 27. Identifying Users and Preventing Fraud</a></li><li><a href="#api-product-tos-violations">Chapter 28. The Technical Means of Preventing ToS Violations</a></li><li><a href="#api-product-customer-support">Chapter 29. Supporting customers</a></li><li><a href="#api-product-documentation">Chapter 30. The Documentation</a></li><li><a href="#api-product-testing">Chapter 31. The Testing Environment</a></li><li><a href="#api-product-expectations">Chapter 32. Managing Expectations</a></li></ul></li></ul></nav><div style="page-break-after: always;"></div></section>
|
||||
<button type="button" class="close"></button></aside><article>
|
||||
<div class="cover">
|
||||
<h1>
|
||||
@ -596,7 +596,7 @@ ul.references li p a.back-anchor {
|
||||
<img class="cc-by-nc-img" alt="Creative Commons «Attribution-NonCommercial» Logo" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFgAAAAfCAMAAABUFvrSAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAAAEZ0FNQQAAsY58+1GTAAAAAXNSR0IB2cksfwAAAblQTFRF////////////////8fHx7+/v4+Pj39/f1tXV09bS0tXS0tXR0dTR0dTQ0NTQ0NPPz9PPztLOztHNzdHNzdHMz8/PzdDMzNDMzNDLzM/Ly8/Ly8/Ky87Kys3Jyc3Jyc3IyMzIyMzHx8vHxsrGxsrFxcnFyMfHxcnExMnExMjDw8jDxMfDw8fCwsfCwcXAwMXAwMW/wMS/v8S+v8O+vsO+vsK9vcK9vcK8v7+/vMG8vMG7vMC8u8C7u8C6ur+6ur+5ub65ub64uL23t7y2urm5tru1tbq0tLqztLmzs7iysrixsrexsbewsbawsLavsLWvr7Wur7SusLOvrrStrrOtr7KvrbOsrLKrr6+vq7GqrKurn6OenqCdn5+fnp2dmpiZlpmWk5iTkZSRkZORkY+Pj4+PiYyJjIqLh4aHhIaEhIWEgoWChIGCgICAfX98fH98fnt8eXx5eHV2dnN0dXJzcHJvcHBwaGVmYGBgXV5dWldYUFFQUFBQQ0RDQEBAPj8+Pzs8NTY1MjMxMjExMDAwMS0uKSkpKCkoKCUmIx8gICAgHxscGxsbGRkZEBAQDg4ODQ4NDQwNAAAABjFVaAAAAAN0Uk5TAAoO5yEBUwAAA5NJREFUeNq1lo930lYUx7NdaUprjKZzQIlFHJtSGVarg+E6Slmx2OpwOihqt1mqm27oGJNh+VG3pbCwGvH7F+8kAUpC6Jl4+g4575xveJ933/e+d1+Y93EojWGARDwWuRyc9XlnRJfD4XKf8vr8wfnIYjyRXPv6djqdyb59Axgk4tHQxYDP4xZ4bsJunzjKC9MeX2AuFFXJqdvpzEhkBvFo6IL/jChwT2ptdRHt2mPuhNt7LvhZNJ64fjN1pxtyoaG+bhTMDEsdDGKhC36vk8/t7Ru0t8k7PGeDocX4yurNTsgPmkC9VKoDzQf9hCE6GEQu+r0OrgJAKefD4XxZAVA5/4Hn3Fwktpxc00O+9xpVloiIreJ1H2GYDgaXA2ecKlfJ20hvGwrQPO/wBuYXlhJayNlsE2UiAtTXaO4DdH1r26yDQdAn8hVAYqnXbBJQ4d2+YCi2nLxxK53JFFAd74Kpip6fBfz9PdHWqzfFMYOugmdPCzlAshEZyZsnPP5LC/Frq6k7mUwDffOyaHTHN/CP/PIP5H/CXYOugn1ubg/KSTI0m4I9btoX/DyWuK56gbqqlqEtnOroja///pssy8WxcaOugr1TT4A8mdoG8FjwBq5El5M3VHCJNCd0L0r74BLRJ0UAxXGDroJnjteg2IjC1Xo9r3cPiUhBjT+lerGydutgMNFYcVeWt78ygUWurS4wrO3g+rrWldVlt4+6z859sXRtLXWQFUR05Dsal2VZfmm0wjUJPCSS0GLDrQ0JErve2tC8mHD5gpGlxGoq3U2eHrAheSzRtry7i+LdX/81Js9pB8LqmLw+tGN3GLA7PuqCC6iS9XarEo398urN1pGB7fa/wP0HpDR4QH7cNusGK2wnW3kJktqZrRjlSHeS18laL3kltDmxl7xs9l4TkMolyVyEhujadqtAod52W69rHbVQ42f8l77Ut9soZdM7ldO8sDogn15ZXE7qVejtC/3H2pFmDz7So4BnTwv3rYpQTvDMzi/EV7QiNAoYz0T+BSD1lSFWK5viz+90TQN47jrWX+hteQX4k3M+w7uC8dRx7IXpauI+/MH0T/18QH/6df0hsgDjqYu/33+Z5ninmQvq/Ghgwo5KFmA8FwUu173+NzlBHPShWzYHJySL6bpg/PWte+o4N2m3T3K8MP3NzqBp1kZ0bRgWMYCdR1dFl9PpEq8+2rHKxvCID/D4ML4K3zsk7n9pO/RNngRtJQAAAABJRU5ErkJggg==">
|
||||
<p class="cc-by-nc">This book is distributed under the <a href="http://creativecommons.org/licenses/by-nc/4.0/">Creative Commons Attribution-NonCommercial 4.0 International licence</a>.</p>
|
||||
<p class="text-align-left">Source code available at <a target="_blank" href="https://github.com/twirl/The-API-Book">github.com/twirl/The-API-Book</a></p>
|
||||
</div><p class="share text-align-left">Share: <a class="share share-facebook" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank">facebook</a> · <a class="share share-twitter" href="https://twitter.com/intent/tweet?text=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market&url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&hashtags=API%2CTheAPIBook&via=blogovodoved" target="_blank">twitter</a> · <a class="share share-linkedin" href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank">linkedin</a> · <a class="share share-reddit" href="http://www.reddit.com/submit?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&title=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market" target="_blank">reddit</a></p><div class="page-break"></div><nav><h2 class="toc">Table of Contents</h2><ul class="table-of-contents"><li><a href="#section-1">Introduction</a><ul><li><a href="#intro-structure">Chapter 1. On the Structure of This Book</a></li><li><a href="#intro-api-definition">Chapter 2. The API Definition</a></li><li><a href="#intro-api-quality">Chapter 3. API Quality Criteria</a></li><li><a href="#intro-back-compat">Chapter 4. On Backwards Compatibility</a></li><li><a href="#intro-versioning">Chapter 5. On Versioning</a></li><li><a href="#intro-terms-notation">Chapter 6. Terms and Notation Keys</a></li></ul></li><li><a href="#section-2">Section I. The API Design</a><ul><li><a href="#api-design-context-pyramid">Chapter 7. The API Contexts Pyramid</a></li><li><a href="#api-design-defining-field">Chapter 8. Defining an Application Field</a></li><li><a href="#api-design-separating-abstractions">Chapter 9. Separating Abstraction Levels</a></li><li><a href="#api-design-isolating-responsibility">Chapter 10. Isolating Responsibility Areas</a></li><li><a href="#api-design-describing-interfaces">Chapter 11. Describing Final Interfaces</a></li><li><a href="#api-design-annex">Chapter 12. Annex to Section I. Generic API Example</a></li></ul></li><li><a href="#section-3">Section II. The Backwards Compatibility</a><ul><li><a href="#back-compat-statement">Chapter 13. The Backwards Compatibility Problem Statement</a></li><li><a href="#back-compat-iceberg-waterline">Chapter 14. On the Waterline of the Iceberg</a></li><li><a href="#back-compat-abstracting-extending">Chapter 15. Extending through Abstracting</a></li><li><a href="#back-compat-strong-coupling">Chapter 16. Strong Coupling and Related Problems</a></li><li><a href="#back-compat-weak-coupling">Chapter 17. Weak Coupling</a></li><li><a href="#back-compat-universal-interfaces">Chapter 18. Interfaces as a Universal Pattern</a></li><li><a href="#back-compat-serenity-notepad">Chapter 19. The Serenity Notepad</a></li></ul></li><li><a href="#section-4">Section III. The API Product</a><ul><li><a href="#api-product">Chapter 20. API as a Product</a></li><li><a href="#api-product-business-models">Chapter 21. The API Business Models</a></li><li><a href="#api-product-vision">Chapter 22. Developing a Product Vision</a></li><li><a href="#api-product-devrel">Chapter 23. Communicating with Developers</a></li><li><a href="#api-product-business-comms">Chapter 24. Communicating with Business Owners</a></li><li><a href="#api-product-range">Chapter 25. The API Services Range</a></li><li><a href="#api-product-kpi">Chapter 26. The API Key Performance Indicators</a></li><li><a href="#api-product-antifraud">Chapter 27. Identifying Users and Preventing Fraud</a></li><li><a href="#api-product-tos-violations">Chapter 28. The Technical Means of Preventing ToS Violations</a></li><li><a href="#api-product-customer-support">Chapter 29. Supporting customers</a></li><li><a href="#api-product-documentation">Chapter 30. The Documentation</a></li><li><a href="#api-product-testing">Chapter 31. The Testing Environment</a></li><li><a href="#api-product-expectations">Chapter 32. Managing expectations</a></li></ul></li></ul></nav><div style="page-break-after: always;"></div><section class="main-content">
|
||||
</div><p class="share text-align-left">Share: <a class="share share-facebook" href="https://www.facebook.com/sharer.php?u=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank">facebook</a> · <a class="share share-twitter" href="https://twitter.com/intent/tweet?text=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market&url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&hashtags=API%2CTheAPIBook&via=blogovodoved" target="_blank">twitter</a> · <a class="share share-linkedin" href="https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F" target="_blank">linkedin</a> · <a class="share share-reddit" href="http://www.reddit.com/submit?url=https%3A%2F%2Ftwirl.github.io%2FThe-API-Book%2F&title=The%20API%20by%20Sergey%20Konstantinov%20%E2%80%94%20a%20book%20about%20designing%20APIs%2C%20extending%20them%20and%20finding%20a%20proper%20place%20in%20the%20market" target="_blank">reddit</a></p><div class="page-break"></div><nav><h2 class="toc">Table of Contents</h2><ul class="table-of-contents"><li><a href="#section-1">Introduction</a><ul><li><a href="#intro-structure">Chapter 1. On the Structure of This Book</a></li><li><a href="#intro-api-definition">Chapter 2. The API Definition</a></li><li><a href="#intro-api-quality">Chapter 3. API Quality Criteria</a></li><li><a href="#intro-back-compat">Chapter 4. On Backwards Compatibility</a></li><li><a href="#intro-versioning">Chapter 5. On Versioning</a></li><li><a href="#intro-terms-notation">Chapter 6. Terms and Notation Keys</a></li></ul></li><li><a href="#section-2">Section I. The API Design</a><ul><li><a href="#api-design-context-pyramid">Chapter 7. The API Contexts Pyramid</a></li><li><a href="#api-design-defining-field">Chapter 8. Defining an Application Field</a></li><li><a href="#api-design-separating-abstractions">Chapter 9. Separating Abstraction Levels</a></li><li><a href="#api-design-isolating-responsibility">Chapter 10. Isolating Responsibility Areas</a></li><li><a href="#api-design-describing-interfaces">Chapter 11. Describing Final Interfaces</a></li><li><a href="#api-design-annex">Chapter 12. Annex to Section I. Generic API Example</a></li></ul></li><li><a href="#section-3">Section II. The Backwards Compatibility</a><ul><li><a href="#back-compat-statement">Chapter 13. The Backwards Compatibility Problem Statement</a></li><li><a href="#back-compat-iceberg-waterline">Chapter 14. On the Waterline of the Iceberg</a></li><li><a href="#back-compat-abstracting-extending">Chapter 15. Extending through Abstracting</a></li><li><a href="#back-compat-strong-coupling">Chapter 16. Strong Coupling and Related Problems</a></li><li><a href="#back-compat-weak-coupling">Chapter 17. Weak Coupling</a></li><li><a href="#back-compat-universal-interfaces">Chapter 18. Interfaces as a Universal Pattern</a></li><li><a href="#back-compat-serenity-notepad">Chapter 19. The Serenity Notepad</a></li></ul></li><li><a href="#section-4">Section III. The API Product</a><ul><li><a href="#api-product">Chapter 20. API as a Product</a></li><li><a href="#api-product-business-models">Chapter 21. The API Business Models</a></li><li><a href="#api-product-vision">Chapter 22. Developing a Product Vision</a></li><li><a href="#api-product-devrel">Chapter 23. Communicating with Developers</a></li><li><a href="#api-product-business-comms">Chapter 24. Communicating with Business Owners</a></li><li><a href="#api-product-range">Chapter 25. The API Services Range</a></li><li><a href="#api-product-kpi">Chapter 26. The API Key Performance Indicators</a></li><li><a href="#api-product-antifraud">Chapter 27. Identifying Users and Preventing Fraud</a></li><li><a href="#api-product-tos-violations">Chapter 28. The Technical Means of Preventing ToS Violations</a></li><li><a href="#api-product-customer-support">Chapter 29. Supporting customers</a></li><li><a href="#api-product-documentation">Chapter 30. The Documentation</a></li><li><a href="#api-product-testing">Chapter 31. The Testing Environment</a></li><li><a href="#api-product-expectations">Chapter 32. Managing Expectations</a></li></ul></li></ul></nav><div style="page-break-after: always;"></div><section class="main-content">
|
||||
<nav class="page-main"><ul class="nav-folded">
|
||||
<li class="share"></li>
|
||||
<li class="para">§</li>
|
||||
@ -3974,7 +3974,7 @@ ProgramContext.dispatch = (action) => {
|
||||
<p>The main disadvantage is the necessity to create a separate scenario for each unhappy path (effectively, for every possible error), and give developers the capability of denoting which scenario they want to run. (For example, like that: if there is a pre-agreed comment to the order, the system will simulate a specific error, and developers will be able to write and debug the code that deals with the error.)</p>
|
||||
<h4>The Automation of Testing</h4>
|
||||
<p>Your final goal in implementing testing APIs, regardless of which option you choose, is allowing partners to automate the QA process for their products. The testing environment should be developed with this purpose in mind; for example, if an end user might be brought to a 3-D Secure page to pay for the order, the testing environment API must provide some way of simulating the successful (or not) passing of this step. Also, in both variants, it's possible (and desirable) to allow running the scenarios in a fast-forward manner that will allow making auto-testing much faster than manual testing.</p>
|
||||
<p>Of course, not every partner will be able to employ this possibility (which also means that a “manual” way of testing usage scenarios must always be supported alongside the programmatical one) simply because not every business might afford to hire a QA automation engineer. Nevertheless, the ability to write such auto-tests is your API's huge competitive advantage from a technically advanced partner's point of view.</p><div class="page-break"></div><h3><a href="#api-product-expectations" class="anchor" id="api-product-expectations">Chapter 32. Managing expectations</a><a href="#chapter-32" class="secondary-anchor" id="chapter-32"> </a></h3>
|
||||
<p>Of course, not every partner will be able to employ this possibility (which also means that a “manual” way of testing usage scenarios must always be supported alongside the programmatical one) simply because not every business might afford to hire a QA automation engineer. Nevertheless, the ability to write such auto-tests is your API's huge competitive advantage from a technically advanced partner's point of view.</p><div class="page-break"></div><h3><a href="#api-product-expectations" class="anchor" id="api-product-expectations">Chapter 32. Managing Expectations</a><a href="#chapter-32" class="secondary-anchor" id="chapter-32"> </a></h3>
|
||||
<p>Finally, the last aspect we would like to shed the light on is managing partners' expectations regarding the further development of the API. If we talk about consumer qualities, APIs differ little from other B2B software products: in both cases, you need to form some understanding of SLA conditions, available features, interface responsiveness and other characteristics that are important for clients. Still, APIs have their specificities</p>
|
||||
<h4>Versioning and Application Lifecycle</h4>
|
||||
<p>Ideally, the API once published should live eternally; but as we all are reasonable people, we do understand it's impossible in the real life. Even if we continue supporting older versions, they will still become outdated eventually, and partners will need to rewrite the code to use newer functionality.</p>
|
||||
|
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -1,5 +1,5 @@
|
||||
{
|
||||
"description": "A book on APIs",
|
||||
"description": "“The API” book by Sergey Konstantinov",
|
||||
"homepage": "https://github.com/twirl/The-API-Book",
|
||||
"license": "CC-BY-NC-4.0",
|
||||
"author": "Sergey Konstantinov <twirl-team@yandex.ru>",
|
||||
|
@ -1,13 +1,13 @@
|
||||
### [On the Structure of This Book][intro-structure]
|
||||
|
||||
The book you're holding in your hands comprises this Introduction and three sections: “The API Design,” “The Backwards Compatibility,” and “The API Product.”
|
||||
The book you're holding in your hands is dedicated to developing APIs as a separate engineering task. Though many concepts we're going to discuss apply to any type of software, our primary goal is to describe those problems and approaches to solving them that are most relevant in the context of the API subject area.
|
||||
|
||||
In Section I, we will discuss designing APIs as a concept: how to build the architecture properly, from high-level planning down to final interfaces.
|
||||
We expect that the reader possesses expertise in software engineering, so we do not provide detailed definitions and explanations of the terms that a developer should already be familiar with in our understanding. Without this knowledge, it will be rather uncomfortable to read the last section of the book (and even more so, other sections). We sincerely apologize for this but that's the only way of writing the book without tripling its size.
|
||||
|
||||
Section II is dedicated to an API lifecycle: how interfaces evolve over time, and how to develop the product to match users' needs.
|
||||
The book comprises the Introduction and six large sections. The first three (namely, “The API Design”, “The API Patterns”, and “The Backwards Compatibility”) are fully abstract and not bound to any concrete technology. We hope they will help those readers who seek building a systematic understanding of the API architecture in developing complex interface hierarchies. The proposed approach, as we see it, allows for designing APIs from start to finish, from a raw idea to concrete implementation.
|
||||
|
||||
Finally, Section III is more about the un-engineering sides of the API, like API marketing, organizing customer support, working with a community, etc.
|
||||
The fourth and fifth sections are dedicated to specific technologies, namely developing HTTP APIs (in the “REST paradigm”) and SDKs (we will talk mostly of UI component libraries).
|
||||
|
||||
The first two sections are interesting to engineers mostly, while the third section is more relevant to both engineers and product managers. However, we insist that the third section is the most important one for the API software developer. Since an API is a product for engineers, you cannot simply pronounce a non-engineering team responsible for product planning and support. Nobody but you knows better your API's product features.
|
||||
Finally, in the sixth section, which is the least technical of all, we will discuss APIs as products and focus on non-engineering aspects of the API lifecycle: doing market research, positioning the service, communicating to consumers, setting KPIs for the team, etc. We insist that the last section is equally important to both PMs and software engineers as products for developers thrive only if the product and technical teams jointly work on them.
|
||||
|
||||
Let's start.
|
@ -1,13 +0,0 @@
|
||||
### [On Backwards Compatibility][intro-back-compat]
|
||||
|
||||
Backwards compatibility is a *temporal* characteristic of your API. An obligation to maintain backwards compatibility is the crucial point where API development differs from software development in general.
|
||||
|
||||
Of course, backwards compatibility isn't an absolute. In some subject areas shipping new backwards-incompatible API versions is a routine. Nevertheless, every time you deploy a new backwards-incompatible API version, the developers need to make some non-zero effort to adapt their code to the new API version. In this sense, releasing new API versions puts a sort of a “tax” on customers. They must spend quite real money just to make sure their product continues working.
|
||||
|
||||
Large companies, which occupy firm market positions, could afford to charge such a tax. Furthermore, they may introduce penalties for those who refuse to adapt their code to new API versions, up to disabling their applications.
|
||||
|
||||
From our point of view, such a practice cannot be justified. Don't impose hidden levies on your customers. If you're able to avoid breaking backwards compatibility — never break it.
|
||||
|
||||
Of course, maintaining old API versions is a sort of a tax either. Technology changes, and you cannot foresee everything, regardless of how nice your API is initially designed. At some point keeping old API versions results in an inability to provide new functionality and support new platforms, and you will be forced to release a new version. But at least you will be able to explain to your customers why they need to make an effort.
|
||||
|
||||
We will discuss API lifecycle and version policies in Section II.
|
@ -1,14 +1,21 @@
|
||||
### [On Versioning][intro-versioning]
|
||||
|
||||
Here and throughout this book, we firmly stick to [semver](https://semver.org/) principles of versioning.
|
||||
|
||||
1. API versions are denoted with three numbers, i.e. `1.2.3`.
|
||||
2. The first number (a major version) increases when backwards-incompatible changes in the API are introduced.
|
||||
3. The second number (a minor version) increases when new functionality is added to the API, keeping backwards compatibility intact.
|
||||
4. The third number (a patch) increases when a new API version contains bug fixes only.
|
||||
|
||||
Sentences “a major API version” and “new API version, containing backwards-incompatible changes” are therefore to be considered equivalent ones.
|
||||
|
||||
It is usually (though not necessary) agreed that the last stable API release might be referenced by either a full version (e.g. `1.2.3`) or a reduced one (`1.2` or just `1`). Some systems support more sophisticated schemes of defining the desired version (for example, `^1.2.3` reads like “get the last stable API release that is backwards-compatible to the `1.2.3` version”) or additional shortcuts (for example, `1.2-beta` to refer to the last beta release of the `1.2` API version family). In this book, we will mostly use designations like `v1` (`v2`, `v3`, etc.) to denote the latest stable release of the `1.x.x` version family of an API.
|
||||
|
||||
The practical meaning of this versioning system and the applicable policies will be discussed in more detail in the [“Backwards Compatibility Problem Statement”](#back-compat-statement) chapter.
|
||||
### [The API-first approach][intro-api-first-approach]
|
||||
|
||||
Today, more and more IT companies accept the importance of the “API-first” approach, e.g. the paradigm of developing software with a heavy focus on developing APIs.
|
||||
|
||||
However, we must differentiate the product concept of the API-first approach from a technical one.
|
||||
|
||||
The former means that the first (and sometimes the only) step in developing a service is creating an API for it, and we will discuss it in “The API Product” section of this book.
|
||||
|
||||
If we, however, talk about the API-first approach in a technical sense, we mean the following: **the contract, e.g. the obligation to connect two programmable contexts, precedes the implementation and defines it**. More specifically, two rules are to be respected:
|
||||
* the contract is developed and committed in a form of a specification before the functionality is implemented;
|
||||
* if it turns out that the implementation and the contract differ, it is the implementation to be fixed, not the contract.
|
||||
|
||||
The “specification” in this context is a formal machine-readable description of the contract in one of the interface definition languages (IDL) — for example, in a form of a Swagger/OpenAPI document or a `.proto` file.
|
||||
|
||||
Both rules assert that partner developers' interests are given the highest priority:
|
||||
* rule \#1 allows partners for writing code based on the specification without coordinating the process with the API provider;
|
||||
* the possibility of auto-generating code based on the specification emerges, and that might make development significantly less complex or even automate it;
|
||||
* the code might be developed without having an access to the API;
|
||||
* rule \#2 means partners won't need to change their implementations should some inconsistencies between the specification and the API functionality pop up.
|
||||
|
||||
Therefore, for your API consumers, the API-first approach is a guarantee of a kind. However, it only works if the API was initially well-designed: if some irreparable flaws in the specification surfaced out, we would have no other option but break rule \#2.
|
@ -1,53 +1,13 @@
|
||||
### [Terms and Notation Keys][intro-terms-notation]
|
||||
### [On Backwards Compatibility][intro-back-compat]
|
||||
|
||||
Software development is characterized, among other things, by the existence of many different engineering paradigms, whose adepts sometimes are quite aggressive towards other paradigms' adepts. While writing this book, we are deliberately avoiding using terms like “method,” “object,” “function,” and so on, using the neutral term “entity” instead. “Entity” means some atomic functionality unit, like class, method, object, monad, prototype (underline what you think is right).
|
||||
Backwards compatibility is a *temporal* characteristic of your API. An obligation to maintain backwards compatibility is the crucial point where API development differs from software development in general.
|
||||
|
||||
As for an entity's components, we regretfully failed to find a proper term, so we will use the words “fields” and “methods.”
|
||||
Of course, backwards compatibility isn't an absolute. In some subject areas shipping new backwards-incompatible API versions is a routine. Nevertheless, every time you deploy a new backwards-incompatible API version, the developers need to make some non-zero effort to adapt their code to the new API version. In this sense, releasing new API versions puts a sort of a “tax” on customers. They must spend quite real money just to make sure their product continues working.
|
||||
|
||||
Most of the examples of APIs will be provided in a form of JSON-over-HTTP endpoints. This is some sort of notation that, as we see it, helps to describe concepts in the most comprehensible manner. A `GET /v1/orders` endpoint call could easily be replaced with an `orders.get()` method call, local or remote; JSON could easily be replaced with any other data format. The semantics of statements shouldn't change.
|
||||
Large companies, which occupy firm market positions, could afford to charge such a tax. Furthermore, they may introduce penalties for those who refuse to adapt their code to new API versions, up to disabling their applications.
|
||||
|
||||
Let's take a look at the following example:
|
||||
From our point of view, such a practice cannot be justified. Don't impose hidden levies on your customers. If you're able to avoid breaking backwards compatibility — never break it.
|
||||
|
||||
```
|
||||
// Method description
|
||||
POST /v1/bucket/{id}/some-resource⮠
|
||||
/{resource_id}
|
||||
X-Idempotency-Token: <idempotency token>
|
||||
{
|
||||
…
|
||||
// This is a single-line comment
|
||||
"some_parameter": "example value",
|
||||
…
|
||||
}
|
||||
→ 404 Not Found
|
||||
Cache-Control: no-cache
|
||||
{
|
||||
/* And this is
|
||||
a multiline comment */
|
||||
"error_reason",
|
||||
"error_message":
|
||||
"Long error message⮠
|
||||
that will span several⮠
|
||||
lines"
|
||||
}
|
||||
```
|
||||
Of course, maintaining old API versions is a sort of a tax either. Technology changes, and you cannot foresee everything, regardless of how nice your API is initially designed. At some point keeping old API versions results in an inability to provide new functionality and support new platforms, and you will be forced to release a new version. But at least you will be able to explain to your customers why they need to make an effort.
|
||||
|
||||
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 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;
|
||||
* in response (marked with an arrow symbol `→`) server returns a `404 Not Founds` status code; the status might be omitted (treat it like a `200 OK` if no status is provided);
|
||||
* the response could possibly contain additional notable headers;
|
||||
* the response body is a JSON comprising two fields: `error_reason` and `error_message`; field value absence means that the field contains exactly what you expect it should contain — so there is some generic error reason value which we omitted;
|
||||
* if some token is too long to fit a single line, we will split it into several lines adding `⮠` to indicate it continues next line.
|
||||
|
||||
The term “client” here stands for an application being executed on a user's device, either a native or a web one. The terms “agent” and “user agent” are synonymous to “client.”
|
||||
|
||||
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.
|
||||
|
||||
We will be using 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.
|
||||
|
||||
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.
|
||||
We will discuss API lifecycle and version policies in Section II.
|
14
src/en/clean-copy/01-Introduction/07.md
Normal file
14
src/en/clean-copy/01-Introduction/07.md
Normal file
@ -0,0 +1,14 @@
|
||||
### [On Versioning][intro-versioning]
|
||||
|
||||
Here and throughout this book, we firmly stick to [semver](https://semver.org/) principles of versioning.
|
||||
|
||||
1. API versions are denoted with three numbers, i.e. `1.2.3`.
|
||||
2. The first number (a major version) increases when backwards-incompatible changes in the API are introduced.
|
||||
3. The second number (a minor version) increases when new functionality is added to the API, keeping backwards compatibility intact.
|
||||
4. The third number (a patch) increases when a new API version contains bug fixes only.
|
||||
|
||||
Sentences “a major API version” and “new API version, containing backwards-incompatible changes” are therefore to be considered equivalent ones.
|
||||
|
||||
It is usually (though not necessary) agreed that the last stable API release might be referenced by either a full version (e.g. `1.2.3`) or a reduced one (`1.2` or just `1`). Some systems support more sophisticated schemes of defining the desired version (for example, `^1.2.3` reads like “get the last stable API release that is backwards-compatible to the `1.2.3` version”) or additional shortcuts (for example, `1.2-beta` to refer to the last beta release of the `1.2` API version family). In this book, we will mostly use designations like `v1` (`v2`, `v3`, etc.) to denote the latest stable release of the `1.x.x` version family of an API.
|
||||
|
||||
The practical meaning of this versioning system and the applicable policies will be discussed in more detail in the [“Backwards Compatibility Problem Statement”](#back-compat-statement) chapter.
|
53
src/en/clean-copy/01-Introduction/08.md
Normal file
53
src/en/clean-copy/01-Introduction/08.md
Normal file
@ -0,0 +1,53 @@
|
||||
### [Terms and Notation Keys][intro-terms-notation]
|
||||
|
||||
Software development is characterized, among other things, by the existence of many different engineering paradigms, whose adepts sometimes are quite aggressive towards other paradigms' adepts. While writing this book, we are deliberately avoiding using terms like “method,” “object,” “function,” and so on, using the neutral term “entity” instead. “Entity” means some atomic functionality unit, like class, method, object, monad, prototype (underline what you think is right).
|
||||
|
||||
As for an entity's components, we regretfully failed to find a proper term, so we will use the words “fields” and “methods.”
|
||||
|
||||
Most of the examples of APIs will be provided in a form of JSON-over-HTTP endpoints. This is some sort of notation that, as we see it, helps to describe concepts in the most comprehensible manner. A `GET /v1/orders` endpoint call could easily be replaced with an `orders.get()` method call, local or remote; JSON could easily be replaced with any other data format. The semantics of statements shouldn't change.
|
||||
|
||||
Let's take a look at the following example:
|
||||
|
||||
```
|
||||
// Method description
|
||||
POST /v1/bucket/{id}/some-resource⮠
|
||||
/{resource_id}
|
||||
X-Idempotency-Token: <idempotency token>
|
||||
{
|
||||
…
|
||||
// This is a single-line comment
|
||||
"some_parameter": "example value",
|
||||
…
|
||||
}
|
||||
→ 404 Not Found
|
||||
Cache-Control: no-cache
|
||||
{
|
||||
/* And this is
|
||||
a multiline comment */
|
||||
"error_reason",
|
||||
"error_message":
|
||||
"Long error message⮠
|
||||
that will span several⮠
|
||||
lines"
|
||||
}
|
||||
```
|
||||
|
||||
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 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;
|
||||
* in response (marked with an arrow symbol `→`) server returns a `404 Not Founds` status code; the status might be omitted (treat it like a `200 OK` if no status is provided);
|
||||
* the response could possibly contain additional notable headers;
|
||||
* the response body is a JSON comprising two fields: `error_reason` and `error_message`; field value absence means that the field contains exactly what you expect it should contain — so there is some generic error reason value which we omitted;
|
||||
* if some token is too long to fit a single line, we will split it into several lines adding `⮠` to indicate it continues next line.
|
||||
|
||||
The term “client” here stands for an application being executed on a user's device, either a native or a web one. The terms “agent” and “user agent” are synonymous to “client.”
|
||||
|
||||
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.
|
||||
|
||||
We will be using 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.
|
||||
|
||||
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.
|
@ -3,7 +3,7 @@
|
||||
"author": "Sergey Konstantinov",
|
||||
"chapter": "Chapter",
|
||||
"toc": "Table of Contents",
|
||||
"description": "Designing APIs is a very special skill: API is a multiplier to both your opportunities and mistakes. This book is written to share the expertise and describe the best practices in designing and developing APIs. In Section I, we'll discuss the API architecture as a concept: how to build the hierarchy properly, from high-level planning down to final interfaces. Section II is dedicated to expanding existing APIs in a backwards-compatible manner. Finally, in Section III we will talk about the API as a product.",
|
||||
"description": "API-first development is one of the hottest technical topics nowadays since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well. This book is written to share the expertise and describe the best practices in designing and developing APIs. It comprises six sections dedicated to: the API design, API patterns, maintaining backwards compatibility, HTTP API & REST, SDK and UI libraries, API product management.",
|
||||
"locale": "en_US",
|
||||
"file": "API",
|
||||
"aboutMe": {
|
||||
@ -59,7 +59,7 @@
|
||||
"githubString": "github.com/twirl/The-API-Book",
|
||||
"twitterHref": "https://twitter.com/blogovodoved",
|
||||
"kindleHref": "https://www.amazon.com/gp/product/B09RHH44S5/ref=dbs_a_def_rwt_hsch_vapi_tkin_p1_i0",
|
||||
"kindleTag": "buy Kindle version",
|
||||
"kindleTag": "buy Kindle version [1st edition]",
|
||||
"mediumHref": "https://twirl.medium.com/",
|
||||
"mediumTag": "Medium"
|
||||
},
|
||||
@ -68,8 +68,14 @@
|
||||
"title": "The API",
|
||||
"pageTitle": "Front Page",
|
||||
"contents": [
|
||||
"<p>The API-first development is one of the hottest technical topics nowadays, since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.</p>",
|
||||
"<p>This book is written to share the expertise and describe the best practices in designing and developing APIs. In Section I, we'll discuss the API architecture as a concept: how to build the hierarchy properly, from high-level planning down to final interfaces. Section II is dedicated to expanding existing APIs in a backwards-compatible manner. Finally, in Section III we will talk about the API as a product.</p>",
|
||||
"<p>API-first development is one of the hottest technical topics nowadays since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.</p>",
|
||||
"<p>This book is written to share the expertise and describe the best practices in designing and developing APIs. It comprises six sections dedicated to:</p>",
|
||||
"<ul><li>the API design</li>",
|
||||
"<li>API patterns</li>",
|
||||
"<li>backwards compatibility</li>",
|
||||
"<li>HTTP API & REST</li>",
|
||||
"<li>SDK and UI libraries</li>",
|
||||
"<li>API product management.</ul>",
|
||||
"<p class=\"text-align-left\">Illustrations & inspiration by Maria Konstantinova · <a href=\"https://www.instagram.com/art.mari.ka/\">art.mari.ka</a></p>",
|
||||
"<img class=\"cc-by-nc-img\" alt=\"Creative Commons «Attribution-NonCommercial» Logo\" src=\"https://i.creativecommons.org/l/by-nc/4.0/88x31.png\"/>",
|
||||
"<p class=\"cc-by-nc\">This book is distributed under the <a href=\"http://creativecommons.org/licenses/by-nc/4.0/\">Creative Commons Attribution-NonCommercial 4.0 International licence</a>.</p>"
|
||||
@ -84,8 +90,14 @@
|
||||
"supportThisWork": "Support this work on",
|
||||
"support": ["patreon", "kindle"],
|
||||
"content": [
|
||||
"<p>The API-first development is one of the hottest technical topics nowadays, since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.</p>",
|
||||
"<p>This book is written to share the expertise and describe the best practices in designing and developing APIs. In Section I, we'll discuss the API architecture as a concept: how to build the hierarchy properly, from high-level planning down to final interfaces. Section II is dedicated to expanding existing APIs in a backwards-compatible manner. Finally, in Section III we will talk about the API as a product.</p>",
|
||||
"<p>API-first development is one of the hottest technical topics nowadays since many companies started to realize that API serves as a multiplicator to their opportunities—but it also amplifies the design mistakes as well.</p>",
|
||||
"<p>This book is written to share the expertise and describe the best practices in designing and developing APIs. It comprises six sections dedicated to:</p>",
|
||||
"<ul><li>— the API design</li>",
|
||||
"<li>— API patterns</li>",
|
||||
"<li>— backwards compatibility</li>",
|
||||
"<li>— HTTP API & REST</li>",
|
||||
"<li>— SDK and UI libraries</li>",
|
||||
"<li>— API product management.</ul>",
|
||||
"<p>Illustration & inspiration: <a href=\"https://www.instagram.com/art.mari.ka/\">art.mari.ka</a>.</p>"
|
||||
],
|
||||
"download": "You might download ‘The API’ in",
|
||||
|
@ -1,13 +1,13 @@
|
||||
### [О структуре этой книги][intro-structure]
|
||||
|
||||
Книга, которую вы держите в руках, состоит из введения и двух больших разделов (ещё один находится в разработке).
|
||||
Книга, которую вы держите в руках, посвящена разработке API как отдельной инженерной задаче. Хотя многое из того, о чём мы будем говорить, применимо к написанию любых программ, наша цель состояла прежде всего в описании тех проблем и подходов к их решению, которые характерны именно для предметной области API.
|
||||
|
||||
В первом разделе мы поговорим о проектировании API на стадии разработки концепции — как грамотно выстроить архитектуру, от крупноблочного планирования до конечных интерфейсов.
|
||||
Мы ожидаем, что читатель обладает навыками разработки программного обеспечения, и не даём подробных определений и объяснений в отношении понятий, которыми разработчик должен по нашему мнению владеть. Без такого рода навыков читать последний раздел вам будет достаточно некомфортно (а остальные разделы — ещё сложнее) — за что мы искренне просим прощения, но не видим другого способа написать эту книгу, не раздув её объём ещё в три раза.
|
||||
|
||||
Второй раздел посвящён жизненному циклу API — как интерфейсы эволюционируют со временем и как развивать продукт так, чтобы отвечать потребностям пользователей.
|
||||
Настоящая книга состоит из введения и шести больших разделов. Первые три из них («Проектирование API», «Паттерны дизайна API» и «Обратная совместимость») являются полностью абстрактными и не привязанными ни к каким конкретным технологиям — мы рассчитываем, что они окажутся полезными тем читателям, которые хотят выстроить системное понимание того, что такое архитектура API и как разрабатывать сложные иерархии интерфейсов. Предложенный подход, как мы надеемся, помогает спроектировать API сверху вниз, от сырой идеи до конкретной реализации.
|
||||
|
||||
Наконец, третий раздел будет касаться больше неразработческих сторон жизни API — поддержки, маркетинга, работы с комьюнити.
|
||||
Четвёртый и пятый раздел посвящены вполне конкретным технологиям — разработке HTTP API («REST») и SDK (в основном речь пойдёт о библиотеках визуальных компонент).
|
||||
|
||||
Первые два будут интересны скорее разработчикам, третий — и разработчикам, и менеджерам. При этом мы настаиваем, что как раз третий раздел — самый важный. Ввиду того, что API — продукт для программистов, перекладывать ответственность за его развитие и поддержку на неразработчиков неправильно: никто кроме вас самих не понимает так хорошо продуктовые свойства вашего API.
|
||||
Наконец, в рамках шестого раздела, наименее технического из всех, мы обсудим API как продукт и сфокусируемся на не-разработческих аспектах существования API: изучение рынка, позиционирование сервиса, взаимодействие с потребителями, KPI команды и так далее. Мы настаиваем здесь, что последний раздел одинаково важен и для менеджеров, и для программистов, поскольку технические продукты можно развивать только в тесном взаимодействии продуктовой и технической команд.
|
||||
|
||||
На этом переходим к делу.
|
||||
|
@ -1,17 +1,36 @@
|
||||
### [Критерии качества API][intro-api-quality]
|
||||
|
||||
Прежде чем излагать рекомендации, нам следует определиться с тем, что мы считаем «хорошим» API, и какую пользу мы получаем от того, что наш API «хороший».
|
||||
|
||||
Начнём со второго вопроса. Очевидно, «хорошесть» API определяется в первую очередь тем, насколько он помогает разработчикам решать стоящие перед ними задачи. (Можно резонно возразить, что решение задач, стоящих перед разработчиками, не обязательно влечёт за собой выполнение целей, которые мы ставим перед собой, предлагая разработчикам API. Однако манипуляция общественным мнением не входит в область интересов автора этой книги: здесь и далее предполагается, что API существует в первую очередь для того, чтобы разработчики решали с его помощью свои задачи, а не ради каких-то завуалированных целей).
|
||||
|
||||
Как же дизайн API может помочь разработчику? Очень просто: API должен решать задачи *максимально удобно и понятно*. Путь разработчика от формулирования своей задачи до написания работающего кода должен быть максимально коротким. Это, в том числе, означает, что:
|
||||
|
||||
* из структуры вашего API должно быть максимально очевидно, как решить ту или иную задачу; в идеале разработчику должно быть достаточно одного взгляда на документацию, чтобы понять, с помощью каких сущностей следует решать поставленную задачу;
|
||||
* API должен быть читаемым: в идеале разработчик, просто глядя в номенклатуру методов, сразу пишет правильный код, не углубляясь в детали (особенно — детали реализации!); немаловажно уточнить, что из интерфейсов объектов должно быть понятно не только решение задачи, но и возможные ошибки и исключения;
|
||||
* API должен быть консистентен: при разработке новой функциональности, т.е. при обращении к каким-то незнакомым сущностям в API, разработчик может действовать по аналогии с уже известными ему концепциями API, и его код будет работать.
|
||||
|
||||
Однако статическое удобство и понятность API — это простая часть. В конце концов, никто не стремится специально сделать API нелогичным и нечитаемым — всегда при разработке мы начинаем с каких-то понятных базовых концепций. При минимальном опыте проектирования сложно сделать ядро API, не удовлетворяющее критериям очевидности, читаемости и консистентности.
|
||||
|
||||
Проблемы возникают, когда мы начинаем API развивать. Добавление новой функциональности рано или поздно приводит к тому, что некогда простой и понятный API становится наслоением разных концепций, а попытки сохранить обратную совместимость приводят к нелогичным, неочевидным и попросту плохим решениям. Отчасти это связано так же и с тем, что невозможно обладать полным знанием о будущем: ваше понимание о «правильном» API тоже будет меняться со временем, как в объективной части (какие задачи и каким образом решает API), так и в субъективной — что такое очевидность, читабельность и консистентность для вашего API.
|
||||
|
||||
Принципы, которые мы будем излагать ниже, во многом ориентированы именно на то, чтобы API правильно развивался во времени и не превращался в нагромождение разнородных неконсистентных интерфейсов. Важно понимать, что такой подход тоже не бесплатен: необходимость держать в голове варианты развития событий и закладывать возможность изменений в API означает избыточность интерфейсов и возможно излишнее абстрагирование. И то, и другое, помимо прочего, усложняет и работу программиста, пользующегося вашим API. **Закладывание перспектив «на будущее» имеет смысл, только если это будущее у API есть, иначе это попросту оверинжиниринг**.
|
||||
### [Обзор существующих решений в области разработки API][intro-api-solutions-overview]
|
||||
|
||||
Цель первых трёх разделов настоящей книги — поговорить о дизайне API вне привязки к какой-либо конкретной технологии. Изложенные нами принципы равно применимы как к веб-сервисам, так и, например, к интерфейсам операционных систем.
|
||||
|
||||
Тем не менее, два больших сценария использования явно доминируют, когда мы говорим о разработке API:
|
||||
* разработка клиент-серверных приложений;
|
||||
* разработка клиентских SDK.
|
||||
|
||||
В первом случае мы говорим практически исключительно об API, работающих поверх протокола HTTP. В настоящий момент клиент-серверное взаимодействие, не опирающееся на HTTP, можно встретить разве что в протоколе WebSockets (хотя и он может быть использован совместно с HTTP, что часто и происходит), а также в различных форматах потокового вещания и других узкоспециализированных интерфейсах.
|
||||
|
||||
#### HTTP API
|
||||
|
||||
Несмотря на кажущуюся гомогенность технологии ввиду использования одного протокола прикладного уровня, в действительности же наблюдается значительное разнообразие подходов к имплементации HTTP API.
|
||||
|
||||
**Во-первых**, существующие протоколы различаются подходом к утилизации собственно протокола HTTP:
|
||||
* либо клиент-серверное взаимодействие опирается на описанные в стандарте HTTP возможности (точнее было бы сказать, «стандартах HTTP», поскольку функциональность протокола описана во множестве разных RFC);
|
||||
* либо HTTP утилизируется как транспорт, и поверх него выстроен дополнительный уровень абстракции (т.е. возможности HTTP, такие как номенклатура ошибок или заголовков, сознательно редуцируются до минимального уровня, а вся мета-информация переносится на уровень вышестоящего протокола).
|
||||
|
||||
К первой категории относятся API, которые принято обозначать словом «REST» или «RESTful». а ко второй — все виды RPC, а также прикладные протоколы типа SSH.
|
||||
|
||||
Во-вторых, реализации HTTP API опираются на разные форматы передаваемых данных:
|
||||
* REST API и некоторые RPC (JSON-RPC, GraphQL) полагаются в основном на формат JSON (опционально дополненный передачей бинарных файлов);
|
||||
* GRPC, а также Apache Avro и другие специализированные протоколы полагаются на бинарные форматы (такие как Protocol Buffers или FlatBuffers);
|
||||
* наконец, некоторые RPC-протоколы (SOAP, XML-RPC) используют для передачи данных формат XML (что на сегодня является скорее устаревшей технологией).
|
||||
|
||||
Все перечисленные технологии оперируют существенно разными парадигмами — и вызывают естественным образом большое количество холиваров — хотя на момент написания этой книги можно констатировать, что для API общего назначения выбор практически сводится к триаде «REST API (фактически, JSON over HTTP) против GRPC против GraphQL».
|
||||
|
||||
HTTP API будет посвящён раздел IV; мы также отдельно и подробно рассмотрим концепцию «REST API», поскольку, в отличие от GRPC и GraphQL, она является более гибкой и низкоуровневой — но и приводит к большему непониманию по той же причине.
|
||||
|
||||
#### SDK
|
||||
|
||||
Понятие SDK, вообще говоря, вовсе не относится к API: это просто термин для некоторого набора программных инструментов. Однако, как и за «REST», за ним закрепилось некоторое определённое толкование — как клиентского фреймворка для работы с некоторым API. Это может быть как обёртка над клиент-серверным API, так и UI-библиотека в рамках какой-то платформы. Существенным отличием от вышеперечисленных API является то, что «SDK» реализован для какого-то конкретного языка программирования, и его целью является как раз превращение абстрактного набора методов (клиент-серверного API или API операционной системы) в конкретные структуры, разработанные для конкретного языка программирования и конкретной платформы.
|
||||
|
||||
В отличие от клиент-серверных API, обобщить такие SDK не представляется возможным, т.к. каждый из них написан под конкретное сочетание язык программирования-платформа. Из интероперабельных технологий в мире SDK можно привести в пример разве что React / React Native.
|
||||
|
||||
Тем не менее, SDK обладают общностью *на уровне задач*, которые они решают (см. выше), и именно этому (решению проблем трансляции и предоставления UI-компонент) будет посвящён раздел V настоящей книги.
|
@ -1,13 +1,17 @@
|
||||
### [Обратная совместимость][intro-back-compat]
|
||||
### [Критерии качества API][intro-api-quality]
|
||||
|
||||
Обратная совместимость — это некоторая *временна́я* характеристика качества вашего API. Именно необходимость поддержания обратной совместимости отличает разработку API от разработки программного обеспечения вообще.
|
||||
Прежде чем излагать рекомендации, нам следует определиться с тем, что мы считаем «хорошим» API, и какую пользу мы получаем от того, что наш API «хороший».
|
||||
|
||||
Разумеется, обратная совместимость не абсолютна. В некоторых предметных областях выпуск новых обратно несовместимых версий API является вполне рутинной процедурой. Тем не менее, каждый раз, когда выпускается новая обратно несовместимая версия API, всем разработчикам приходится инвестировать какое-то ненулевое количество усилий, чтобы адаптировать свой код к новой версии. В этом плане выпуск новых версий API является некоторого рода «налогом» на потребителей — им нужно тратить вполне осязаемые деньги только для того, чтобы их продукт продолжал работать.
|
||||
Начнём со второго вопроса. Очевидно, «хорошесть» API определяется в первую очередь тем, насколько он помогает разработчикам решать стоящие перед ними задачи. (Можно резонно возразить, что решение задач, стоящих перед разработчиками, не обязательно влечёт за собой выполнение целей, которые мы ставим перед собой, предлагая разработчикам API. Однако манипуляция общественным мнением не входит в область интересов автора этой книги: здесь и далее предполагается, что API существует в первую очередь для того, чтобы разработчики решали с его помощью свои задачи, а не ради каких-то завуалированных целей).
|
||||
|
||||
Конечно, крупные компании с прочным положением на рынке могут позволить себе такой налог взимать. Более того, они могут вводить какие-то санкции за отказ от перехода на новые версии API, вплоть до отключения приложений.
|
||||
Как же дизайн API может помочь разработчику? Очень просто: API должен решать задачи *максимально удобно и понятно*. Путь разработчика от формулирования своей задачи до написания работающего кода должен быть максимально коротким. Это, в том числе, означает, что:
|
||||
|
||||
С нашей точки зрения, подобное поведение ничем не может быть оправдано. Избегайте скрытых налогов на своих пользователей. Если вы можете не ломать обратную совместимость — не ломайте её.
|
||||
* из структуры вашего API должно быть максимально очевидно, как решить ту или иную задачу; в идеале разработчику должно быть достаточно одного взгляда на документацию, чтобы понять, с помощью каких сущностей следует решать поставленную задачу;
|
||||
* API должен быть читаемым: в идеале разработчик, просто глядя в номенклатуру методов, сразу пишет правильный код, не углубляясь в детали (особенно — детали реализации!); немаловажно уточнить, что из интерфейсов объектов должно быть понятно не только решение задачи, но и возможные ошибки и исключения;
|
||||
* API должен быть консистентен: при разработке новой функциональности, т.е. при обращении к каким-то незнакомым сущностям в API, разработчик может действовать по аналогии с уже известными ему концепциями API, и его код будет работать.
|
||||
|
||||
Да, безусловно, поддержка старых версий API — это тоже своего рода налог. Технологии меняются, и, как бы хорошо ни был спроектирован ваш API, всего предусмотреть невозможно. В какой-то момент ценой поддержки старых версий становится невозможность предоставлять новую функциональность и поддерживать новые платформы, и выпустить новую версию всё равно придётся. Однако вы по крайней мере сможете убедить своих потребителей в необходимости перехода.
|
||||
Однако статическое удобство и понятность API — это простая часть. В конце концов, никто не стремится специально сделать API нелогичным и нечитаемым — всегда при разработке мы начинаем с каких-то понятных базовых концепций. При минимальном опыте проектирования сложно сделать ядро API, не удовлетворяющее критериям очевидности, читаемости и консистентности.
|
||||
|
||||
Более подробно о жизненном цикле API и политиках выпуска новых версий будет рассказано в разделе II.
|
||||
Проблемы возникают, когда мы начинаем API развивать. Добавление новой функциональности рано или поздно приводит к тому, что некогда простой и понятный API становится наслоением разных концепций, а попытки сохранить обратную совместимость приводят к нелогичным, неочевидным и попросту плохим решениям. Отчасти это связано так же и с тем, что невозможно обладать полным знанием о будущем: ваше понимание о «правильном» API тоже будет меняться со временем, как в объективной части (какие задачи и каким образом решает API), так и в субъективной — что такое очевидность, читабельность и консистентность для вашего API.
|
||||
|
||||
Принципы, которые мы будем излагать ниже, во многом ориентированы именно на то, чтобы API правильно развивался во времени и не превращался в нагромождение разнородных неконсистентных интерфейсов. Важно понимать, что такой подход тоже не бесплатен: необходимость держать в голове варианты развития событий и закладывать возможность изменений в API означает избыточность интерфейсов и возможно излишнее абстрагирование. И то, и другое, помимо прочего, усложняет и работу программиста, пользующегося вашим API. **Закладывание перспектив «на будущее» имеет смысл, только если это будущее у API есть, иначе это попросту оверинжиниринг**.
|
||||
|
@ -1,14 +1,21 @@
|
||||
### [О версионировании][intro-versioning]
|
||||
|
||||
Здесь и далее мы будем придерживаться принципов версионирования [semver](https://semver.org/).
|
||||
|
||||
1. Версия API задаётся тремя цифрами вида `1.2.3`.
|
||||
2. Первая цифра (мажорная версия) увеличивается при обратно несовместимых изменениях в API.
|
||||
3. Вторая цифра (минорная версия) увеличивается при добавлении новой функциональности с сохранением обратной совместимости.
|
||||
4. Третья цифра (патч) увеличивается при выпуске новых версий, содержащих только исправление ошибок.
|
||||
|
||||
Выражения «мажорная версия API» и «версия API, содержащая обратно несовместимые изменения функциональности» тем самым следует считать эквивалентными.
|
||||
|
||||
Обычно (но не обязательно) устанавливается, что на последнюю стабильную версию API можно сослаться как по полной версии (`1.2.3`), так и по усечённой (`1.2` или просто `1`). Некоторые системы поддерживают и более сложные схемы указания подключаемой версии (например, `^1.2.3` читается как «подключить последнюю стабильную версию, обратно совместимую с версией `1.2.3`) или дополнительные шорткаты (например `1.2-beta` для подключения бета-версии API семейства `1.2`). В настоящей книге мы будем в основном использовать обозначения вида `v1` (`v2`, `v3` и так далее) для обозначения последнего стабильного релиза API семейства `1.x.x`.
|
||||
|
||||
Более подробно о смысле и политиках такого версионирования читайте в главе [«Постановка проблемы обратной совместимости»](#back-compat-statement).
|
||||
### [API-first подход][intro-api-first-approach]
|
||||
|
||||
На сегодняшний день всё больше и больше IT-компаний понимают и принимают важность концепции «API-first», т.е. парадигмы разработки ПО, в которой главной составляющей является разработка API.
|
||||
|
||||
Следует, однако, различать API-first подход в продуктовом и техническом смысле.
|
||||
|
||||
Первое означает, что при разработке некоторого сервиса сначала как первый (и иногда единственный) шаг разрабатывается API к нему, и мы обсудим этот подход в разделе «API как продукт».
|
||||
|
||||
Если же мы говорим об API-first подходе в техническом смысле, то мы имеем в виду следующее: **контракт, т.е. обязательство связывать программные контексты, предшествует реализации и определяет её**. Конкретнее, речь идёт о двух принципах:
|
||||
* контракт разрабатывается и фиксируется в виде спецификации до того, как функциональность непосредственно реализована;
|
||||
* если обнаруживается несоответствие контракта и его имплементации, изменения вносятся в имплементацию, а не в контракт.
|
||||
|
||||
Здесь под спецификацией мы понимаем формальное машиночитаемое описание контракта на одном из языков определения интерфейсов (Interface Definition Language, IDL) — например, в виде Swagger/OpenAPI спецификации или .proto-файла.
|
||||
|
||||
Оба вышеуказанных принципа фактически утверждают приоритет интересов партнёра-разработчика API:
|
||||
* первый принцип позволяет партнёру разрабатывать код по формальной спецификации, не требуя согласования с провайдером API;
|
||||
* появляется возможность использовать генерацию кода по спецификации, что может существенно упрощать и автоматизировать разработку;
|
||||
* партнёрский код может быть написан вообще в отсутствие доступа к API;
|
||||
* второй принцип позволяет не требовать изменений в коде партнёра, если обнаружен ошибка в реализации API.
|
||||
|
||||
Таким образом, API-first подход — это некоторая гарантия для ваших потребителей. Но, как легко заметить, работает эта гарантия только в условиях качественного дизайна API: если в фазе разработки спецификации были допущены неисправимые ошибки, то второй принцип придётся нарушить.
|
||||
|
@ -1,51 +1,13 @@
|
||||
### [Условные обозначения и терминология][intro-terms-notation]
|
||||
### [Обратная совместимость][intro-back-compat]
|
||||
|
||||
В мире разработки программного обеспечения существует множество различных парадигм разработки, адепты которых зачастую настроены весьма воинственно по отношению к адептам других парадигм. Поэтому при написании этой книги мы намеренно избегали слов «метод», «объект», «функция» и так далее, используя нейтральный термин «сущность», под которым понимается некоторая атомарная единица функциональности: класс, метод, объект, монада, прототип (нужное подчеркнуть).
|
||||
Обратная совместимость — это некоторая *временна́я* характеристика качества вашего API. Именно необходимость поддержания обратной совместимости отличает разработку API от разработки программного обеспечения вообще.
|
||||
|
||||
Для составных частей сущности, к сожалению, достаточно нейтрального термина нам придумать не удалось, поэтому мы используем слова «поля» и «методы».
|
||||
Разумеется, обратная совместимость не абсолютна. В некоторых предметных областях выпуск новых обратно несовместимых версий API является вполне рутинной процедурой. Тем не менее, каждый раз, когда выпускается новая обратно несовместимая версия API, всем разработчикам приходится инвестировать какое-то ненулевое количество усилий, чтобы адаптировать свой код к новой версии. В этом плане выпуск новых версий API является некоторого рода «налогом» на потребителей — им нужно тратить вполне осязаемые деньги только для того, чтобы их продукт продолжал работать.
|
||||
|
||||
Большинство примеров API в общих разделах будут даны в виде JSON-over-HTTP-эндпойтов. Это некоторая условность, которая помогает описать концепции, как нам кажется, максимально понятно. Вместо `GET /v1/orders` вполне может быть вызов метода `orders.get()`, локальный или удалённый; вместо JSON может быть любой другой формат данных. Смысл утверждений от этого не меняется.
|
||||
Конечно, крупные компании с прочным положением на рынке могут позволить себе такой налог взимать. Более того, они могут вводить какие-то санкции за отказ от перехода на новые версии API, вплоть до отключения приложений.
|
||||
|
||||
Рассмотрим следующую запись:
|
||||
```
|
||||
// Описание метода
|
||||
POST /v1/bucket/{id}/some-resource⮠
|
||||
/{resource_id}
|
||||
X-Idempotency-Token: <токен идемпотентности>
|
||||
{
|
||||
…
|
||||
// Это однострочный комментарий
|
||||
"some_parameter": "value",
|
||||
…
|
||||
}
|
||||
→ 404 Not Found
|
||||
Cache-Control: no-cache
|
||||
{
|
||||
/* А это многострочный
|
||||
комментарий */
|
||||
"error_message":
|
||||
"Длинное сообщение,⮠
|
||||
которое приходится⮠
|
||||
разбивать на строки"
|
||||
}
|
||||
```
|
||||
С нашей точки зрения, подобное поведение ничем не может быть оправдано. Избегайте скрытых налогов на своих пользователей. Если вы можете не ломать обратную совместимость — не ломайте её.
|
||||
|
||||
Её следует читать так:
|
||||
* клиент выполняет POST-запрос к ресурсу `/v1/bucket/{id}/some-resource`, где `{id}` заменяется на некоторый идентификатор `bucket`-а (при отсутствии уточнений подстановки вида `{something}` следует относить к ближайшему термину слева);
|
||||
* запрос сопровождается (помимо стандартных заголовков, которые мы опускаем) дополнительным заголовком `X-Idempotency-Token`;
|
||||
* фразы в угловых скобках (`<токен идемпотентности>`) описывают семантику значения сущности (поля, заголовка, параметра);
|
||||
* в качестве тела запроса передаётся JSON, содержащий поле `some_parameter` со значением `value` и ещё какие-то поля, которые для краткости опущены (что показано многоточием);
|
||||
* в ответ (индицируется стрелкой `→`) сервер возвращает статус `404 Not Found`; статус может быть опущен (отсутствие статуса следует трактовать как `200 OK`);
|
||||
* в ответе также могут находиться дополнительные заголовки, на которые мы обращаем внимание;
|
||||
* телом ответа является JSON, состоящий из единственного поля `error_message`; отсутствие значения поля означает, что его значением является именно то, что в этом поле и ожидается — в данном случае какое-то сообщение об ошибке
|
||||
* если какой-то токен оказывается слишком длинным, мы будем переносить его на следующую строку, используя символ `⮠` для индикации переноса.
|
||||
Да, безусловно, поддержка старых версий API — это тоже своего рода налог. Технологии меняются, и, как бы хорошо ни был спроектирован ваш API, всего предусмотреть невозможно. В какой-то момент ценой поддержки старых версий становится невозможность предоставлять новую функциональность и поддерживать новые платформы, и выпустить новую версию всё равно придётся. Однако вы по крайней мере сможете убедить своих потребителей в необходимости перехода.
|
||||
|
||||
Здесь термин «клиент» означает «приложение, установленное на устройстве пользователя, использующее рассматриваемый API». Приложение может быть как нативным, так и веб-приложением. Термины «агент» и «юзер-агент» являются синонимами термина «клиент».
|
||||
|
||||
Ответ (частично или целиком) и тело запроса могут быть опущены, если в контексте обсуждаемого вопроса их содержание не имеет значения.
|
||||
|
||||
Возможна сокращённая запись вида: `POST /some-resource` `{…,"some_parameter",…}` → `{ "operation_id" }`; тело запроса и/или ответа может опускаться аналогично полной записи.
|
||||
|
||||
Чтобы сослаться на это описание будут использоваться выражения типа «метод `POST /v1/bucket/{id}/some-resource`» или, для простоты, «метод `some-resource`» или «метод `bucket/some-resource`» (если никаких других `some-resource` в контексте главы не упоминается и перепутать не с чем).
|
||||
|
||||
Помимо HTTP API-нотации мы будем активно использовать C-подобный псевдокод — точнее будет сказать, JavaScript или Python-подобный, поскольку нотации типов мы будем опускать. Мы предполагаем, что подобного рода императивные конструкции достаточно читабельны, и не будем здесь описывать грамматику подробно.
|
||||
Более подробно о жизненном цикле API и политиках выпуска новых версий будет рассказано в разделе II.
|
14
src/ru/clean-copy/01-Введение/07.md
Normal file
14
src/ru/clean-copy/01-Введение/07.md
Normal file
@ -0,0 +1,14 @@
|
||||
### [О версионировании][intro-versioning]
|
||||
|
||||
Здесь и далее мы будем придерживаться принципов версионирования [semver](https://semver.org/).
|
||||
|
||||
1. Версия API задаётся тремя цифрами вида `1.2.3`.
|
||||
2. Первая цифра (мажорная версия) увеличивается при обратно несовместимых изменениях в API.
|
||||
3. Вторая цифра (минорная версия) увеличивается при добавлении новой функциональности с сохранением обратной совместимости.
|
||||
4. Третья цифра (патч) увеличивается при выпуске новых версий, содержащих только исправление ошибок.
|
||||
|
||||
Выражения «мажорная версия API» и «версия API, содержащая обратно несовместимые изменения функциональности» тем самым следует считать эквивалентными.
|
||||
|
||||
Обычно (но не обязательно) устанавливается, что на последнюю стабильную версию API можно сослаться как по полной версии (`1.2.3`), так и по усечённой (`1.2` или просто `1`). Некоторые системы поддерживают и более сложные схемы указания подключаемой версии (например, `^1.2.3` читается как «подключить последнюю стабильную версию, обратно совместимую с версией `1.2.3`) или дополнительные шорткаты (например `1.2-beta` для подключения бета-версии API семейства `1.2`). В настоящей книге мы будем в основном использовать обозначения вида `v1` (`v2`, `v3` и так далее) для обозначения последнего стабильного релиза API семейства `1.x.x`.
|
||||
|
||||
Более подробно о смысле и политиках такого версионирования читайте в главе [«Постановка проблемы обратной совместимости»](#back-compat-statement).
|
51
src/ru/clean-copy/01-Введение/08.md
Normal file
51
src/ru/clean-copy/01-Введение/08.md
Normal file
@ -0,0 +1,51 @@
|
||||
### [Условные обозначения и терминология][intro-terms-notation]
|
||||
|
||||
В мире разработки программного обеспечения существует множество различных парадигм разработки, адепты которых зачастую настроены весьма воинственно по отношению к адептам других парадигм. Поэтому при написании этой книги мы намеренно избегали слов «метод», «объект», «функция» и так далее, используя нейтральный термин «сущность», под которым понимается некоторая атомарная единица функциональности: класс, метод, объект, монада, прототип (нужное подчеркнуть).
|
||||
|
||||
Для составных частей сущности, к сожалению, достаточно нейтрального термина нам придумать не удалось, поэтому мы используем слова «поля» и «методы».
|
||||
|
||||
Большинство примеров API в общих разделах будут даны в виде JSON-over-HTTP-эндпойтов. Это некоторая условность, которая помогает описать концепции, как нам кажется, максимально понятно. Вместо `GET /v1/orders` вполне может быть вызов метода `orders.get()`, локальный или удалённый; вместо JSON может быть любой другой формат данных. Смысл утверждений от этого не меняется.
|
||||
|
||||
Рассмотрим следующую запись:
|
||||
```
|
||||
// Описание метода
|
||||
POST /v1/bucket/{id}/some-resource⮠
|
||||
/{resource_id}
|
||||
X-Idempotency-Token: <токен идемпотентности>
|
||||
{
|
||||
…
|
||||
// Это однострочный комментарий
|
||||
"some_parameter": "value",
|
||||
…
|
||||
}
|
||||
→ 404 Not Found
|
||||
Cache-Control: no-cache
|
||||
{
|
||||
/* А это многострочный
|
||||
комментарий */
|
||||
"error_message":
|
||||
"Длинное сообщение,⮠
|
||||
которое приходится⮠
|
||||
разбивать на строки"
|
||||
}
|
||||
```
|
||||
|
||||
Её следует читать так:
|
||||
* клиент выполняет POST-запрос к ресурсу `/v1/bucket/{id}/some-resource`, где `{id}` заменяется на некоторый идентификатор `bucket`-а (при отсутствии уточнений подстановки вида `{something}` следует относить к ближайшему термину слева);
|
||||
* запрос сопровождается (помимо стандартных заголовков, которые мы опускаем) дополнительным заголовком `X-Idempotency-Token`;
|
||||
* фразы в угловых скобках (`<токен идемпотентности>`) описывают семантику значения сущности (поля, заголовка, параметра);
|
||||
* в качестве тела запроса передаётся JSON, содержащий поле `some_parameter` со значением `value` и ещё какие-то поля, которые для краткости опущены (что показано многоточием);
|
||||
* в ответ (индицируется стрелкой `→`) сервер возвращает статус `404 Not Found`; статус может быть опущен (отсутствие статуса следует трактовать как `200 OK`);
|
||||
* в ответе также могут находиться дополнительные заголовки, на которые мы обращаем внимание;
|
||||
* телом ответа является JSON, состоящий из единственного поля `error_message`; отсутствие значения поля означает, что его значением является именно то, что в этом поле и ожидается — в данном случае какое-то сообщение об ошибке
|
||||
* если какой-то токен оказывается слишком длинным, мы будем переносить его на следующую строку, используя символ `⮠` для индикации переноса.
|
||||
|
||||
Здесь термин «клиент» означает «приложение, установленное на устройстве пользователя, использующее рассматриваемый API». Приложение может быть как нативным, так и веб-приложением. Термины «агент» и «юзер-агент» являются синонимами термина «клиент».
|
||||
|
||||
Ответ (частично или целиком) и тело запроса могут быть опущены, если в контексте обсуждаемого вопроса их содержание не имеет значения.
|
||||
|
||||
Возможна сокращённая запись вида: `POST /some-resource` `{…,"some_parameter",…}` → `{ "operation_id" }`; тело запроса и/или ответа может опускаться аналогично полной записи.
|
||||
|
||||
Чтобы сослаться на это описание будут использоваться выражения типа «метод `POST /v1/bucket/{id}/some-resource`» или, для простоты, «метод `some-resource`» или «метод `bucket/some-resource`» (если никаких других `some-resource` в контексте главы не упоминается и перепутать не с чем).
|
||||
|
||||
Помимо HTTP API-нотации мы будем активно использовать C-подобный псевдокод — точнее будет сказать, JavaScript или Python-подобный, поскольку нотации типов мы будем опускать. Мы предполагаем, что подобного рода императивные конструкции достаточно читабельны, и не будем здесь описывать грамматику подробно.
|
@ -1,15 +0,0 @@
|
||||
### Об этой книге
|
||||
|
||||
Книга, которую вы держите в руках, посвящена разработке API как отдельной инженерной задаче. Хотя многое из того, о чём мы будем говорить, применимо к написанию любых программ, наша цель состояла прежде всего в описании тех проблем и подходов к их решению, которые характерны именно для разработки API.
|
||||
|
||||
Мы ожидаем, что читатель обладает навыками разработки программного обеспечения, и не даём подробных определений и объяснений в отношении понятий, которыми разработчик должен по нашему мнению владеть. Без такого рода навыков читать последнюю главу вам будет достаточно некомфортно (а остальные главы — скорее всего, невозможно) — за что мы искренне просим прощения, но не видим другого способа написать эту книгу, не раздув её объём ещё в три раза.
|
||||
|
||||
Настоящая книга состоит из введения и шести больших разделов. Первые два из них («Проектирование API» и «Обратная совместимость») являются полностью абстрактными и не привязанными ни к каким конкретным технологиям — мы рассчитываем, что они окажутся полезными тем читателям, которые хотят выстроить системное понимание того, что такое архитектура API и как разрабатывать сложные иерархии интерфейсов. Предложенный подход, как мы надеемся, помогает выстроить API сверху вниз, от сырой идеи до конкретной реализации.
|
||||
|
||||
Третий раздел («Паттерны проектирования API») является более практическим и содержит описания типичных проблем, возникающих при разработке API, и предлагает типовые решения для них.
|
||||
|
||||
Четвёртый и пятый раздел посвящены вполне конкретным технологиям — разработке HTTP API («REST») и SDK (в основном речь пойдёт о библиотеках визуальных компонент).
|
||||
|
||||
Наконец, шестой раздел, наименее технический из всех, посвящён API как продукту и фокусируется на всех не-разработческих аспектах существования API: изучение рынка, позиционирование сервиса, взаимодействие с потребителями, KPI команды и так далее. Мы настаиваем здесь, что последний раздел одинаково важен и для менеджеров, и для программистов, поскольку технические продукты можно развивать только в тесном взаимодействии продуктовой и технической команд.
|
||||
|
||||
На этом переходим к делу.
|
@ -1,36 +0,0 @@
|
||||
### Обзор существующих решений в области разработки API
|
||||
|
||||
Цель первых трёх разделов настоящей книги — поговорить о дизайне API вне привязки к какой-либо конкретной технологии. Изложенные нами принципы равно применимы как к веб-сервисам, так и, например, к интерфейсам операционных систем.
|
||||
|
||||
Тем не менее, два больших сценария использования явно доминируют, когда мы говорим о разработке API:
|
||||
* разработка клиент-серверных приложений;
|
||||
* разработка клиентских SDK.
|
||||
|
||||
В первом случае мы говорим практически исключительно об API, работающих поверх протокола HTTP. В настоящий момент клиент-серверное взаимодействие, не опирающееся на HTTP, можно встретить разве что в протоколе WebSocket (хотя и он может быть использован совместно с HTTP, что часто и происходит), а также в различных форматах потокового вещания и других узкоспециализированных интерфейсах.
|
||||
|
||||
#### HTTP API
|
||||
|
||||
Несмотря на кажущуюся гомогенность технологии ввиду использования одного протокола прикладного уровня, в действительности же наблюдается значительное разнообразие подходов к имплементации HTTP API.
|
||||
|
||||
**Во-первых**, существующие протоколы различаются подходом к утилизации собственно протокола HTTP:
|
||||
* либо клиент-серверное взаимодействие опирается на описанные в стандарте HTTP возможности (точнее было бы сказать, «стандартах HTTP», поскольку функциональность протокола описана во множестве разных RFC);
|
||||
* либо HTTP утилизируется как транспорт, и поверх него выстроен дополнительный уровень абстракции (т.е. возможности HTTP, такие как номенклатура ошибок или заголовков, сознательно редуцируются до минимального уровня, а вся мета-информация переносится на уровень вышестоящего протокола).
|
||||
|
||||
К первой категории относятся API, которые принято обозначать словом «REST» или «RESTful». а ко второй — все виды RPC, а также прикладные протоколы типа FTP или SSH.
|
||||
|
||||
Во-вторых, реализации HTTP API опираются на разные форматы передаваемых данных:
|
||||
* REST API и некоторые RPC (JSON-RPC, GraphQL) полагаются в основном на формат JSON (опционально дополненный передачей бинарных файлов);
|
||||
* GRPC, а также Apache Avro и другие специализированные протоколы полагаются на бинарные форматы (такие как Protocol Buffers или FlattBuffers);
|
||||
* наконец, некоторые RPC-протоколы (SOAP, XML-RPC) используют для передачи данных формат XML (что на сегодня является скорее устаревшей технологией).
|
||||
|
||||
Все перечисленные технологии оперируют существенно разными парадигмами — и вызывают естественным образом большое количество холиваров — хотя на момент написания этой книги можно констатировать, что для API общего назначения выбор практически сводится к триаде «REST API (фактически, JSON over HTTP) против GRPC против GraphQL».
|
||||
|
||||
HTTP API будет посвящён раздел IV; мы также отдельно и подробно рассмотрим концепцию «REST API», поскольку, в отличие от GRPC и GraphQL, она является более гибкой и низкоуровневой — но и приводит к большему непониманию по той же причине.
|
||||
|
||||
#### SDK
|
||||
|
||||
Понятие SDK, вообще говоря, вовсе не относится к API: это просто термин для некоторого набора программных инструментов. Однако, как и за «REST», за ним закрепилось некоторое определённое толкование — как клиентского фреймворка для работы с некоторым API. Это может быть как обёртка над клиент-серверным API, так и UI-библиотека в рамках какой-то платформы. Существенным отличием от вышеперечисленных API является то, что «SDK» реализован для какого-то конкретного языка программирования, и его целью является как раз превращение абстрактного набора методов (клиент-серверного API или API операционной системы) в конкретные структуры, разработанные для конкретного языка программирования и конкретной платформы.
|
||||
|
||||
В отличие от клиент-серверных API, обобщить такие SDK не представляется возможным, т.к. каждый из них написан под конкретное сочетание язык программирования-платформа. Из интероперабельных технологий в мире SDK можно привести в пример разве что React / React Native.
|
||||
|
||||
Тем не менее, SDK обладают общностью *на уровне задач*, которые они решают (см. выше), и именно этому (решению проблем трансляции и предоставления UI-компонент) будет посвящён раздел V настоящей книги.
|
@ -1,19 +0,0 @@
|
||||
### API-first подход
|
||||
|
||||
На сегодняшний день всё больше и больше IT-компаний понимают и принимают важность концепции «API-first», т.е. парадигмы разработки ПО, в которой главной составляющей является разработка API.
|
||||
|
||||
Следует, однако, различать API-first подход в продуктовом и техническом смысле. Первое означает, что при разработке некоторого сервиса сначала как первый (и иногда единственный) шаг разрабатывается API к нему, и мы обсудим этот подход в разделе «API как продукт».
|
||||
|
||||
Если же мы говорим об API-first подходе в техническом смысле, то мы имеем в виду следующее: **контракт, т.е. обязательство связывать программные контексты, предшествует реализации и определяет её**. Конкретнее, речь идёт о двух принципах:
|
||||
* контракт разрабатывается и фиксируется в виде спецификации до того, как функциональность непосредственно реализована;
|
||||
* если обнаруживается несоответствие контракта и его имплементации, изменения вносятся в имплементацию, а не в контракт.
|
||||
|
||||
Здесь под спецификацией мы понимаем формальное машиночитаемое описание контракта на одном из языков определения интерфейсов (Interface Definition Language, IDL) — например, в виде Swagger/OpenAPI спецификации или .proto-файла.
|
||||
|
||||
Оба вышеуказанных принципа фактически утверждают приоритет интересов партнёра-разработчика API:
|
||||
* первый принцип позволяет партнёру разрабатывать код по формальной спецификации, не требуя согласования с провайдером API;
|
||||
* появляется возможность использовать генерацию кода по спецификации, что может существенно упрощать и автоматизировать разработку;
|
||||
* партнёрский код может быть написан вообще в отсутствие доступа к API;
|
||||
* второй принцип позволяет не требовать изменений в коде партнёра, если обнаружен ошибка в реализации API.
|
||||
|
||||
Таким образом, API-first подход — это некоторая гарантия для ваших потребителей. Но, как легко заметить, работает эта гарантия только в условиях качественного дизайна API: если в фазе разработки спецификации были допущены неисправимые ошибки, то второй принцип придётся нарушить.
|
@ -3,7 +3,7 @@
|
||||
"author": "Сергей Константинов",
|
||||
"chapter": "Глава",
|
||||
"toc": "Содержание",
|
||||
"description": "Разработка API — особый навык: API является как мультипликатором ваших возможностей, так и мультипликатором ваших ошибок. Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. В первом разделе мы поговорим о проектировании API: как грамотно выстроить архитектуру, от крупноблочного планирования до конечных интерфейсов. Второй раздел посвящён развитию существующих API с сохранением обратной совместимости. Наконец, в третьем разделе мы поговорим об API как о продукте.",
|
||||
"description": "Разработка API — особый навык: API является как мультипликатором ваших возможностей, так и мультипликатором ваших ошибок. Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. Книга состоит из шести разделов, посвящённых проектированию API, паттернам дизайна API, поддержанию обратной совместимости, HTTP API и REST, SDK и UI-библиотекам, продуктовому управлению API.",
|
||||
"locale": "ru_RU",
|
||||
"file": "API",
|
||||
"landingFile": "index.ru.html",
|
||||
@ -63,7 +63,7 @@
|
||||
"githubString": "github.com/twirl/The-API-Book",
|
||||
"twitterHref": "https://twitter.com/blogovodoved",
|
||||
"kindleHref": "https://www.amazon.com/gp/product/B09RHH44S5/ref=dbs_a_def_rwt_hsch_vapi_tkin_p1_i0",
|
||||
"kindleTag": "buy Kindle version",
|
||||
"kindleTag": "buy Kindle version [1st edition]",
|
||||
"mediumHref": "https://twirl.medium.com/",
|
||||
"mediumTag": "Medium",
|
||||
"habrHref": "https://habr.com/ru/users/forgotten/",
|
||||
@ -75,7 +75,13 @@
|
||||
"pageTitle": "Титульный лист",
|
||||
"contents": [
|
||||
"<p>«API-first» подход — одна из самых горячих горячих тем в разработке программного обеспечения в наше время. Многие компании начали понимать, что API выступает мультипликатором их возможностей — но также умножает и допущенные ошибки.</p>",
|
||||
"<p>Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. В первом разделе мы поговорим о проектировании API: как грамотно выстроить архитектуру, от крупноблочного планирования до конечных интерфейсов. Второй раздел посвящён развитию существующих API с сохранением обратной совместимости. Наконец, в третьем разделе мы поговорим об API как о продукте.</p>",
|
||||
"<p>Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. Книга состоит из шести разделов, посвящённых:</p>",
|
||||
"<ul><li>проектированию API,</li>",
|
||||
"<li>паттернам дизайна API,</li>",
|
||||
"<li>поддержанию обратной совместимости,</li>",
|
||||
"<li>HTTP API и REST,</li>",
|
||||
"<li>SDK и UI-библиотекам,</li>",
|
||||
"<li>продуктовому управлению API.</li></ul>",
|
||||
"<p class=\"text-align-left\">Иллюстрации и вдохновение: Maria Konstantinova · <a href=\"https://www.instagram.com/art.mari.ka/\">art.mari.ka</a>.</p>",
|
||||
"<img class=\"cc-by-nc-img\" alt=\"Creative Commons «Attribution-NonCommercial» Logo\" src=\"https://i.creativecommons.org/l/by-nc/4.0/88x31.png\"/>",
|
||||
"<p class=\"cc-by-nc\">Это произведение доступно по <a href=\"http://creativecommons.org/licenses/by-nc/4.0/\">лицензии Creative Commons «Attribution-NonCommercial» («Атрибуция — Некоммерческое использование») 4.0 Всемирная</a>.</p>"
|
||||
@ -91,7 +97,13 @@
|
||||
"support": ["patreon"],
|
||||
"content": [
|
||||
"<p>«API-first» подход — одна из самых горячих горячих тем в разработке программного обеспечения в наше время. Многие компании начали понимать, что API выступает мультипликатором их возможностей — но также умножает и допущенные ошибки.</p>",
|
||||
"<p>Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. В первом разделе мы поговорим о проектировании API: как грамотно выстроить архитектуру, от крупноблочного планирования до конечных интерфейсов. Второй раздел посвящён развитию существующих API с сохранением обратной совместимости. Наконец, в третьем разделе мы поговорим об API как о продукте.</p>",
|
||||
"<p>Эта книга написана для того, чтобы поделиться опытом и изложить лучшие практики разработки API. Книга состоит из шести разделов, посвящённых:</p>",
|
||||
"<ul><li>— проектированию API,</li>",
|
||||
"<li>— паттернам дизайна API,</li>",
|
||||
"<li>— поддержанию обратной совместимости,</li>",
|
||||
"<li>— HTTP API и REST,</li>",
|
||||
"<li>— SDK и UI-библиотекам,</li>",
|
||||
"<li>— продуктовому управлению API.</li></ul>",
|
||||
"<p>Иллюстрации и вдохновение: Maria Konstantinova · <a href=\"https://www.instagram.com/art.mari.ka/\">art.mari.ka</a>.</p>"
|
||||
],
|
||||
"download": "Вы можете скачать книгу «API» в формате",
|
||||
|
Loading…
x
Reference in New Issue
Block a user