1
0
mirror of https://github.com/twirl/The-API-Book.git synced 2025-01-23 17:53:04 +02:00

README updated + style fix

This commit is contained in:
Sergey Konstantinov 2022-01-28 22:48:50 +03:00
parent 3928d1fb73
commit ea9c3d079a
19 changed files with 195 additions and 26 deletions

View File

@ -22,22 +22,15 @@ You might support this work [on Patreon](https://www.patreon.com/yatwirl).
## Current State and the Roadmap
Right now Section I (‘API Design’) is finished. The Section is lacking readable schemes, I'll draw them later.
Right now Section I (‘API Design’) and Section II (‘Backwards Compatibility’) are finished. The Sections are lacking readable schemes, I'll draw them later.
The book will contain two more sections.
* Section II ‘Backwards Compatibility’ will cover growth issues. Major themes are:
* major sources of problems leading to backwards compatibility breach;
* interface decomposing allowing for third-party plugins and switching underlying technologies;
* structuring public and private parts of your API;
* versioning policies;
* common mistakes.
* Section III ‘API as a Product’ will be discussing non-technical issues:
* what for the APIs exist;
* monetizing APIs;
* making sure your understand users' needs and collect proper metrics;
* common practices, including AA issues and fraud problems;
* organizing docs portal;
* open source and community.
Section III ‘API as a Product’ will be discussing non-technical issues
* what for the APIs exist;
* monetizing APIs;
* making sure you understand users' needs and collect proper metrics;
* common practices, including AA issues and fraud problems;
* organizing docs portal;
* open source and community.
I also have more distant plans on adding two more subsections to Section I.
* Section Ia ‘JSON HTTP APIs’:
@ -57,3 +50,6 @@ I am accepting inquiries. Feel free to open issues.
I am NOT accepting pull requests introducing any new content, since I'm willing to be the only author. I would gratefully accept typo fixes, though.
Thanks @tholman for https://github.com/tholman/github-corners
Thanks [Ira Gorelik](https://pixabay.com/users/igorelick-680927/) for the Aqueduct
Thanks [ParaType](https://www.paratype.ru/) for PT Sans and PT Serif
Thanks [Christian Robertson](https://twitter.com/cr64) for Roboto Mono

View File

@ -1,3 +1,81 @@
@font-face {
font-family: local-serif;
src: url(/fonts/PTSerif-Regular.ttf);
}
@font-face {
font-family: local-serif;
src: url(/fonts/PTSerif-Italic.ttf);
font-style: italic;
}
@font-face {
font-family: local-serif;
src: url(/fonts/PTSerif-Italic.ttf);
font-style: oblique;
}
@font-face {
font-family: local-serif;
src: url(/fonts/PTSerif-Bold.ttf);
font-weight: bold;
}
@font-face {
font-family: local-serif;
src: url(/fonts/PTSerif-BoldItalic.ttf);
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: local-serif;
src: url(/fonts/PTSerif-BoldItalic.ttf);
font-weight: bold;
font-style: oblique;
}
@font-face {
font-family: local-sans;
src: url(/fonts/PTSans-Regular.ttf);
}
@font-face {
font-family: local-sans;
src: url(/fonts/PTSans-Bold.ttf);
font-weight: bold;
}
@font-face {
font-family: local-sans;
src: url(/fonts/PTSans-Italic.ttf);
font-style: oblique;
}
@font-face {
font-family: local-sans;
src: url(/fonts/PTSans-Italic.ttf);
font-style: italic;
}
@font-face {
font-family: local-sans;
src: url(/fonts/PTSans-BoldItalic.ttf);
font-style: oblique;
font-weight: bold;
}
@font-face {
font-family: local-sans;
src: url(/fonts/PTSans-BoldItalic.ttf);
font-style: italic;
font-weight: bold;
}
@font-face {
font-family: local-monospace;
src: url(/fonts/RobotoMono-Regular.ttf);
}
html {
width: 100%;
margin: 0;
@ -6,7 +84,7 @@ html {
body,
h6 {
font-family: 'PT Serif';
font-family: local-serif, serif;
font-size: 14pt;
text-align: justify;
}
@ -27,7 +105,7 @@ h6 {
code,
pre {
font-family: Inconsolata, sans-serif;
font-family: local-monospace, sans-serif;
}
code {
@ -77,7 +155,7 @@ h3,
h4,
h5 {
text-align: left;
font-family: 'PT Sans';
font-family: local-sans, sans-serif;
font-weight: bold;
page-break-after: avoid;
}

View File

@ -2,7 +2,7 @@
In previous chapters, we have tried to outline theoretical rules and illustrate them with practical examples. However, understanding the principles of change-proof API design requires practice above all things. An ability to anticipate future growth problems comes from a handful of grave mistakes once made. One cannot foresee everything but can develop certain technical intuition.
So in the following chapters, we will try to probe our study API from the previous Section, testing its robustness from every possible viewpoint, thus carrying out some ‘variational analysis’ of our interfaces. More specifically, we will apply a ‘What If?’ question to every entity, as if we are to provide a possibility to write an alternate implementation of every piece of logic.
So in the following chapters, we will try to probe [our study API](#chapter-12) from the previous Section, testing its robustness from every possible viewpoint, thus carrying out some ‘variational analysis’ of our interfaces. More specifically, we will apply a ‘What If?’ question to every entity, as if we are to provide a possibility to write an alternate implementation of every piece of logic.
**NB**. In our examples, the interfaces will be constructed in a manner allowing for dynamic real-time linking of different entities. In practice, such integrations usually imply writing an ad hoc server-side code in accordance with specific agreements made with specific partners. But for educational purposes, we will pursue more abstract and complicated ways. Dynamic real-time linking is more typical in complex program constructs like operating system APIs or embeddable libraries; giving educational examples based on such sophisticated systems would be too inconvenient.
@ -65,9 +65,10 @@ More specifically, if we talk about changing available order options, we should
2. Add new ‘with-options’ endpoint:
```
PUT /v1/partners/{partnerId}/coffee-machines-with-options
PUT /v1/partners/{partner_id}/coffee-machines-with-options
{
"coffee_machines": [{
"id",
"api_type",
"location",
"supported_recipes",

View File

@ -1,4 +1,4 @@
### Strong coupling and related problems
### Strong Coupling and Related Problems
To demonstrate the strong coupling problematics let us move to *really interesting* things. Let's continue our ‘variation analysis’: what if the partners wish to offer not only the standard beverages but their own unique coffee recipes to end-users? There is a catch in this question: the partner API as we described it in the previous chapter, does not expose the very existence of the partner network to the end-user, and thus describes a simple case. Once we start providing methods to alter the core functionality, not just API extensions, we will soon face next-level problems.

View File

@ -1,4 +1,4 @@
### Weak coupling
### Weak Coupling
In the previous chapter we've demonstrated how breaking strong coupling of components leads to decomposing entities and collapsing their public interfaces down to a reasonable minimum. A mindful reader might have noted that this technique was already used in our API study much earlier in [Chapter 9](#chapter-9) with regards to ‘program’ and ‘program run’ entities. Indeed, we might do it without `program-matcher` endpoint and make it this way:

Binary file not shown.

94
src/fonts/OFL.txt Normal file
View File

@ -0,0 +1,94 @@
Copyright (c) 2010, ParaType Ltd. (http://www.paratype.com/public),
with Reserved Font Names "PT Sans", "PT Serif" and "ParaType".
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

BIN
src/fonts/PTSans-Bold.ttf Normal file

Binary file not shown.

Binary file not shown.

BIN
src/fonts/PTSans-Italic.ttf Normal file

Binary file not shown.

Binary file not shown.

BIN
src/fonts/PTSerif-Bold.ttf Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
src/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

View File

@ -2,9 +2,9 @@
В предыдущих разделах мы старались приводить теоретические правила и иллюстрировать их на практических примерах. Однако понимание принципов проектирования API, устойчивого к изменениям, как ничто другое требует прежде всего практики. Знание о том, куда стоит «постелить соломку» — оно во многом «сын ошибок трудных». Нельзя предусмотреть всего — но можно выработать необходимый уровень технической интуиции.
Поэтому в этом разделе мы поступим следующим образом: возьмём наше модельное API из предыдущего раздела, и проверим его на устойчивость в каждой возможной точке — проведём некоторый «вариационный анализ» наших интерфейсов. Ещё более конкретно — к каждой сущности мы подойдём с вопросом «что, если?» — что, если нам потребуется предоставить партнерам возможность написать свою независимую реализацию этого фрагмента логики.
Поэтому в этом разделе мы поступим следующим образом: возьмём наше [модельное API](#chapter-12) из предыдущего раздела, и проверим его на устойчивость в каждой возможной точке — проведём некоторый «вариационный анализ» наших интерфейсов. Ещё более конкретно — к каждой сущности мы подойдём с вопросом «что, если?» — что, если нам потребуется предоставить партнерам возможность написать свою независимую реализацию этого фрагмента логики.
**NB**: в рассматриваемых нами примерах мы будем выстраивать интерфейсы так, чтобы связывание разных сущностей происходило динамически в реальном времени; на практике такие интеграции будут делаться на стороне сервера путём написания ad hoc кода и формирования конкретных договорённостей с конкретным клиентом, однако мы для целей обучения специально будем идти более сложным и абстрактным путём. Динамическое связывание в реальном времени применимо скорее к сложным программным конструктам типа API операционных систем или встраиваемых библиотек; приводить обучающие примеры на основе систем подобной сложности было бы, однако, чересчур затруднительно.
**NB**. В рассматриваемых нами примерах мы будем выстраивать интерфейсы так, чтобы связывание разных сущностей происходило динамически в реальном времени; на практике такие интеграции будут делаться на стороне сервера путём написания ad hoc кода и формирования конкретных договорённостей с конкретным клиентом, однако мы для целей обучения специально будем идти более сложным и абстрактным путём. Динамическое связывание в реальном времени применимо скорее к сложным программным конструктам типа API операционных систем или встраиваемых библиотек; приводить обучающие примеры на основе систем подобной сложности было бы, однако, чересчур затруднительно.
Начнём с базового интерфейса. Предположим, что мы пока что вообще не раскрывали никакой функциональности помимо поиска предложений и заказа, т.е. мы предоставляем API из двух методов — `POST /offers/search` и `POST /orders`.
@ -64,7 +64,7 @@ PUT /v1/partners/{partnerId}/coffee-machines
2. Добавляем новый метод `with-options`:
```
PUT /v1/partners/{partnerId}/coffee-machines-with-options
PUT /v1/partners/{partner_id}/coffee-machines-with-options
{
"coffee_machines": [{
"id",

View File

@ -23,7 +23,7 @@
Таким образом, наш интерфейс (назовём его `ISearchResult`) — это композиция двух других интерфейсов: `IOrderParameters` (сущности, позволяющей сделать заказ) и `ISearchItemViewParameters` (некоторого абстрактного представления результатов поиска в UI). Подобное разделение должно автоматически подводить нас к ряду вопросов.
1. Каким образом мы будем связывать одно с другим? Очевидно, что эти два суб-интерфейса зависимы: например, отформатированная человекочитаемая цена должна совпадать с машиночитаемой. Это естественным образом подводит нас к концепции абстрагирования форматирования, описанной в [главе 16](#chapter15).
1. Каким образом мы будем связывать одно с другим? Очевидно, что эти два суб-интерфейса зависимы: например, отформатированная человекочитаемая цена должна совпадать с машиночитаемой. Это естественным образом подводит нас к концепции абстрагирования форматирования, описанной в [главе 16](#chapter-16).
2. А что такое, в свою очередь, «абстрактное представление результатов поиска в UI»? Есть ли у нас какие-то другие виды поисков, не является ли `ISearchItemViewParameters` сам наследником какого-либо другого интерфейса или композицией других интерфейсов?