api_recipes 2.10.4 → 3.0.0.beta1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +631 -81
- data/UPGRADING.md +473 -0
- data/exe/api_recipes +6 -0
- data/lib/api_recipes/api.rb +71 -49
- data/lib/api_recipes/cli/upgrade.rb +179 -0
- data/lib/api_recipes/cli.rb +70 -0
- data/lib/api_recipes/configuration.rb +185 -36
- data/lib/api_recipes/endpoint.rb +68 -118
- data/lib/api_recipes/errors.rb +137 -0
- data/lib/api_recipes/internals/compiler.rb +680 -0
- data/lib/api_recipes/internals/context.rb +237 -0
- data/lib/api_recipes/internals/credential.rb +86 -0
- data/lib/api_recipes/internals/declaration.rb +225 -0
- data/lib/api_recipes/internals/definition.rb +179 -0
- data/lib/api_recipes/internals/handles.rb +81 -0
- data/lib/api_recipes/internals/level.rb +192 -0
- data/lib/api_recipes/internals/path_template.rb +131 -0
- data/lib/api_recipes/internals/registry.rb +146 -0
- data/lib/api_recipes/internals/request.rb +285 -0
- data/lib/api_recipes/internals/template.rb +73 -0
- data/lib/api_recipes/response.rb +90 -9
- data/lib/api_recipes/version.rb +3 -1
- data/lib/api_recipes.rb +42 -152
- metadata +26 -12
- data/lib/api_recipes/exceptions.rb +0 -91
- data/lib/api_recipes/route.rb +0 -165
- data/lib/api_recipes/settings.rb +0 -30
- data/lib/api_recipes/utils.rb +0 -195
data/README.md
CHANGED
|
@@ -10,46 +10,60 @@
|
|
|
10
10
|
Describe an HTTP API once, in YAML, and call it with plain Ruby methods.
|
|
11
11
|
|
|
12
12
|
```ruby
|
|
13
|
-
ApiRecipes.github.users.repos('octocat')
|
|
13
|
+
ApiRecipes.github.users.repos('octocat') do |response|
|
|
14
|
+
response.data.each { |repo| puts repo['name'] }
|
|
15
|
+
end
|
|
14
16
|
# GET https://api.github.com/users/octocat/repos
|
|
15
|
-
#
|
|
17
|
+
# prints "Hello-World" and the other repository names
|
|
16
18
|
```
|
|
17
19
|
|
|
18
20
|
There are no client classes to write. Hosts, paths, verbs, timeouts and expected
|
|
19
21
|
status codes live in a configuration file, and ApiRecipes turns them into a chain
|
|
20
22
|
of methods. Requests are made with [http.rb](https://github.com/httprb/http).
|
|
21
23
|
|
|
24
|
+
This page describes version 3.0, which is in pre-release. The documentation of
|
|
25
|
+
version 2 is the
|
|
26
|
+
[README of the `v2.10.4` tag](https://github.com/madAle/api_recipes/blob/v2.10.4/README.md).
|
|
27
|
+
Coming from version 2? Read [UPGRADING.md](UPGRADING.md) first.
|
|
28
|
+
|
|
22
29
|
## Contents
|
|
23
30
|
|
|
24
31
|
- [Installation](#installation)
|
|
25
32
|
- [Quick start](#quick-start)
|
|
26
33
|
- [Describing an API](#describing-an-api)
|
|
34
|
+
- [Variables](#variables)
|
|
27
35
|
- [Loading the configuration](#loading-the-configuration)
|
|
28
36
|
- [Where an API is available](#where-an-api-is-available)
|
|
29
37
|
- [Making requests](#making-requests)
|
|
38
|
+
- [Options for one chain: `with`](#options-for-one-chain-with)
|
|
39
|
+
- [Reaching an endpoint by name: `[]`](#reaching-an-endpoint-by-name-)
|
|
30
40
|
- [Reading the response](#reading-the-response)
|
|
31
41
|
- [Deciding what counts as success](#deciding-what-counts-as-success)
|
|
32
42
|
- [Handling errors](#handling-errors)
|
|
33
43
|
- [Authorization](#authorization)
|
|
34
44
|
- [Logging and debugging](#logging-and-debugging)
|
|
45
|
+
- [Inspecting an API](#inspecting-an-api)
|
|
35
46
|
- [Recipes](#recipes)
|
|
47
|
+
- [Security](#security)
|
|
36
48
|
- [Options reference](#options-reference)
|
|
37
49
|
- [Good to know](#good-to-know)
|
|
38
50
|
- [Runnable examples](#runnable-examples)
|
|
39
51
|
- [Compatibility](#compatibility)
|
|
52
|
+
- [Upgrading from 2.x](#upgrading-from-2x)
|
|
40
53
|
- [Development](#development)
|
|
41
54
|
|
|
42
55
|
## Installation
|
|
43
56
|
|
|
44
|
-
Add the gem to your Gemfile and run `bundle install
|
|
57
|
+
Add the gem to your Gemfile and run `bundle install`. While 3.0 is in
|
|
58
|
+
pre-release, Bundler installs it only when you ask for a pre-release version:
|
|
45
59
|
|
|
46
60
|
```ruby
|
|
47
|
-
gem 'api_recipes'
|
|
61
|
+
gem 'api_recipes', '>= 3.0.0.beta1'
|
|
48
62
|
```
|
|
49
63
|
|
|
50
64
|
Or install it directly:
|
|
51
65
|
|
|
52
|
-
$ gem install api_recipes
|
|
66
|
+
$ gem install api_recipes --pre
|
|
53
67
|
|
|
54
68
|
## Quick start
|
|
55
69
|
|
|
@@ -83,7 +97,8 @@ end
|
|
|
83
97
|
response = ApiRecipes.github.users.show('octocat').run
|
|
84
98
|
|
|
85
99
|
response.code # => 200
|
|
86
|
-
response.data['name']
|
|
100
|
+
response.data['name']
|
|
101
|
+
# => "The Octocat"
|
|
87
102
|
```
|
|
88
103
|
|
|
89
104
|
Each endpoint in the file becomes a method, arguments fill the `:placeholders`
|
|
@@ -113,6 +128,8 @@ github:
|
|
|
113
128
|
show: # GET /repos/:owner/:repo
|
|
114
129
|
path: ''
|
|
115
130
|
contributors: # GET /repos/:owner/:repo/contributors
|
|
131
|
+
contents: # GET /repos/:owner/:repo/contents/*path
|
|
132
|
+
path: /contents/*path
|
|
116
133
|
issues: # GET /repos/:owner/:repo/issues
|
|
117
134
|
endpoints:
|
|
118
135
|
create: # POST /repos/:owner/:repo/issues
|
|
@@ -125,6 +142,12 @@ github:
|
|
|
125
142
|
repositories: # GET /search/repositories
|
|
126
143
|
```
|
|
127
144
|
|
|
145
|
+
The configuration is checked when it is loaded. A mistake, such as an unknown
|
|
146
|
+
option, a verb that does not exist or a negative timeout, raises
|
|
147
|
+
`ApiRecipes::ConfigurationError`. Its message lists every problem at once, so you
|
|
148
|
+
fix them in one go. Keys that start with `x-` are free: ApiRecipes ignores them,
|
|
149
|
+
and you can use them for your own notes.
|
|
150
|
+
|
|
128
151
|
### How a path is built
|
|
129
152
|
|
|
130
153
|
The path of an endpoint is the path of its parent followed by its own segment:
|
|
@@ -153,6 +176,31 @@ ApiRecipes.github.repos('rails', 'rails').contributors.url.to_s
|
|
|
153
176
|
|
|
154
177
|
The wrong number of values raises `ApiRecipes::PathParamsMismatch`.
|
|
155
178
|
|
|
179
|
+
ApiRecipes encodes each value for you, so a value cannot add segments, a query
|
|
180
|
+
string or a fragment to the URL:
|
|
181
|
+
|
|
182
|
+
```ruby
|
|
183
|
+
ApiRecipes.github.users.show('Jane Doe').url.to_s
|
|
184
|
+
# => "https://api.github.com/users/Jane%20Doe"
|
|
185
|
+
|
|
186
|
+
ApiRecipes.github.users.show('a/b').url.to_s
|
|
187
|
+
# => "https://api.github.com/users/a%2Fb"
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Do not encode values yourself: `%2F` would be sent as `%252F`. A value that is
|
|
191
|
+
`nil`, empty, `.` or `..` raises `ApiRecipes::InvalidPathParameter`.
|
|
192
|
+
|
|
193
|
+
When a value really is several segments, such as the path of a file, write the
|
|
194
|
+
placeholder with a `*`. Each segment is encoded and the slashes stay:
|
|
195
|
+
|
|
196
|
+
```ruby
|
|
197
|
+
ApiRecipes.github.repos('rails', 'rails').contents('lib/rails.rb').url.to_s
|
|
198
|
+
# => "https://api.github.com/repos/rails/rails/contents/lib/rails.rb"
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
A `*name` placeholder works only at the start of a segment, and a `:` that must
|
|
202
|
+
stay in the path is written `\:`.
|
|
203
|
+
|
|
156
204
|
### Endpoints that only group others
|
|
157
205
|
|
|
158
206
|
With `route: no` an endpoint exists only to hold nested endpoints. `search` above
|
|
@@ -182,11 +230,113 @@ ApiRecipes.billing.invoices.show(42).url.to_s
|
|
|
182
230
|
# => "http://billing_service:3000/api/v1/invoices/42"
|
|
183
231
|
```
|
|
184
232
|
|
|
233
|
+
`host` is a plain host name: no scheme, port, path or spaces. Use `protocol` and
|
|
234
|
+
`port` for those. A `base_url` cannot contain a `:name` or `*name` placeholder;
|
|
235
|
+
for a value that changes, use a [variable](#variables).
|
|
236
|
+
|
|
185
237
|
All options are listed in the [options reference](#options-reference).
|
|
186
238
|
|
|
239
|
+
## Variables
|
|
240
|
+
|
|
241
|
+
A variable is a `{name}` placeholder in the `host`, the `base_url` or the value
|
|
242
|
+
of a header. Use it for what changes from one account or one environment to the
|
|
243
|
+
next, such as the address of a shop. Declare the variables of the API, with an
|
|
244
|
+
optional `default` and `description`:
|
|
245
|
+
|
|
246
|
+
```yaml
|
|
247
|
+
shopify:
|
|
248
|
+
variables:
|
|
249
|
+
shop:
|
|
250
|
+
description: the part of the shop address before .myshopify.com
|
|
251
|
+
api_version:
|
|
252
|
+
default: '2026-10'
|
|
253
|
+
host: '{shop}.myshopify.com'
|
|
254
|
+
base_url: admin/api/{api_version}
|
|
255
|
+
auth:
|
|
256
|
+
type: header
|
|
257
|
+
name: X-Shopify-Access-Token
|
|
258
|
+
endpoints:
|
|
259
|
+
products:
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
A variable without a value and without a default raises
|
|
263
|
+
`ApiRecipes::MissingVariable` when the request is built. Give it a value in the
|
|
264
|
+
way that fits your code. The nearest one wins: the chain (`with`), then the
|
|
265
|
+
object, then its class, then `ApiRecipes.shopify`, then the default of the file.
|
|
266
|
+
|
|
267
|
+
```ruby
|
|
268
|
+
ApiRecipes.shopify.with(variables: { shop: 'acme' }).products.url.to_s
|
|
269
|
+
# => "https://acme.myshopify.com/admin/api/2026-10/products"
|
|
270
|
+
|
|
271
|
+
ApiRecipes.shopify.variables = { shop: 'acme' }
|
|
272
|
+
ApiRecipes.shopify.products.url.to_s
|
|
273
|
+
# => "https://acme.myshopify.com/admin/api/2026-10/products"
|
|
274
|
+
|
|
275
|
+
ApiRecipes.shopify.with(variables: { api_version: '2027-01' }).products.url.to_s
|
|
276
|
+
# => "https://acme.myshopify.com/admin/api/2027-01/products"
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
For one class, or for the objects of a class:
|
|
280
|
+
|
|
281
|
+
```ruby
|
|
282
|
+
class Store
|
|
283
|
+
include ApiRecipes
|
|
284
|
+
api :shopify, variables: { shop: 'acme' }
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
Store.shopify.products.url.to_s
|
|
288
|
+
# => "https://acme.myshopify.com/admin/api/2026-10/products"
|
|
289
|
+
|
|
290
|
+
store = Store.new
|
|
291
|
+
store.shopify.variables = { shop: 'zed' }
|
|
292
|
+
store.shopify.products.url.to_s
|
|
293
|
+
# => "https://zed.myshopify.com/admin/api/2026-10/products"
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
The options that a class gives to `api` can use the variables of the API, as in
|
|
297
|
+
`api :shopify, host: '{shop}.staging.example.test'`. When an API exists only in
|
|
298
|
+
a class, the names given in `variables:` are its variables, so each one gets a
|
|
299
|
+
value there, and an object or `with` can give another:
|
|
300
|
+
|
|
301
|
+
```ruby
|
|
302
|
+
class Sandbox
|
|
303
|
+
include ApiRecipes
|
|
304
|
+
api :sandbox, host: '{tenant}.sandbox.example.test', variables: { tenant: 'demo' },
|
|
305
|
+
endpoints: { ping: nil }
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
Sandbox.sandbox.with(variables: { tenant: 'acme' }).ping.url.to_s
|
|
309
|
+
# => "https://acme.sandbox.example.test/ping"
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
Or for everybody, when the application starts:
|
|
313
|
+
|
|
314
|
+
```ruby
|
|
315
|
+
ApiRecipes.configure do |config|
|
|
316
|
+
config.variables = { shopify: { shop: 'acme' } }
|
|
317
|
+
end
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
ApiRecipes never reads the environment for you: if the shop comes from an
|
|
321
|
+
environment variable, read it in your code and pass it in.
|
|
322
|
+
|
|
323
|
+
A value is checked for the place where it ends up. In a `host` it can contain
|
|
324
|
+
only letters, digits, dots, hyphens and underscores. In a `base_url` it is
|
|
325
|
+
encoded like a path parameter. In a header it cannot contain a line break or
|
|
326
|
+
another control character. Anything else raises `ApiRecipes::InvalidVariable`.
|
|
327
|
+
A name that the API does not declare raises `ApiRecipes::ConfigurationError` at
|
|
328
|
+
every level, so a misspelled name is never ignored.
|
|
329
|
+
`variables` without an assignment returns the values set at the level you call
|
|
330
|
+
it on. Assigning `nil` clears them. At the global level (`ApiRecipes.shopify`)
|
|
331
|
+
that includes the values given with `config.variables`, which are the same level;
|
|
332
|
+
a default declared in the file applies again.
|
|
333
|
+
The values given with `config.variables` are applied again at every `configure`,
|
|
334
|
+
so a value assigned directly with `ApiRecipes.shopify.variables = ...` under the
|
|
335
|
+
same name lasts only until the next `configure`.
|
|
336
|
+
|
|
187
337
|
## Loading the configuration
|
|
188
338
|
|
|
189
|
-
Configure ApiRecipes once,
|
|
339
|
+
Configure ApiRecipes once, when your application starts.
|
|
190
340
|
|
|
191
341
|
### From YAML files
|
|
192
342
|
|
|
@@ -197,19 +347,27 @@ end
|
|
|
197
347
|
```
|
|
198
348
|
|
|
199
349
|
A file can describe one API or several. If two files describe the same API, the
|
|
200
|
-
later one replaces the earlier one entirely.
|
|
350
|
+
later one replaces the earlier one entirely. The same holds for the sources
|
|
351
|
+
together: they are applied in the order they are assigned, so assigning
|
|
352
|
+
`apis_configs` after `apis_files_paths` lets the Hash replace the file.
|
|
353
|
+
|
|
354
|
+
A file that is missing, empty, not valid YAML or not valid UTF-8 raises
|
|
355
|
+
`ApiRecipes::RecipeFileError`, which names the file. A file called
|
|
356
|
+
`something.recipe.yml` is refused: that name is kept for another purpose.
|
|
201
357
|
|
|
202
358
|
Files are evaluated with ERB before being parsed, so values can come from the
|
|
203
359
|
environment:
|
|
204
360
|
|
|
205
361
|
```yaml
|
|
206
|
-
|
|
207
|
-
host: <%= ENV.fetch('
|
|
208
|
-
timeout: <%= ENV.fetch('
|
|
362
|
+
billing:
|
|
363
|
+
host: <%= ENV.fetch('BILLING_HOST', 'billing.example.com') %>
|
|
364
|
+
timeout: <%= ENV.fetch('BILLING_TIMEOUT', 3) %>
|
|
209
365
|
endpoints:
|
|
210
|
-
|
|
366
|
+
invoices:
|
|
211
367
|
```
|
|
212
368
|
|
|
369
|
+
Only files you wrote and trust should be loaded: ERB runs the Ruby code in them.
|
|
370
|
+
|
|
213
371
|
### From a Hash
|
|
214
372
|
|
|
215
373
|
```ruby
|
|
@@ -225,16 +383,28 @@ ApiRecipes.configure do |config|
|
|
|
225
383
|
end
|
|
226
384
|
```
|
|
227
385
|
|
|
228
|
-
Keys can be strings or symbols.
|
|
386
|
+
Keys can be strings or symbols, but not both for the same option.
|
|
387
|
+
|
|
388
|
+
If the configuration has a problem, `configure` raises and the previous
|
|
389
|
+
configuration stays active.
|
|
229
390
|
|
|
230
391
|
## Where an API is available
|
|
231
392
|
|
|
232
393
|
### On the `ApiRecipes` module
|
|
233
394
|
|
|
234
|
-
Every configured API is a method of the module
|
|
395
|
+
Every configured API is a method of the module, and `ApiRecipes[...]` reaches the
|
|
396
|
+
same API by name, which is handy when the name is in a variable:
|
|
235
397
|
|
|
236
398
|
```ruby
|
|
237
399
|
ApiRecipes.github.users.run
|
|
400
|
+
ApiRecipes[:github].users.run
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
`ApiRecipes.apis` lists the names:
|
|
404
|
+
|
|
405
|
+
```ruby
|
|
406
|
+
ApiRecipes.apis.inspect
|
|
407
|
+
# => "[:github, :billing, :shopify]"
|
|
238
408
|
```
|
|
239
409
|
|
|
240
410
|
### In your classes
|
|
@@ -261,6 +431,20 @@ class GithubProfile
|
|
|
261
431
|
end
|
|
262
432
|
```
|
|
263
433
|
|
|
434
|
+
`api :github, as: :gh` gives the method another name. An API is declared once in
|
|
435
|
+
a class and its ancestors, modules included: declaring it twice raises
|
|
436
|
+
`ApiRecipes::ApiNameClashError`. If a subclass needs other options, use
|
|
437
|
+
[`with`](#options-for-one-chain-with). A singleton class cannot declare an API
|
|
438
|
+
(`ApiRecipes::ApiNameClashError`): declare it in a module and `extend` the object
|
|
439
|
+
with it.
|
|
440
|
+
|
|
441
|
+
An API declared in a module is available as an instance method of every class
|
|
442
|
+
that includes the module, and as `Module.name_of_api` on the module itself. The
|
|
443
|
+
including class gets no class-level method.
|
|
444
|
+
|
|
445
|
+
A credential or a variable set through one declaration is never seen by another
|
|
446
|
+
declaration of the same API name.
|
|
447
|
+
|
|
264
448
|
### With settings of its own
|
|
265
449
|
|
|
266
450
|
A class can change the configuration it uses. The Hash is merged over the global
|
|
@@ -289,6 +473,10 @@ Forecast.weather.forecast('rome').url.to_s
|
|
|
289
473
|
# => "https://api.weather.test/forecast/rome"
|
|
290
474
|
```
|
|
291
475
|
|
|
476
|
+
The options are checked like the ones in a file. When a class changes the
|
|
477
|
+
destination, with its own `host`, `protocol` or `port`, it needs a credential of
|
|
478
|
+
its own: see [Authorization](#authorization).
|
|
479
|
+
|
|
292
480
|
## Making requests
|
|
293
481
|
|
|
294
482
|
### `run` or a block
|
|
@@ -308,7 +496,7 @@ end
|
|
|
308
496
|
```
|
|
309
497
|
|
|
310
498
|
Use `run` when you need the returned value: the block form returns the endpoint,
|
|
311
|
-
not the response.
|
|
499
|
+
not the response. `run` with a block yields the response and returns it.
|
|
312
500
|
|
|
313
501
|
### Query string, body and headers
|
|
314
502
|
|
|
@@ -323,6 +511,7 @@ They are the options of
|
|
|
323
511
|
| `form:` | a form-encoded body |
|
|
324
512
|
| `body:` | a raw body |
|
|
325
513
|
| `headers:` | extra headers for this request only |
|
|
514
|
+
| `follow:` | follow redirects: `true`, or a Hash with `strict`, `max_hops` and `on_redirect` |
|
|
326
515
|
|
|
327
516
|
```ruby
|
|
328
517
|
# GET /search/repositories?q=api%20language:ruby&per_page=5
|
|
@@ -338,6 +527,16 @@ ApiRecipes.github.repos('rails', 'rails').issues.create(json: { title: 'Found a
|
|
|
338
527
|
ApiRecipes.github.users.show('octocat', headers: { 'X-Request-Id' => 'abc123' }).run
|
|
339
528
|
```
|
|
340
529
|
|
|
530
|
+
An option http.rb does not know raises its own `ArgumentError`. `follow` accepts
|
|
531
|
+
`true`, `false`, `nil` or a Hash with the keys above, and anything else raises
|
|
532
|
+
`ApiRecipes::ConfigurationError` before the request is sent.
|
|
533
|
+
|
|
534
|
+
When a redirect leads to another origin (another scheme, host or port), the
|
|
535
|
+
`Authorization` header, the header named by `auth.name`, the `Cookie` header and
|
|
536
|
+
the credential query parameter are not sent there, wherever they came from.
|
|
537
|
+
Cookies that a server sets during a chain of redirects are not carried to the
|
|
538
|
+
next hop.
|
|
539
|
+
|
|
341
540
|
### Verbs
|
|
342
541
|
|
|
343
542
|
The verb is part of the endpoint description (`verb: post`, `put`, `patch`,
|
|
@@ -350,6 +549,59 @@ ApiRecipes.github.users.repos('octocat').url.to_s
|
|
|
350
549
|
# => "https://api.github.com/users/octocat/repos"
|
|
351
550
|
```
|
|
352
551
|
|
|
552
|
+
`url` sends nothing and has no query string. For an endpoint with `route: no` it
|
|
553
|
+
returns `nil`.
|
|
554
|
+
|
|
555
|
+
## Options for one chain: `with`
|
|
556
|
+
|
|
557
|
+
`with` returns a copy of the API with some options changed. The copy is used for
|
|
558
|
+
the chain that follows it, and nothing is stored: the API itself does not change.
|
|
559
|
+
|
|
560
|
+
```ruby
|
|
561
|
+
ApiRecipes.github.with(host: 'github.example.com').users.show('octocat').url.to_s
|
|
562
|
+
# => "https://github.example.com/users/octocat"
|
|
563
|
+
```
|
|
564
|
+
|
|
565
|
+
On an API, `with` takes `protocol`, `host`, `port`, `base_url`, `timeout`,
|
|
566
|
+
`on_bad_code`, `mime_type`, `verify_with`, `default_headers`, `variables`,
|
|
567
|
+
`authorization` and `basic_auth`. The values are checked like the ones in a file,
|
|
568
|
+
and an option that is not in this list raises `ApiRecipes::ConfigurationError`.
|
|
569
|
+
|
|
570
|
+
On an endpoint, `with` takes `timeout`, `on_bad_code`, `ok_code`, `mime_type` and
|
|
571
|
+
`verify_with`, for that request only:
|
|
572
|
+
|
|
573
|
+
```ruby
|
|
574
|
+
ApiRecipes.github.users.show('octocat').with(timeout: 10, ok_code: [200, 304]).run
|
|
575
|
+
```
|
|
576
|
+
|
|
577
|
+
Giving an option as `nil` drops the value given before it in the same chain.
|
|
578
|
+
`default_headers` given to `with` are added to the ones already configured:
|
|
579
|
+
|
|
580
|
+
```ruby
|
|
581
|
+
ApiRecipes.github.with(default_headers: { 'X-Request-Id' => 'abc123' }).users.run
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
The options of a chain are one set. A credential given to `with` is sent
|
|
585
|
+
wherever that chain goes, also to a `host` given by another `with` of the same
|
|
586
|
+
chain: give them together only when the credential is meant for that host.
|
|
587
|
+
|
|
588
|
+
The other way of changing an API for a while is `api :name, options` in a class.
|
|
589
|
+
|
|
590
|
+
## Reaching an endpoint by name: `[]`
|
|
591
|
+
|
|
592
|
+
Every endpoint can be reached with `[]`, with a name that is a Symbol or a
|
|
593
|
+
String. The arguments after the name are the path parameters:
|
|
594
|
+
|
|
595
|
+
```ruby
|
|
596
|
+
ApiRecipes.github[:users][:show, 'octocat'].url.to_s
|
|
597
|
+
# => "https://api.github.com/users/octocat"
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
It is the same call as `github.users.show('octocat')`. Use it when the name is
|
|
601
|
+
in a variable, and for an endpoint whose name is already a method (see
|
|
602
|
+
[Good to know](#good-to-know)). A name that does not exist raises
|
|
603
|
+
`ApiRecipes::UnknownEndpoint`, and its message lists the available names.
|
|
604
|
+
|
|
353
605
|
## Reading the response
|
|
354
606
|
|
|
355
607
|
`run` returns an `ApiRecipes::Response`. It adds `data` and forwards everything
|
|
@@ -370,13 +622,52 @@ anything that is not JSON, or for an empty body, it raises `HTTP::Error`: read
|
|
|
370
622
|
`response.body.to_s` instead. If a server sends JSON with the wrong
|
|
371
623
|
`Content-Type`, set `mime_type: application/json` on the endpoint or on the API.
|
|
372
624
|
|
|
625
|
+
`response.success?` tells whether the response passed the rule of the endpoint
|
|
626
|
+
(see the next section). It is the way to check a response when `on_bad_code` is
|
|
627
|
+
`ignore`.
|
|
628
|
+
|
|
629
|
+
`response.uri` is the address that was requested. When the API sends its
|
|
630
|
+
credential in the query string, the parameter is left out of it.
|
|
631
|
+
|
|
632
|
+
### Filling an object
|
|
633
|
+
|
|
634
|
+
`fill` copies the data into an object, through its public writers:
|
|
635
|
+
|
|
636
|
+
```ruby
|
|
637
|
+
class Profile
|
|
638
|
+
attr_accessor :login, :name
|
|
639
|
+
end
|
|
640
|
+
|
|
641
|
+
profile = ApiRecipes.github.users.show('octocat').run.fill(Profile.new)
|
|
642
|
+
profile.login
|
|
643
|
+
# => "octocat"
|
|
644
|
+
|
|
645
|
+
ApiRecipes.github.users.show('octocat').run.fill(Profile.new, only: :login).name.nil?
|
|
646
|
+
# => "true"
|
|
647
|
+
```
|
|
648
|
+
|
|
649
|
+
Given an Array, `fill` takes a class and returns one new object per element. Keys
|
|
650
|
+
that the object has no writer for, or that are not plain attribute names, are
|
|
651
|
+
skipped. `only:` and `except:` take one name or a list, as Symbols or Strings.
|
|
652
|
+
An error raised by a writer is not hidden.
|
|
653
|
+
|
|
654
|
+
With a block, `fill` calls it with the filled object (or the list of objects),
|
|
655
|
+
the parsed data and the status of the response, and still returns the filled
|
|
656
|
+
object:
|
|
657
|
+
|
|
658
|
+
```ruby
|
|
659
|
+
ApiRecipes.github.users.show('octocat').run.fill(Profile.new) do |profile, data, status|
|
|
660
|
+
puts "#{status}: #{profile.login}"
|
|
661
|
+
end
|
|
662
|
+
```
|
|
663
|
+
|
|
373
664
|
## Deciding what counts as success
|
|
374
665
|
|
|
375
666
|
By default any 2xx status is a success and anything else raises
|
|
376
667
|
`ApiRecipes::ResponseCodeNotAsExpected`. Three options change that, for one
|
|
377
668
|
endpoint or for the whole API.
|
|
378
669
|
|
|
379
|
-
**Expect
|
|
670
|
+
**Expect given statuses** with `ok_code`, one status or a list:
|
|
380
671
|
|
|
381
672
|
```yaml
|
|
382
673
|
create:
|
|
@@ -385,6 +676,11 @@ create:
|
|
|
385
676
|
ok_code: 201 # a 200 is now an error
|
|
386
677
|
```
|
|
387
678
|
|
|
679
|
+
```yaml
|
|
680
|
+
refresh:
|
|
681
|
+
ok_code: [200, 304]
|
|
682
|
+
```
|
|
683
|
+
|
|
388
684
|
**Never raise** with `on_bad_code: ignore`, and inspect the response yourself:
|
|
389
685
|
|
|
390
686
|
```yaml
|
|
@@ -394,7 +690,7 @@ health:
|
|
|
394
690
|
|
|
395
691
|
```ruby
|
|
396
692
|
response = ApiRecipes.status.health.run
|
|
397
|
-
response.
|
|
693
|
+
response.success? # => false, and no exception
|
|
398
694
|
```
|
|
399
695
|
|
|
400
696
|
**Decide in Ruby** with `verify_with`, the name of a method of the object that
|
|
@@ -425,7 +721,8 @@ end
|
|
|
425
721
|
```
|
|
426
722
|
|
|
427
723
|
The method can be private. It is looked up on the caller, so `verify_with` is
|
|
428
|
-
meant for APIs used from a class or an instance.
|
|
724
|
+
meant for APIs used from a class or an instance. A nested endpoint that has no
|
|
725
|
+
`verify_with` of its own uses the one of its parent.
|
|
429
726
|
|
|
430
727
|
## Handling errors
|
|
431
728
|
|
|
@@ -444,25 +741,40 @@ rescue HTTP::ConnectionError
|
|
|
444
741
|
end
|
|
445
742
|
```
|
|
446
743
|
|
|
447
|
-
|
|
448
|
-
|
|
744
|
+
Every error of ApiRecipes inherits from `ApiRecipes::Error`, which is a
|
|
745
|
+
`StandardError`. A bare `rescue` catches them, so rescue by name when you want
|
|
746
|
+
to treat them differently. The message of an error never contains the response
|
|
747
|
+
body, a credential or a query string: the body is on `error.response`.
|
|
449
748
|
|
|
450
749
|
| Error | Raised when |
|
|
451
750
|
| --- | --- |
|
|
452
751
|
| `ApiRecipes::ResponseCodeNotAsExpected` | the response is not a success; has `response`, `path` and `expected_code` |
|
|
453
752
|
| `ApiRecipes::PathParamsMismatch` | an endpoint gets the wrong number of path parameters |
|
|
753
|
+
| `ApiRecipes::InvalidPathParameter` | a path parameter is `nil`, empty, `.` or `..` |
|
|
454
754
|
| `ApiRecipes::NoRouteExists` | `run` is called on an endpoint with `route: no` |
|
|
455
|
-
| `ApiRecipes::
|
|
755
|
+
| `ApiRecipes::UnknownEndpoint` | `[]` gets a name that does not exist |
|
|
756
|
+
| `ApiRecipes::MissingVariable` | a variable has no value and no default |
|
|
757
|
+
| `ApiRecipes::InvalidVariable` | the value of a variable is not allowed where it is used |
|
|
758
|
+
| `ApiRecipes::InvalidCredential` | a credential is not a String, or contains a line break or a control character |
|
|
759
|
+
| `ApiRecipes::CredentialOriginMismatch` | a request would send a credential to an origin other than the one it was set for |
|
|
760
|
+
| `ApiRecipes::InvalidUrl` | the address that would be contacted is not the one that was validated |
|
|
761
|
+
| `ApiRecipes::ConfigurationError` | the configuration or the options of `with` or `follow` are not valid; has `errors`, the list of problems |
|
|
762
|
+
| `ApiRecipes::RecipeFileError` | a configuration file cannot be read; a kind of `ConfigurationError` that names the file |
|
|
763
|
+
| `ApiRecipes::ApiNameClashError` | an API is declared twice in a class hierarchy, or `api :name` names a method the class already has |
|
|
456
764
|
| `ApiRecipes::ApiConfigIsNotAnHash` | the second argument of `api` is not a Hash |
|
|
457
|
-
| `
|
|
458
|
-
| `HTTP::TimeoutError`, `HTTP::ConnectionError` | http.rb network errors; these are `StandardError`s |
|
|
765
|
+
| `HTTP::TimeoutError`, `HTTP::ConnectionError` | http.rb network errors |
|
|
459
766
|
|
|
460
767
|
## Authorization
|
|
461
768
|
|
|
462
|
-
|
|
463
|
-
|
|
769
|
+
A credential belongs to a level, and a request uses the nearest one. From the
|
|
770
|
+
nearest to the farthest:
|
|
464
771
|
|
|
465
|
-
|
|
772
|
+
1. the chain, with `with(authorization: ...)` or `with(basic_auth: ...)`
|
|
773
|
+
2. the object that makes the call
|
|
774
|
+
3. its class, then the classes and modules it inherits from
|
|
775
|
+
4. the API of the `ApiRecipes` module
|
|
776
|
+
|
|
777
|
+
**A token**, sent as the `Authorization` header, as it is written:
|
|
466
778
|
|
|
467
779
|
```ruby
|
|
468
780
|
ApiRecipes.github.authorization = "Bearer #{ENV.fetch('GITHUB_TOKEN')}"
|
|
@@ -474,37 +786,186 @@ ApiRecipes.github.authorization = "Bearer #{ENV.fetch('GITHUB_TOKEN')}"
|
|
|
474
786
|
ApiRecipes.github.basic_auth = { user: 'me', pass: 'secret' }
|
|
475
787
|
```
|
|
476
788
|
|
|
477
|
-
**A different token for one class
|
|
789
|
+
**A different token for one class.** It applies to the class and its instances:
|
|
478
790
|
|
|
479
791
|
```ruby
|
|
480
792
|
class AdminClient
|
|
481
793
|
include ApiRecipes
|
|
482
|
-
api :github
|
|
794
|
+
api :github
|
|
795
|
+
end
|
|
796
|
+
|
|
797
|
+
AdminClient.github.authorization = "Bearer #{ENV.fetch('ADMIN_TOKEN')}"
|
|
798
|
+
```
|
|
799
|
+
|
|
800
|
+
**A different token for one object**, for example one object per user:
|
|
801
|
+
|
|
802
|
+
```ruby
|
|
803
|
+
class UserRepos
|
|
804
|
+
include ApiRecipes
|
|
805
|
+
api :github
|
|
806
|
+
|
|
807
|
+
def initialize(user)
|
|
808
|
+
github.authorization = "Bearer #{user.github_token}"
|
|
809
|
+
end
|
|
483
810
|
end
|
|
484
811
|
```
|
|
485
812
|
|
|
486
|
-
**A different token for one
|
|
813
|
+
**A different token for one chain**, for example the token of the current user:
|
|
814
|
+
|
|
815
|
+
```ruby
|
|
816
|
+
ApiRecipes.github.with(authorization: "Bearer #{user.token}").users.repos('octocat').run
|
|
817
|
+
```
|
|
818
|
+
|
|
819
|
+
The reader returns what the nearest level assigned:
|
|
820
|
+
|
|
821
|
+
```ruby
|
|
822
|
+
ApiRecipes.github.authorization = 'Bearer abc'
|
|
823
|
+
ApiRecipes.github.authorization
|
|
824
|
+
# => "Bearer abc"
|
|
825
|
+
```
|
|
826
|
+
|
|
827
|
+
**No credential.** Assigning `nil` means "send none" and ends the search: it
|
|
828
|
+
does not fall back to a level farther away. The same goes for
|
|
829
|
+
`with(authorization: nil)`:
|
|
487
830
|
|
|
488
831
|
```ruby
|
|
489
|
-
|
|
832
|
+
AdminClient.github.authorization = nil # this class sends none
|
|
833
|
+
ApiRecipes.github.with(authorization: nil).users.run # this chain sends none
|
|
490
834
|
```
|
|
491
835
|
|
|
492
|
-
|
|
493
|
-
|
|
836
|
+
`authorization=`, `basic_auth=` and `variables=` change the level of the object
|
|
837
|
+
they are called on. They raise on an API that `with` returned: use
|
|
838
|
+
`with(authorization: ...)` there.
|
|
839
|
+
|
|
840
|
+
A credential is valid only for the origin it was set for: the scheme, the host
|
|
841
|
+
and the port. If a nearer level changes the destination (its own `host`,
|
|
842
|
+
`protocol` or `port`, or a variable of the host) and does not set a credential of
|
|
843
|
+
its own, the request raises `ApiRecipes::CredentialOriginMismatch` instead of
|
|
844
|
+
sending the credential somewhere else. Set the credential where you change the
|
|
845
|
+
destination:
|
|
846
|
+
|
|
847
|
+
```ruby
|
|
848
|
+
class EnterpriseClient
|
|
849
|
+
include ApiRecipes
|
|
850
|
+
api :github, host: 'github.example.com'
|
|
851
|
+
end
|
|
852
|
+
|
|
853
|
+
EnterpriseClient.github.authorization = "Bearer #{ENV.fetch('ENTERPRISE_TOKEN')}"
|
|
854
|
+
```
|
|
855
|
+
|
|
856
|
+
An API or an endpoint kept in a variable keeps the destination it was created
|
|
857
|
+
with. If a later `configure` moves the API to another origin, a request made
|
|
858
|
+
through it raises the same error instead of sending a credential of the levels
|
|
859
|
+
to the old origin: ask `ApiRecipes` (or the class, or the object) for the API
|
|
860
|
+
again. A `configure` that does not move the origin changes nothing for it.
|
|
861
|
+
|
|
862
|
+
The readers `authorization` and `basic_auth` return the nearest credential that
|
|
863
|
+
was assigned. They do not apply that check: only a request does.
|
|
864
|
+
|
|
865
|
+
A credential with a line break or another control character raises
|
|
866
|
+
`ApiRecipes::InvalidCredential`. The message never contains the value. A client
|
|
867
|
+
restored from a serialized form has no credential.
|
|
868
|
+
|
|
869
|
+
An API can say where its credential goes with `auth`:
|
|
870
|
+
|
|
871
|
+
| `auth.type` | The credential assigned with `authorization=` goes |
|
|
872
|
+
| --- | --- |
|
|
873
|
+
| none of these, or `none`, `bearer`, `basic` | in the `Authorization` header, as it is written |
|
|
874
|
+
| `header`, with a `name` | in the header called `name` |
|
|
875
|
+
| `query`, with a `name` | in the query parameter called `name` |
|
|
876
|
+
|
|
877
|
+
```yaml
|
|
878
|
+
weather:
|
|
879
|
+
host: api.weather.test
|
|
880
|
+
auth:
|
|
881
|
+
type: query
|
|
882
|
+
name: api_key
|
|
883
|
+
endpoints:
|
|
884
|
+
forecast:
|
|
885
|
+
```
|
|
886
|
+
|
|
887
|
+
Basic auth cannot be sent to an API of type `header` or `query`: the request
|
|
888
|
+
raises `ApiRecipes::InvalidCredential`. Assign the value with `authorization=`.
|
|
889
|
+
|
|
890
|
+
A credential written in `headers:` or in `default_headers` is sent as it is.
|
|
891
|
+
ApiRecipes does not check its origin, so prefer the levels above.
|
|
494
892
|
|
|
495
893
|
## Logging and debugging
|
|
496
894
|
|
|
497
895
|
```ruby
|
|
498
896
|
ApiRecipes.configure do |config|
|
|
499
|
-
config.logger = Rails.logger # any Logger
|
|
500
|
-
config.print_urls = true #
|
|
897
|
+
config.logger = Rails.logger # any Logger
|
|
898
|
+
config.print_urls = true # log the URL of every request
|
|
501
899
|
config.apis_files_paths = ['config/apis/github.yml']
|
|
502
900
|
end
|
|
503
901
|
```
|
|
504
902
|
|
|
505
|
-
Without `logger`, ApiRecipes logs to
|
|
506
|
-
|
|
507
|
-
`:fatal`) change that
|
|
903
|
+
Without `logger`, ApiRecipes logs to STDERR at warn level, so normal use prints
|
|
904
|
+
nothing and a problem shows up. `config.log_to` (a path or an IO) and
|
|
905
|
+
`config.log_level` (`:debug`, `:info`, `:warn`, `:error`, `:fatal`) change that
|
|
906
|
+
without building a Logger. Without `log_level`, the `LOG_LEVEL` environment
|
|
907
|
+
variable is used, in any letter case; a value that is not a level is ignored.
|
|
908
|
+
|
|
909
|
+
- The level of the default logger is, in this order: `log_level`; the `LOG_LEVEL`
|
|
910
|
+
variable; info when `print_urls` is on; otherwise warn. A level you chose is
|
|
911
|
+
never lowered by `print_urls`. A logger you provide keeps its own level.
|
|
912
|
+
- `print_urls = true` logs the URL of each request at info level.
|
|
913
|
+
- At debug level, every request logs one line: the verb, the URL, the status and
|
|
914
|
+
the time it took. A response with a bad status that raises is logged too. A
|
|
915
|
+
request whose connection fails or times out logs nothing.
|
|
916
|
+
- A log line never contains a query string, a header, a body or a credential.
|
|
917
|
+
- `ApiRecipes.logger` is the logger in use, and `ApiRecipes.configuration` is the
|
|
918
|
+
current configuration. Change the configuration only inside `configure`.
|
|
919
|
+
|
|
920
|
+
At the start, ApiRecipes logs one warning for each endpoint whose name cannot
|
|
921
|
+
become a method, when the configuration is loaded (see
|
|
922
|
+
[Good to know](#good-to-know)).
|
|
923
|
+
|
|
924
|
+
It also warns, once for each endpoint, when the value of a path parameter
|
|
925
|
+
contains a `/` (it is sent as `%2F`) or looks already percent-encoded (it is
|
|
926
|
+
encoded again). The warning names the endpoint and never the value.
|
|
927
|
+
`config.upgrade_warnings = false` turns these two warnings off.
|
|
928
|
+
|
|
929
|
+
## Inspecting an API
|
|
930
|
+
|
|
931
|
+
`inspect` is made for the console. It shows the name and the origin, and never a
|
|
932
|
+
credential, a header, a body or a query string:
|
|
933
|
+
|
|
934
|
+
```ruby
|
|
935
|
+
ApiRecipes.github.inspect
|
|
936
|
+
# => "#<ApiRecipes::Api github https://api.github.com endpoints: users, repos, search>"
|
|
937
|
+
|
|
938
|
+
ApiRecipes.github.users.show('octocat').inspect
|
|
939
|
+
# => "#<ApiRecipes::Endpoint github.users.show GET https://api.github.com/users/octocat>"
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
`definition` returns a read-only description of an API or of an endpoint:
|
|
943
|
+
|
|
944
|
+
```ruby
|
|
945
|
+
ApiRecipes.github.definition.host
|
|
946
|
+
# => "api.github.com"
|
|
947
|
+
|
|
948
|
+
ApiRecipes.github.users.show('octocat').definition.full_path
|
|
949
|
+
# => "/users/:login"
|
|
950
|
+
```
|
|
951
|
+
|
|
952
|
+
For an API: `name`, `protocol`, `host`, `port`, `base_url`, `timeout`,
|
|
953
|
+
`on_bad_code`, `mime_type`, `verify_with`, `default_headers`, `auth`,
|
|
954
|
+
`variables`, `endpoints`, `routes` and `to_h`. For an endpoint: `name`,
|
|
955
|
+
`full_name`, `path`, `full_path`, `path_params`, `verb`, `route?`, `ok_code`,
|
|
956
|
+
`timeout`, `on_bad_code`, `mime_type`, `verify_with`, `parent`, `endpoints` and
|
|
957
|
+
`to_h`. A definition never holds a credential assigned with `authorization=`,
|
|
958
|
+
`basic_auth=` or `with`, nor the value of a variable. It does return the
|
|
959
|
+
`default_headers` as they are configured, so do not write a credential there if
|
|
960
|
+
you pass definitions around; `to_h` and `inspect` hide the values of the headers.
|
|
961
|
+
|
|
962
|
+
`routes` lists every endpoint that can be called, with the call that reaches it:
|
|
963
|
+
|
|
964
|
+
```ruby
|
|
965
|
+
route = ApiRecipes.github.definition.routes.find { |r| r.call.end_with?('.contributors') }
|
|
966
|
+
[route.call, route.verb, route.url].join(' ')
|
|
967
|
+
# => "github.repos(owner, repo).contributors get https://api.github.com/repos/:owner/:repo/contributors"
|
|
968
|
+
```
|
|
508
969
|
|
|
509
970
|
## Recipes
|
|
510
971
|
|
|
@@ -525,11 +986,11 @@ ApiRecipes.github.authorization = "Bearer #{Rails.application.credentials.github
|
|
|
525
986
|
Keep one file and let ERB pick the values:
|
|
526
987
|
|
|
527
988
|
```yaml
|
|
528
|
-
|
|
529
|
-
protocol: <%= ENV.fetch('
|
|
530
|
-
host: <%= ENV.fetch('
|
|
989
|
+
reports:
|
|
990
|
+
protocol: <%= ENV.fetch('REPORTS_PROTOCOL', 'https') %>
|
|
991
|
+
host: <%= ENV.fetch('REPORTS_HOST', 'reports.example.com') %>
|
|
531
992
|
endpoints:
|
|
532
|
-
|
|
993
|
+
monthly:
|
|
533
994
|
```
|
|
534
995
|
|
|
535
996
|
### Every page of a list
|
|
@@ -559,19 +1020,22 @@ response.code # => 201
|
|
|
559
1020
|
response.data['number'] # => 1347
|
|
560
1021
|
```
|
|
561
1022
|
|
|
562
|
-
### A token per user
|
|
1023
|
+
### A token per user
|
|
563
1024
|
|
|
564
|
-
|
|
565
|
-
|
|
1025
|
+
Give each user's object its own credential, or pass it with the chain, and the
|
|
1026
|
+
users never see each other's token:
|
|
566
1027
|
|
|
567
1028
|
```ruby
|
|
568
1029
|
class UserRepos
|
|
1030
|
+
include ApiRecipes
|
|
1031
|
+
api :github
|
|
1032
|
+
|
|
569
1033
|
def initialize(user)
|
|
570
|
-
@
|
|
1034
|
+
@token = user.github_token
|
|
571
1035
|
end
|
|
572
1036
|
|
|
573
1037
|
def names
|
|
574
|
-
|
|
1038
|
+
github.with(authorization: "Bearer #{@token}").users.repos('octocat').run.data.map { |repo| repo['name'] }
|
|
575
1039
|
end
|
|
576
1040
|
end
|
|
577
1041
|
```
|
|
@@ -589,7 +1053,7 @@ status:
|
|
|
589
1053
|
|
|
590
1054
|
```ruby
|
|
591
1055
|
def service_up?
|
|
592
|
-
ApiRecipes.status.health.run.
|
|
1056
|
+
ApiRecipes.status.health.run.success?
|
|
593
1057
|
rescue HTTP::Error # timeout, refused connection, DNS failure
|
|
594
1058
|
false
|
|
595
1059
|
end
|
|
@@ -628,8 +1092,8 @@ end
|
|
|
628
1092
|
```
|
|
629
1093
|
|
|
630
1094
|
If your tests configure ApiRecipes themselves, `ApiRecipes.reset!` removes the
|
|
631
|
-
global configuration
|
|
632
|
-
can start clean:
|
|
1095
|
+
global configuration, the API methods defined on the module and every credential
|
|
1096
|
+
and variable value that was assigned, so each example can start clean:
|
|
633
1097
|
|
|
634
1098
|
```ruby
|
|
635
1099
|
RSpec.configure do |config|
|
|
@@ -637,6 +1101,55 @@ RSpec.configure do |config|
|
|
|
637
1101
|
end
|
|
638
1102
|
```
|
|
639
1103
|
|
|
1104
|
+
## Security
|
|
1105
|
+
|
|
1106
|
+
What ApiRecipes does:
|
|
1107
|
+
|
|
1108
|
+
- **Path parameters** are encoded one by one. A value cannot add a segment, a
|
|
1109
|
+
query string or a fragment. `nil`, an empty value, `.` and `..` are refused.
|
|
1110
|
+
- **Variables** are checked for the place where they end up: a host, a path or a
|
|
1111
|
+
header.
|
|
1112
|
+
- **Credentials** are sent only to the origin they were set for, and a request
|
|
1113
|
+
that would send one elsewhere raises. A value with a control character is
|
|
1114
|
+
refused, so a credential cannot add a header.
|
|
1115
|
+
- **Redirects.** With `follow`, a redirect to another origin drops the
|
|
1116
|
+
credentials, the `Cookie` header and the credential query parameter. They are
|
|
1117
|
+
not sent again if the chain comes back.
|
|
1118
|
+
- **Before sending**, the address that http.rb will contact is checked against
|
|
1119
|
+
the origin that was validated.
|
|
1120
|
+
- **Logs, errors and `inspect`.** A log line and an error message of the gem
|
|
1121
|
+
never contain a credential, a header value, a body or a query string. Neither
|
|
1122
|
+
does the `inspect` or the `pp` of an API, an endpoint, a response, a
|
|
1123
|
+
definition or the configuration, nor their `to_s`, except that the `to_s` of
|
|
1124
|
+
a response is its body, as for the http.rb response. `definition` never holds
|
|
1125
|
+
a credential that was assigned with `authorization=`, `basic_auth=` or `with`.
|
|
1126
|
+
It does hold the values of `default_headers`, which its readers return; its
|
|
1127
|
+
`inspect`, its `to_h` and its JSON show them as `[FILTERED]`.
|
|
1128
|
+
- **Serialization.** An API, an endpoint and a response refuse `Marshal.dump`,
|
|
1129
|
+
`YAML.dump`, `as_json` and `to_json`, and raise `TypeError`: serialize
|
|
1130
|
+
`response.data` or `response.body.to_s` instead. A definition refuses
|
|
1131
|
+
`Marshal.dump` and `YAML.dump`, and its JSON is the one of `to_h`.
|
|
1132
|
+
- **`fill`** calls only public writers and skips keys that are not plain
|
|
1133
|
+
attribute names.
|
|
1134
|
+
- **Configuration files** are read with `YAML.safe_load`, and the options are
|
|
1135
|
+
validated when they are loaded.
|
|
1136
|
+
|
|
1137
|
+
What stays with your application:
|
|
1138
|
+
|
|
1139
|
+
- ApiRecipes checks the form of a host, not who owns it. Never pass a value
|
|
1140
|
+
chosen by an end user as a whole host: not in `with(host: ...)`, and not in a
|
|
1141
|
+
variable that is the entire host. Check it against a list of hosts you know. A
|
|
1142
|
+
variable that is only a part of a host, like the shop name in
|
|
1143
|
+
`{shop}.myshopify.com`, is the intended use.
|
|
1144
|
+
- `response.original_response` is the raw http.rb response, and it gives access
|
|
1145
|
+
to the request that was sent, headers included. Do not log or serialize it.
|
|
1146
|
+
- ERB in a configuration file runs code. Load only files you trust.
|
|
1147
|
+
- Do not put a credential in the source of an application or in a file of the
|
|
1148
|
+
repository: read it from the place where your application keeps secrets.
|
|
1149
|
+
|
|
1150
|
+
Every protection has an example in [`spec/security`](spec/security); its
|
|
1151
|
+
[README](spec/security/README.md) maps each one to the example that proves it.
|
|
1152
|
+
|
|
640
1153
|
## Options reference
|
|
641
1154
|
|
|
642
1155
|
### `ApiRecipes.configure`
|
|
@@ -645,24 +1158,28 @@ end
|
|
|
645
1158
|
| --- | --- |
|
|
646
1159
|
| `apis_files_paths` | Array of YAML files, evaluated with ERB |
|
|
647
1160
|
| `apis_configs` | Hash of API descriptions |
|
|
1161
|
+
| `variables` | Hash of default variable values, as `{ api_name: { variable: value } }` |
|
|
648
1162
|
| `logger` | a Logger to use |
|
|
649
|
-
| `log_to` | path or IO for the default logger (default:
|
|
650
|
-
| `log_level` | level of the default logger (default: the `LOG_LEVEL` variable, or
|
|
651
|
-
| `print_urls` |
|
|
1163
|
+
| `log_to` | path or IO for the default logger (default: STDERR) |
|
|
1164
|
+
| `log_level` | level of the default logger (default: the `LOG_LEVEL` variable, or warn) |
|
|
1165
|
+
| `print_urls` | log the URL of each request at info level (default: false) |
|
|
1166
|
+
| `upgrade_warnings` | warn when a path parameter value contains `/` or looks already percent-encoded (default: true) |
|
|
652
1167
|
|
|
653
1168
|
### API
|
|
654
1169
|
|
|
655
1170
|
| Option | Default | Meaning |
|
|
656
1171
|
| --- | --- | --- |
|
|
657
1172
|
| `protocol` | `https` | `http` or `https` |
|
|
658
|
-
| `host` | `localhost` | host name |
|
|
1173
|
+
| `host` | `localhost` | host name, which can contain `{variables}` |
|
|
659
1174
|
| `port` | port of the protocol | port number |
|
|
660
|
-
| `base_url` | none | prefix of every path, for example `api/v1` |
|
|
1175
|
+
| `base_url` | none | prefix of every path, for example `api/v1`; can contain `{variables}` |
|
|
661
1176
|
| `timeout` | `3` | seconds allowed for the whole request |
|
|
662
|
-
| `default_headers` | none | headers sent with every request |
|
|
1177
|
+
| `default_headers` | none | headers sent with every request; a value can contain `{variables}` |
|
|
663
1178
|
| `on_bad_code` | `raise` | `raise` or `ignore` when the response is not a success |
|
|
664
1179
|
| `mime_type` | from the response | content type used by `response.data` |
|
|
665
1180
|
| `verify_with` | none | method that decides whether a response is a success |
|
|
1181
|
+
| `auth` | none | where the credential goes: `type` (`none`, `bearer`, `basic`, `header`, `query`) and `name` (for `header` and `query`) |
|
|
1182
|
+
| `variables` | none | the variables of the API, each with an optional `default` and `description` |
|
|
666
1183
|
| `endpoints` | none | the endpoints of the API |
|
|
667
1184
|
|
|
668
1185
|
### Endpoint
|
|
@@ -672,7 +1189,7 @@ end
|
|
|
672
1189
|
| `path` | the endpoint name | segment added to the parent path; `''` adds nothing |
|
|
673
1190
|
| `verb` | `get` | HTTP verb |
|
|
674
1191
|
| `route` | `yes` | `no` makes the endpoint a group that cannot be called |
|
|
675
|
-
| `ok_code` | any 2xx | the
|
|
1192
|
+
| `ok_code` | any 2xx | the status, or the list of statuses, accepted as a success |
|
|
676
1193
|
| `timeout` | the API value | seconds allowed for the whole request |
|
|
677
1194
|
| `on_bad_code` | the API value | `raise` or `ignore` |
|
|
678
1195
|
| `mime_type` | the API value | content type used by `response.data` |
|
|
@@ -684,26 +1201,49 @@ the endpoint that contains it.
|
|
|
684
1201
|
|
|
685
1202
|
## Good to know
|
|
686
1203
|
|
|
687
|
-
- **Configure
|
|
688
|
-
the
|
|
689
|
-
- **
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
`
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
`
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1204
|
+
- **Configure once, at startup.** Calling `configure` again replaces the whole
|
|
1205
|
+
configuration. A class sees the new configuration at its next call.
|
|
1206
|
+
- **Mistakes are reported, not ignored.** An unknown option, a wrong value or a
|
|
1207
|
+
verb that does not exist raises `ApiRecipes::ConfigurationError` when the
|
|
1208
|
+
configuration is loaded. The only free keys start with `x-`.
|
|
1209
|
+
- **Sharing a name.** An endpoint can have any name, and it is always reachable
|
|
1210
|
+
with `[]`. When the name is also a method of the object (`with`, `definition`,
|
|
1211
|
+
`authorization`, `basic_auth` or `variables` on an API; `run`, `url`, `with` or `definition`
|
|
1212
|
+
on an endpoint) or one of the names that Ruby and common libraries call on any
|
|
1213
|
+
object by themselves (`to_ary`, `to_str`, `to_json`...), no method is generated
|
|
1214
|
+
for it and ApiRecipes logs a warning when the configuration is loaded. Reach
|
|
1215
|
+
it with `[]`, as in `ApiRecipes.github[:with]`. Private methods of Ruby's
|
|
1216
|
+
`Kernel`, such as `test`, `open` and `format`, are not a problem. An API or an
|
|
1217
|
+
endpoint name cannot be empty or contain control characters.
|
|
1218
|
+
- **An API name can be a method of the module.** An API called `configure`,
|
|
1219
|
+
`configuration`, `logger`, `apis` or `reset!` gets no method of its own, so the
|
|
1220
|
+
method of the module keeps working, and a warning is logged. Reach the API with
|
|
1221
|
+
`ApiRecipes[:logger]`. In a class, `api :open` raises
|
|
1222
|
+
`ApiRecipes::ApiNameClashError` because `open` is already a method of the
|
|
1223
|
+
class: give the API another method name with `as:`.
|
|
1224
|
+
- **One declaration per API.** An API name is declared once in a class and its
|
|
1225
|
+
ancestors, modules included. A subclass that needs other options uses `with`.
|
|
1226
|
+
A credential or a variable set through one declaration is never seen by another
|
|
1227
|
+
declaration of the same API name.
|
|
1228
|
+
- **Serialization is refused.** An API, an endpoint and a response cannot be
|
|
1229
|
+
dumped with `Marshal` or `YAML`.
|
|
1230
|
+
- **Internationalized hosts.** A redirect to a host with non-ASCII characters
|
|
1231
|
+
needs the [addressable](https://github.com/sporkmonger/addressable) gem; without
|
|
1232
|
+
it http.rb raises `LoadError`.
|
|
1233
|
+
- **Constants seen by a class that includes `ApiRecipes`.** Ruby looks a constant
|
|
1234
|
+
up in the ancestors of a class before the top level, so inside a class that
|
|
1235
|
+
includes `ApiRecipes` the constants of the gem win over the constants of your
|
|
1236
|
+
application with the same name: `Api`, `Endpoint`, `Response`, `Configuration`,
|
|
1237
|
+
`Internals`, `VERSION`, `Error` and the error classes (`ApiConfigIsNotAnHash`,
|
|
1238
|
+
`ApiNameClashError`, `ConfigurationError`, `CredentialOriginMismatch`,
|
|
1239
|
+
`InvalidCredential`, `InvalidPathParameter`, `InvalidUrl`, `InvalidVariable`,
|
|
1240
|
+
`MissingVariable`, `NoRouteExists`, `PathParamsMismatch`, `RecipeFileError`,
|
|
1241
|
+
`ResponseCodeNotAsExpected` and `UnknownEndpoint`). If your application has a
|
|
1242
|
+
class with one of these names, write it with a leading `::` inside the classes
|
|
1243
|
+
that include `ApiRecipes`, for example `::Response`. The internal classes of
|
|
1244
|
+
the gem are all under `ApiRecipes::Internals`, so they hide nothing else.
|
|
1245
|
+
- **No changes to Ruby.** The gem adds no method to `Hash`, `Array` or any other
|
|
1246
|
+
class of Ruby, and does not touch `URI`.
|
|
707
1247
|
|
|
708
1248
|
## Runnable examples
|
|
709
1249
|
|
|
@@ -717,7 +1257,7 @@ The [`examples`](examples) folder contains scripts that call public APIs:
|
|
|
717
1257
|
| `multiple_endpoints.rb` | two APIs from two files |
|
|
718
1258
|
| `authorization.rb` | token authorization |
|
|
719
1259
|
| `basic_auth.rb` | basic auth |
|
|
720
|
-
| `
|
|
1260
|
+
| `authorization_for_a_class.rb` | a token for one class |
|
|
721
1261
|
|
|
722
1262
|
Run one from the root of the repository:
|
|
723
1263
|
|
|
@@ -728,10 +1268,17 @@ configuration file with every option commented.
|
|
|
728
1268
|
|
|
729
1269
|
## Compatibility
|
|
730
1270
|
|
|
731
|
-
- Ruby
|
|
732
|
-
- http.rb
|
|
1271
|
+
- Ruby 3.3 or higher. The test suite runs on the maintained versions: 3.3, 3.4 and 4.0
|
|
1272
|
+
- http.rb 6 (6.0.4 or higher)
|
|
733
1273
|
- uri 0.x and 1.x
|
|
734
1274
|
|
|
1275
|
+
## Upgrading from 2.x
|
|
1276
|
+
|
|
1277
|
+
[UPGRADING.md](UPGRADING.md) lists what stops with a message, what changes
|
|
1278
|
+
silently and what is new, and explains the `api_recipes upgrade` command, which
|
|
1279
|
+
looks for the changes in your code. A YAML file that is valid for 2.x keeps
|
|
1280
|
+
working, apart from the cases listed there.
|
|
1281
|
+
|
|
735
1282
|
## Development
|
|
736
1283
|
|
|
737
1284
|
$ bundle install
|
|
@@ -742,8 +1289,11 @@ uri gem:
|
|
|
742
1289
|
|
|
743
1290
|
$ URI_VERSION='~> 1.0' bundle exec rspec
|
|
744
1291
|
|
|
745
|
-
|
|
746
|
-
|
|
1292
|
+
The examples in this README and in UPGRADING.md are checked by
|
|
1293
|
+
`spec/docs/examples_spec.rb`. The protections described in the Security section
|
|
1294
|
+
are proved by the examples in [`spec/security`](spec/security).
|
|
1295
|
+
|
|
1296
|
+
What is planned for the next releases is in the [roadmap](docs/ROADMAP.md).
|
|
747
1297
|
|
|
748
1298
|
Bug reports and pull requests are welcome on
|
|
749
1299
|
[GitHub](https://github.com/madAle/api_recipes). Contributors are expected to
|