api_recipes 2.10.4 → 3.0.0.beta2

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.
Files changed (36) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +783 -81
  3. data/UPGRADING.md +473 -0
  4. data/exe/api_recipes +6 -0
  5. data/lib/api_recipes/api.rb +71 -49
  6. data/lib/api_recipes/cli/import/document.rb +234 -0
  7. data/lib/api_recipes/cli/import/security.rb +138 -0
  8. data/lib/api_recipes/cli/import/server.rb +166 -0
  9. data/lib/api_recipes/cli/import/tree.rb +288 -0
  10. data/lib/api_recipes/cli/import/writer.rb +127 -0
  11. data/lib/api_recipes/cli/import.rb +129 -0
  12. data/lib/api_recipes/cli/routes.rb +50 -0
  13. data/lib/api_recipes/cli/upgrade.rb +179 -0
  14. data/lib/api_recipes/cli.rb +166 -0
  15. data/lib/api_recipes/configuration.rb +185 -36
  16. data/lib/api_recipes/endpoint.rb +68 -118
  17. data/lib/api_recipes/errors.rb +137 -0
  18. data/lib/api_recipes/internals/compiler.rb +680 -0
  19. data/lib/api_recipes/internals/context.rb +237 -0
  20. data/lib/api_recipes/internals/credential.rb +86 -0
  21. data/lib/api_recipes/internals/declaration.rb +225 -0
  22. data/lib/api_recipes/internals/definition.rb +179 -0
  23. data/lib/api_recipes/internals/handles.rb +81 -0
  24. data/lib/api_recipes/internals/level.rb +192 -0
  25. data/lib/api_recipes/internals/path_template.rb +131 -0
  26. data/lib/api_recipes/internals/registry.rb +146 -0
  27. data/lib/api_recipes/internals/request.rb +285 -0
  28. data/lib/api_recipes/internals/template.rb +73 -0
  29. data/lib/api_recipes/response.rb +90 -9
  30. data/lib/api_recipes/version.rb +3 -1
  31. data/lib/api_recipes.rb +42 -152
  32. metadata +33 -12
  33. data/lib/api_recipes/exceptions.rb +0 -91
  34. data/lib/api_recipes/route.rb +0 -165
  35. data/lib/api_recipes/settings.rb +0 -30
  36. data/lib/api_recipes/utils.rb +0 -195
data/README.md CHANGED
@@ -10,46 +10,61 @@
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').run.data
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
- # => [{ "name" => "Hello-World", ... }, ...]
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)
36
+ - [Importing an OpenAPI description](#importing-an-openapi-description)
28
37
  - [Where an API is available](#where-an-api-is-available)
29
38
  - [Making requests](#making-requests)
39
+ - [Options for one chain: `with`](#options-for-one-chain-with)
40
+ - [Reaching an endpoint by name: `[]`](#reaching-an-endpoint-by-name-)
30
41
  - [Reading the response](#reading-the-response)
31
42
  - [Deciding what counts as success](#deciding-what-counts-as-success)
32
43
  - [Handling errors](#handling-errors)
33
44
  - [Authorization](#authorization)
34
45
  - [Logging and debugging](#logging-and-debugging)
46
+ - [Inspecting an API](#inspecting-an-api)
35
47
  - [Recipes](#recipes)
48
+ - [Security](#security)
36
49
  - [Options reference](#options-reference)
37
50
  - [Good to know](#good-to-know)
38
51
  - [Runnable examples](#runnable-examples)
39
52
  - [Compatibility](#compatibility)
53
+ - [Upgrading from 2.x](#upgrading-from-2x)
40
54
  - [Development](#development)
41
55
 
42
56
  ## Installation
43
57
 
44
- Add the gem to your Gemfile and run `bundle install`:
58
+ Add the gem to your Gemfile and run `bundle install`. While 3.0 is in
59
+ pre-release, Bundler installs it only when you ask for a pre-release version:
45
60
 
46
61
  ```ruby
47
- gem 'api_recipes'
62
+ gem 'api_recipes', '>= 3.0.0.beta1'
48
63
  ```
49
64
 
50
65
  Or install it directly:
51
66
 
52
- $ gem install api_recipes
67
+ $ gem install api_recipes --pre
53
68
 
54
69
  ## Quick start
55
70
 
@@ -83,7 +98,8 @@ end
83
98
  response = ApiRecipes.github.users.show('octocat').run
84
99
 
85
100
  response.code # => 200
86
- response.data['name'] # => "The Octocat"
101
+ response.data['name']
102
+ # => "The Octocat"
87
103
  ```
88
104
 
89
105
  Each endpoint in the file becomes a method, arguments fill the `:placeholders`
@@ -113,6 +129,8 @@ github:
113
129
  show: # GET /repos/:owner/:repo
114
130
  path: ''
115
131
  contributors: # GET /repos/:owner/:repo/contributors
132
+ contents: # GET /repos/:owner/:repo/contents/*path
133
+ path: /contents/*path
116
134
  issues: # GET /repos/:owner/:repo/issues
117
135
  endpoints:
118
136
  create: # POST /repos/:owner/:repo/issues
@@ -125,6 +143,12 @@ github:
125
143
  repositories: # GET /search/repositories
126
144
  ```
127
145
 
146
+ The configuration is checked when it is loaded. A mistake, such as an unknown
147
+ option, a verb that does not exist or a negative timeout, raises
148
+ `ApiRecipes::ConfigurationError`. Its message lists every problem at once, so you
149
+ fix them in one go. Keys that start with `x-` are free: ApiRecipes ignores them,
150
+ and you can use them for your own notes.
151
+
128
152
  ### How a path is built
129
153
 
130
154
  The path of an endpoint is the path of its parent followed by its own segment:
@@ -153,6 +177,31 @@ ApiRecipes.github.repos('rails', 'rails').contributors.url.to_s
153
177
 
154
178
  The wrong number of values raises `ApiRecipes::PathParamsMismatch`.
155
179
 
180
+ ApiRecipes encodes each value for you, so a value cannot add segments, a query
181
+ string or a fragment to the URL:
182
+
183
+ ```ruby
184
+ ApiRecipes.github.users.show('Jane Doe').url.to_s
185
+ # => "https://api.github.com/users/Jane%20Doe"
186
+
187
+ ApiRecipes.github.users.show('a/b').url.to_s
188
+ # => "https://api.github.com/users/a%2Fb"
189
+ ```
190
+
191
+ Do not encode values yourself: `%2F` would be sent as `%252F`. A value that is
192
+ `nil`, empty, `.` or `..` raises `ApiRecipes::InvalidPathParameter`.
193
+
194
+ When a value really is several segments, such as the path of a file, write the
195
+ placeholder with a `*`. Each segment is encoded and the slashes stay:
196
+
197
+ ```ruby
198
+ ApiRecipes.github.repos('rails', 'rails').contents('lib/rails.rb').url.to_s
199
+ # => "https://api.github.com/repos/rails/rails/contents/lib/rails.rb"
200
+ ```
201
+
202
+ A `*name` placeholder works only at the start of a segment, and a `:` that must
203
+ stay in the path is written `\:`.
204
+
156
205
  ### Endpoints that only group others
157
206
 
158
207
  With `route: no` an endpoint exists only to hold nested endpoints. `search` above
@@ -182,11 +231,113 @@ ApiRecipes.billing.invoices.show(42).url.to_s
182
231
  # => "http://billing_service:3000/api/v1/invoices/42"
183
232
  ```
184
233
 
234
+ `host` is a plain host name: no scheme, port, path or spaces. Use `protocol` and
235
+ `port` for those. A `base_url` cannot contain a `:name` or `*name` placeholder;
236
+ for a value that changes, use a [variable](#variables).
237
+
185
238
  All options are listed in the [options reference](#options-reference).
186
239
 
240
+ ## Variables
241
+
242
+ A variable is a `{name}` placeholder in the `host`, the `base_url` or the value
243
+ of a header. Use it for what changes from one account or one environment to the
244
+ next, such as the address of a shop. Declare the variables of the API, with an
245
+ optional `default` and `description`:
246
+
247
+ ```yaml
248
+ shopify:
249
+ variables:
250
+ shop:
251
+ description: the part of the shop address before .myshopify.com
252
+ api_version:
253
+ default: '2026-10'
254
+ host: '{shop}.myshopify.com'
255
+ base_url: admin/api/{api_version}
256
+ auth:
257
+ type: header
258
+ name: X-Shopify-Access-Token
259
+ endpoints:
260
+ products:
261
+ ```
262
+
263
+ A variable without a value and without a default raises
264
+ `ApiRecipes::MissingVariable` when the request is built. Give it a value in the
265
+ way that fits your code. The nearest one wins: the chain (`with`), then the
266
+ object, then its class, then `ApiRecipes.shopify`, then the default of the file.
267
+
268
+ ```ruby
269
+ ApiRecipes.shopify.with(variables: { shop: 'acme' }).products.url.to_s
270
+ # => "https://acme.myshopify.com/admin/api/2026-10/products"
271
+
272
+ ApiRecipes.shopify.variables = { shop: 'acme' }
273
+ ApiRecipes.shopify.products.url.to_s
274
+ # => "https://acme.myshopify.com/admin/api/2026-10/products"
275
+
276
+ ApiRecipes.shopify.with(variables: { api_version: '2027-01' }).products.url.to_s
277
+ # => "https://acme.myshopify.com/admin/api/2027-01/products"
278
+ ```
279
+
280
+ For one class, or for the objects of a class:
281
+
282
+ ```ruby
283
+ class Store
284
+ include ApiRecipes
285
+ api :shopify, variables: { shop: 'acme' }
286
+ end
287
+
288
+ Store.shopify.products.url.to_s
289
+ # => "https://acme.myshopify.com/admin/api/2026-10/products"
290
+
291
+ store = Store.new
292
+ store.shopify.variables = { shop: 'zed' }
293
+ store.shopify.products.url.to_s
294
+ # => "https://zed.myshopify.com/admin/api/2026-10/products"
295
+ ```
296
+
297
+ The options that a class gives to `api` can use the variables of the API, as in
298
+ `api :shopify, host: '{shop}.staging.example.test'`. When an API exists only in
299
+ a class, the names given in `variables:` are its variables, so each one gets a
300
+ value there, and an object or `with` can give another:
301
+
302
+ ```ruby
303
+ class Sandbox
304
+ include ApiRecipes
305
+ api :sandbox, host: '{tenant}.sandbox.example.test', variables: { tenant: 'demo' },
306
+ endpoints: { ping: nil }
307
+ end
308
+
309
+ Sandbox.sandbox.with(variables: { tenant: 'acme' }).ping.url.to_s
310
+ # => "https://acme.sandbox.example.test/ping"
311
+ ```
312
+
313
+ Or for everybody, when the application starts:
314
+
315
+ ```ruby
316
+ ApiRecipes.configure do |config|
317
+ config.variables = { shopify: { shop: 'acme' } }
318
+ end
319
+ ```
320
+
321
+ ApiRecipes never reads the environment for you: if the shop comes from an
322
+ environment variable, read it in your code and pass it in.
323
+
324
+ A value is checked for the place where it ends up. In a `host` it can contain
325
+ only letters, digits, dots, hyphens and underscores. In a `base_url` it is
326
+ encoded like a path parameter. In a header it cannot contain a line break or
327
+ another control character. Anything else raises `ApiRecipes::InvalidVariable`.
328
+ A name that the API does not declare raises `ApiRecipes::ConfigurationError` at
329
+ every level, so a misspelled name is never ignored.
330
+ `variables` without an assignment returns the values set at the level you call
331
+ it on. Assigning `nil` clears them. At the global level (`ApiRecipes.shopify`)
332
+ that includes the values given with `config.variables`, which are the same level;
333
+ a default declared in the file applies again.
334
+ The values given with `config.variables` are applied again at every `configure`,
335
+ so a value assigned directly with `ApiRecipes.shopify.variables = ...` under the
336
+ same name lasts only until the next `configure`.
337
+
187
338
  ## Loading the configuration
188
339
 
189
- Configure ApiRecipes once, before the first request.
340
+ Configure ApiRecipes once, when your application starts.
190
341
 
191
342
  ### From YAML files
192
343
 
@@ -197,19 +348,27 @@ end
197
348
  ```
198
349
 
199
350
  A file can describe one API or several. If two files describe the same API, the
200
- later one replaces the earlier one entirely.
351
+ later one replaces the earlier one entirely. The same holds for the sources
352
+ together: they are applied in the order they are assigned, so assigning
353
+ `apis_configs` after `apis_files_paths` lets the Hash replace the file.
354
+
355
+ A file that is missing, empty, not valid YAML or not valid UTF-8 raises
356
+ `ApiRecipes::RecipeFileError`, which names the file. A file called
357
+ `something.recipe.yml` is refused: that name is kept for another purpose.
201
358
 
202
359
  Files are evaluated with ERB before being parsed, so values can come from the
203
360
  environment:
204
361
 
205
362
  ```yaml
206
- github:
207
- host: <%= ENV.fetch('GITHUB_HOST', 'api.github.com') %>
208
- timeout: <%= ENV.fetch('GITHUB_TIMEOUT', 3) %>
363
+ billing:
364
+ host: <%= ENV.fetch('BILLING_HOST', 'billing.example.com') %>
365
+ timeout: <%= ENV.fetch('BILLING_TIMEOUT', 3) %>
209
366
  endpoints:
210
- users:
367
+ invoices:
211
368
  ```
212
369
 
370
+ Only files you wrote and trust should be loaded: ERB runs the Ruby code in them.
371
+
213
372
  ### From a Hash
214
373
 
215
374
  ```ruby
@@ -225,16 +384,163 @@ ApiRecipes.configure do |config|
225
384
  end
226
385
  ```
227
386
 
228
- Keys can be strings or symbols.
387
+ Keys can be strings or symbols, but not both for the same option.
388
+
389
+ If the configuration has a problem, `configure` raises and the previous
390
+ configuration stays active.
391
+
392
+ ## Importing an OpenAPI description
393
+
394
+ When an API publishes an OpenAPI description, the `api_recipes` command writes
395
+ the recipe for you:
396
+
397
+ $ api_recipes import openapi.yml --name github --output config/apis/github.yml
398
+
399
+ The description is read once, when you run the command. Your application never
400
+ reads it: it loads the recipe, which is a file like the ones above, and you can
401
+ read it, trim it and rename things in it. These operations
402
+
403
+ ```
404
+ GET /users
405
+ GET /users/{username}
406
+ GET /users/{username}/repos
407
+ GET /repos/{owner}/{repo}/issues
408
+ POST /repos/{owner}/{repo}/issues
409
+ GET /repos/{owner}/{repo}/issues/{issue_number}
410
+ PATCH /repos/{owner}/{repo}/issues/{issue_number}
411
+ ```
412
+
413
+ become this recipe:
414
+
415
+ ```
416
+ # Generated by api_recipes import from GitHub 1.0
417
+ github:
418
+ host: api.github.com
419
+ endpoints:
420
+ users: # GET /users (users/list)
421
+ endpoints:
422
+ show: # GET /users/{username} (users/get-by-username)
423
+ path: "/:username"
424
+ repos: # GET /users/{username}/repos (repos/list-for-user)
425
+ path: "/:username/repos"
426
+ repos:
427
+ route: false
428
+ endpoints:
429
+ issues: # GET /repos/{owner}/{repo}/issues (issues/list-for-repo)
430
+ path: "/:owner/:repo/issues"
431
+ endpoints:
432
+ create: # POST /repos/{owner}/{repo}/issues (issues/create)
433
+ path: ''
434
+ verb: post
435
+ ok_code: 201
436
+ show: # GET /repos/{owner}/{repo}/issues/{issue_number} (issues/get)
437
+ path: "/:issue_number"
438
+ update: # PATCH /repos/{owner}/{repo}/issues/{issue_number} (issues/update)
439
+ path: "/:issue_number"
440
+ verb: patch
441
+ ```
442
+
443
+ | Request | Call |
444
+ | --- | --- |
445
+ | `GET /users` | `github.users` |
446
+ | `GET /users/{username}` | `github.users.show('octocat')` |
447
+ | `GET /users/{username}/repos` | `github.users.repos('octocat')` |
448
+ | `GET /repos/{owner}/{repo}/issues` | `github.repos.issues('rails', 'rails')` |
449
+ | `POST /repos/{owner}/{repo}/issues` | `github.repos.issues('rails', 'rails').create(json: { title: 'Bug' })` |
450
+ | `GET /repos/{owner}/{repo}/issues/{issue_number}` | `github.repos.issues('rails', 'rails').show(1347)` |
451
+ | `PATCH /repos/{owner}/{repo}/issues/{issue_number}` | `github.repos.issues('rails', 'rails').update(1347, json: { state: 'closed' })` |
452
+
453
+ ### Options
454
+
455
+ | Option | Meaning |
456
+ | --- | --- |
457
+ | `--name NAME` | the name of the API in the recipe. Default: the title of the description, in lower case with `_` |
458
+ | `--only GLOB` | only the paths that match; can be repeated. `*` also crosses `/`: `--only 'repos/*'` |
459
+ | `--except GLOB` | leaves out the paths that match; can be repeated |
460
+ | `--server N` | which entry of `servers` gives the address, counted from 0. Default: the first |
461
+ | `--output FILE` | writes the recipe in FILE, which must not exist, instead of on STDOUT |
462
+
463
+ The input is one local file, YAML or JSON, OpenAPI 3.0 or 3.1. Warnings and a
464
+ summary go to STDERR, so the recipe can be redirected. The command exits with 1
465
+ when the description cannot be imported and with 2 when the arguments are wrong.
466
+
467
+ ### What is read
468
+
469
+ | From the description | In the recipe |
470
+ | --- | --- |
471
+ | the address of the server | `protocol`, `host`, `port`, `base_url` |
472
+ | the variables of the server | `variables`, with their defaults |
473
+ | the paths | the tree of endpoints |
474
+ | the path parameters | `:name` placeholders |
475
+ | the query parameters | a comment beside the endpoint, with a `*` on the required ones |
476
+ | the documented 2xx statuses | `ok_code`: one status, or a list. Left out when `200` is the only one or none is documented, since every 2xx is accepted by default |
477
+ | `security` and `securitySchemes` | `auth`: `bearer` for http bearer, OAuth 2 and OpenID Connect; `basic`; `header` or `query` for an API key |
478
+ | `operationId`, `deprecated` | a comment beside the endpoint |
479
+
480
+ Schemas, bodies, callbacks, webhooks, links and cookie parameters are not read:
481
+ the gem does not validate requests and responses against them.
482
+
483
+ ### How the names are made
484
+
485
+ Each segment of a path that is not a parameter is a node, named after the
486
+ segment in lower case, with `camelCase` turned into `snake_case` and every other
487
+ character into `_`. The parameters that come before a segment travel with it;
488
+ those at the end of the path travel with the operation. An operation is named
489
+ after its verb and after how its path ends:
490
+
491
+ | Verb | The path ends with a name (`/issues`) | The path ends with a parameter (`/issues/{n}`) |
492
+ | --- | --- | --- |
493
+ | GET | the node itself | `show` |
494
+ | POST | `create` | `post` |
495
+ | PUT | `replace_all` | `replace` |
496
+ | PATCH | `update_all` | `update` |
497
+ | DELETE | `delete_all` | `delete` |
498
+ | others | the name of the verb | the name of the verb and `_one` |
499
+
500
+ - A node whose path has no GET only groups others: `route: false`.
501
+ - Two endpoints with the same name under the same node: one gets a number
502
+ (`show_2`), and a warning says so.
503
+ - A name that is an existing method, such as `with`, is written all the same,
504
+ with a warning: reach it with `[]`.
505
+ - A single resource comes out badly: `PATCH /user` becomes `user.update_all`.
506
+ Rename it in the file.
507
+
508
+ What the gem cannot write as a path is left out, with a warning for each path:
509
+ a parameter directly followed by a letter, a digit or `_` (`/files/{id}_meta`),
510
+ because the gem reads `:id_meta` as one name; a segment that starts with `*` and
511
+ a name, which the gem reads as a parameter that spans segments; and an empty
512
+ segment (`/a//b`), because the gem joins two slashes into one.
513
+
514
+ ### What the command refuses
515
+
516
+ - Swagger 2.0: convert the description to OpenAPI 3 first.
517
+ - A `$ref` to another file or to an address: bundle the description into one
518
+ file first. References inside the file are followed.
519
+ - A description whose text would become code in the recipe: `<%` in a value is
520
+ an error that says where, and it is removed from the comments.
521
+ - A YAML description with binary values, with keys that are not plain text, or
522
+ with aliases that stand for more than ten million values.
523
+
524
+ The command reads that one file, never uses the network and runs nothing of the
525
+ description.
229
526
 
230
527
  ## Where an API is available
231
528
 
232
529
  ### On the `ApiRecipes` module
233
530
 
234
- Every configured API is a method of the module:
531
+ Every configured API is a method of the module, and `ApiRecipes[...]` reaches the
532
+ same API by name, which is handy when the name is in a variable:
235
533
 
236
534
  ```ruby
237
535
  ApiRecipes.github.users.run
536
+ ApiRecipes[:github].users.run
537
+ ```
538
+
539
+ `ApiRecipes.apis` lists the names:
540
+
541
+ ```ruby
542
+ ApiRecipes.apis.inspect
543
+ # => "[:github, :billing, :shopify]"
238
544
  ```
239
545
 
240
546
  ### In your classes
@@ -261,6 +567,20 @@ class GithubProfile
261
567
  end
262
568
  ```
263
569
 
570
+ `api :github, as: :gh` gives the method another name. An API is declared once in
571
+ a class and its ancestors, modules included: declaring it twice raises
572
+ `ApiRecipes::ApiNameClashError`. If a subclass needs other options, use
573
+ [`with`](#options-for-one-chain-with). A singleton class cannot declare an API
574
+ (`ApiRecipes::ApiNameClashError`): declare it in a module and `extend` the object
575
+ with it.
576
+
577
+ An API declared in a module is available as an instance method of every class
578
+ that includes the module, and as `Module.name_of_api` on the module itself. The
579
+ including class gets no class-level method.
580
+
581
+ A credential or a variable set through one declaration is never seen by another
582
+ declaration of the same API name.
583
+
264
584
  ### With settings of its own
265
585
 
266
586
  A class can change the configuration it uses. The Hash is merged over the global
@@ -289,6 +609,10 @@ Forecast.weather.forecast('rome').url.to_s
289
609
  # => "https://api.weather.test/forecast/rome"
290
610
  ```
291
611
 
612
+ The options are checked like the ones in a file. When a class changes the
613
+ destination, with its own `host`, `protocol` or `port`, it needs a credential of
614
+ its own: see [Authorization](#authorization).
615
+
292
616
  ## Making requests
293
617
 
294
618
  ### `run` or a block
@@ -308,7 +632,7 @@ end
308
632
  ```
309
633
 
310
634
  Use `run` when you need the returned value: the block form returns the endpoint,
311
- not the response.
635
+ not the response. `run` with a block yields the response and returns it.
312
636
 
313
637
  ### Query string, body and headers
314
638
 
@@ -323,6 +647,7 @@ They are the options of
323
647
  | `form:` | a form-encoded body |
324
648
  | `body:` | a raw body |
325
649
  | `headers:` | extra headers for this request only |
650
+ | `follow:` | follow redirects: `true`, or a Hash with `strict`, `max_hops` and `on_redirect` |
326
651
 
327
652
  ```ruby
328
653
  # GET /search/repositories?q=api%20language:ruby&per_page=5
@@ -338,6 +663,16 @@ ApiRecipes.github.repos('rails', 'rails').issues.create(json: { title: 'Found a
338
663
  ApiRecipes.github.users.show('octocat', headers: { 'X-Request-Id' => 'abc123' }).run
339
664
  ```
340
665
 
666
+ An option http.rb does not know raises its own `ArgumentError`. `follow` accepts
667
+ `true`, `false`, `nil` or a Hash with the keys above, and anything else raises
668
+ `ApiRecipes::ConfigurationError` before the request is sent.
669
+
670
+ When a redirect leads to another origin (another scheme, host or port), the
671
+ `Authorization` header, the header named by `auth.name`, the `Cookie` header and
672
+ the credential query parameter are not sent there, wherever they came from.
673
+ Cookies that a server sets during a chain of redirects are not carried to the
674
+ next hop.
675
+
341
676
  ### Verbs
342
677
 
343
678
  The verb is part of the endpoint description (`verb: post`, `put`, `patch`,
@@ -350,6 +685,59 @@ ApiRecipes.github.users.repos('octocat').url.to_s
350
685
  # => "https://api.github.com/users/octocat/repos"
351
686
  ```
352
687
 
688
+ `url` sends nothing and has no query string. For an endpoint with `route: no` it
689
+ returns `nil`.
690
+
691
+ ## Options for one chain: `with`
692
+
693
+ `with` returns a copy of the API with some options changed. The copy is used for
694
+ the chain that follows it, and nothing is stored: the API itself does not change.
695
+
696
+ ```ruby
697
+ ApiRecipes.github.with(host: 'github.example.com').users.show('octocat').url.to_s
698
+ # => "https://github.example.com/users/octocat"
699
+ ```
700
+
701
+ On an API, `with` takes `protocol`, `host`, `port`, `base_url`, `timeout`,
702
+ `on_bad_code`, `mime_type`, `verify_with`, `default_headers`, `variables`,
703
+ `authorization` and `basic_auth`. The values are checked like the ones in a file,
704
+ and an option that is not in this list raises `ApiRecipes::ConfigurationError`.
705
+
706
+ On an endpoint, `with` takes `timeout`, `on_bad_code`, `ok_code`, `mime_type` and
707
+ `verify_with`, for that request only:
708
+
709
+ ```ruby
710
+ ApiRecipes.github.users.show('octocat').with(timeout: 10, ok_code: [200, 304]).run
711
+ ```
712
+
713
+ Giving an option as `nil` drops the value given before it in the same chain.
714
+ `default_headers` given to `with` are added to the ones already configured:
715
+
716
+ ```ruby
717
+ ApiRecipes.github.with(default_headers: { 'X-Request-Id' => 'abc123' }).users.run
718
+ ```
719
+
720
+ The options of a chain are one set. A credential given to `with` is sent
721
+ wherever that chain goes, also to a `host` given by another `with` of the same
722
+ chain: give them together only when the credential is meant for that host.
723
+
724
+ The other way of changing an API for a while is `api :name, options` in a class.
725
+
726
+ ## Reaching an endpoint by name: `[]`
727
+
728
+ Every endpoint can be reached with `[]`, with a name that is a Symbol or a
729
+ String. The arguments after the name are the path parameters:
730
+
731
+ ```ruby
732
+ ApiRecipes.github[:users][:show, 'octocat'].url.to_s
733
+ # => "https://api.github.com/users/octocat"
734
+ ```
735
+
736
+ It is the same call as `github.users.show('octocat')`. Use it when the name is
737
+ in a variable, and for an endpoint whose name is already a method (see
738
+ [Good to know](#good-to-know)). A name that does not exist raises
739
+ `ApiRecipes::UnknownEndpoint`, and its message lists the available names.
740
+
353
741
  ## Reading the response
354
742
 
355
743
  `run` returns an `ApiRecipes::Response`. It adds `data` and forwards everything
@@ -370,13 +758,52 @@ anything that is not JSON, or for an empty body, it raises `HTTP::Error`: read
370
758
  `response.body.to_s` instead. If a server sends JSON with the wrong
371
759
  `Content-Type`, set `mime_type: application/json` on the endpoint or on the API.
372
760
 
761
+ `response.success?` tells whether the response passed the rule of the endpoint
762
+ (see the next section). It is the way to check a response when `on_bad_code` is
763
+ `ignore`.
764
+
765
+ `response.uri` is the address that was requested. When the API sends its
766
+ credential in the query string, the parameter is left out of it.
767
+
768
+ ### Filling an object
769
+
770
+ `fill` copies the data into an object, through its public writers:
771
+
772
+ ```ruby
773
+ class Profile
774
+ attr_accessor :login, :name
775
+ end
776
+
777
+ profile = ApiRecipes.github.users.show('octocat').run.fill(Profile.new)
778
+ profile.login
779
+ # => "octocat"
780
+
781
+ ApiRecipes.github.users.show('octocat').run.fill(Profile.new, only: :login).name.nil?
782
+ # => "true"
783
+ ```
784
+
785
+ Given an Array, `fill` takes a class and returns one new object per element. Keys
786
+ that the object has no writer for, or that are not plain attribute names, are
787
+ skipped. `only:` and `except:` take one name or a list, as Symbols or Strings.
788
+ An error raised by a writer is not hidden.
789
+
790
+ With a block, `fill` calls it with the filled object (or the list of objects),
791
+ the parsed data and the status of the response, and still returns the filled
792
+ object:
793
+
794
+ ```ruby
795
+ ApiRecipes.github.users.show('octocat').run.fill(Profile.new) do |profile, data, status|
796
+ puts "#{status}: #{profile.login}"
797
+ end
798
+ ```
799
+
373
800
  ## Deciding what counts as success
374
801
 
375
802
  By default any 2xx status is a success and anything else raises
376
803
  `ApiRecipes::ResponseCodeNotAsExpected`. Three options change that, for one
377
804
  endpoint or for the whole API.
378
805
 
379
- **Expect one exact status** with `ok_code`:
806
+ **Expect given statuses** with `ok_code`, one status or a list:
380
807
 
381
808
  ```yaml
382
809
  create:
@@ -385,6 +812,11 @@ create:
385
812
  ok_code: 201 # a 200 is now an error
386
813
  ```
387
814
 
815
+ ```yaml
816
+ refresh:
817
+ ok_code: [200, 304]
818
+ ```
819
+
388
820
  **Never raise** with `on_bad_code: ignore`, and inspect the response yourself:
389
821
 
390
822
  ```yaml
@@ -394,7 +826,7 @@ health:
394
826
 
395
827
  ```ruby
396
828
  response = ApiRecipes.status.health.run
397
- response.status.success? # => false, and no exception
829
+ response.success? # => false, and no exception
398
830
  ```
399
831
 
400
832
  **Decide in Ruby** with `verify_with`, the name of a method of the object that
@@ -425,7 +857,8 @@ end
425
857
  ```
426
858
 
427
859
  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.
860
+ meant for APIs used from a class or an instance. A nested endpoint that has no
861
+ `verify_with` of its own uses the one of its parent.
429
862
 
430
863
  ## Handling errors
431
864
 
@@ -444,25 +877,40 @@ rescue HTTP::ConnectionError
444
877
  end
445
878
  ```
446
879
 
447
- > **Rescue ApiRecipes errors by name.** They inherit from `Exception`, not from
448
- > `StandardError`, so a bare `rescue` or `rescue => e` does not catch them.
880
+ Every error of ApiRecipes inherits from `ApiRecipes::Error`, which is a
881
+ `StandardError`. A bare `rescue` catches them, so rescue by name when you want
882
+ to treat them differently. The message of an error never contains the response
883
+ body, a credential or a query string: the body is on `error.response`.
449
884
 
450
885
  | Error | Raised when |
451
886
  | --- | --- |
452
887
  | `ApiRecipes::ResponseCodeNotAsExpected` | the response is not a success; has `response`, `path` and `expected_code` |
453
888
  | `ApiRecipes::PathParamsMismatch` | an endpoint gets the wrong number of path parameters |
889
+ | `ApiRecipes::InvalidPathParameter` | a path parameter is `nil`, empty, `.` or `..` |
454
890
  | `ApiRecipes::NoRouteExists` | `run` is called on an endpoint with `route: no` |
455
- | `ApiRecipes::ApiNameClashError` | `api :name` is declared in a class that already has a method `name` |
891
+ | `ApiRecipes::UnknownEndpoint` | `[]` gets a name that does not exist |
892
+ | `ApiRecipes::MissingVariable` | a variable has no value and no default |
893
+ | `ApiRecipes::InvalidVariable` | the value of a variable is not allowed where it is used |
894
+ | `ApiRecipes::InvalidCredential` | a credential is not a String, or contains a line break or a control character |
895
+ | `ApiRecipes::CredentialOriginMismatch` | a request would send a credential to an origin other than the one it was set for |
896
+ | `ApiRecipes::InvalidUrl` | the address that would be contacted is not the one that was validated |
897
+ | `ApiRecipes::ConfigurationError` | the configuration or the options of `with` or `follow` are not valid; has `errors`, the list of problems |
898
+ | `ApiRecipes::RecipeFileError` | a configuration file cannot be read; a kind of `ConfigurationError` that names the file |
899
+ | `ApiRecipes::ApiNameClashError` | an API is declared twice in a class hierarchy, or `api :name` names a method the class already has |
456
900
  | `ApiRecipes::ApiConfigIsNotAnHash` | the second argument of `api` is not a Hash |
457
- | `ApiRecipes::RouteNameClashWithExistentMethod` | a nested endpoint has the name of an existing method, such as `url`, `run` or `name` |
458
- | `HTTP::TimeoutError`, `HTTP::ConnectionError` | http.rb network errors; these are `StandardError`s |
901
+ | `HTTP::TimeoutError`, `HTTP::ConnectionError` | http.rb network errors |
459
902
 
460
903
  ## Authorization
461
904
 
462
- Credentials are set on the API of the `ApiRecipes` module. They apply to every
463
- request to that API, including those made from classes that declare it.
905
+ A credential belongs to a level, and a request uses the nearest one. From the
906
+ nearest to the farthest:
907
+
908
+ 1. the chain, with `with(authorization: ...)` or `with(basic_auth: ...)`
909
+ 2. the object that makes the call
910
+ 3. its class, then the classes and modules it inherits from
911
+ 4. the API of the `ApiRecipes` module
464
912
 
465
- **A token**, sent as the `Authorization` header:
913
+ **A token**, sent as the `Authorization` header, as it is written:
466
914
 
467
915
  ```ruby
468
916
  ApiRecipes.github.authorization = "Bearer #{ENV.fetch('GITHUB_TOKEN')}"
@@ -474,37 +922,199 @@ ApiRecipes.github.authorization = "Bearer #{ENV.fetch('GITHUB_TOKEN')}"
474
922
  ApiRecipes.github.basic_auth = { user: 'me', pass: 'secret' }
475
923
  ```
476
924
 
477
- **A different token for one class**, through its own default headers:
925
+ **A different token for one class.** It applies to the class and its instances:
478
926
 
479
927
  ```ruby
480
928
  class AdminClient
481
929
  include ApiRecipes
482
- api :github, default_headers: { 'Authorization' => "Bearer #{ENV.fetch('ADMIN_TOKEN')}" }
930
+ api :github
931
+ end
932
+
933
+ AdminClient.github.authorization = "Bearer #{ENV.fetch('ADMIN_TOKEN')}"
934
+ ```
935
+
936
+ **A different token for one object**, for example one object per user:
937
+
938
+ ```ruby
939
+ class UserRepos
940
+ include ApiRecipes
941
+ api :github
942
+
943
+ def initialize(user)
944
+ github.authorization = "Bearer #{user.github_token}"
945
+ end
483
946
  end
484
947
  ```
485
948
 
486
- **A different token for one request**, for example the token of the current user:
949
+ **A different token for one chain**, for example the token of the current user:
950
+
951
+ ```ruby
952
+ ApiRecipes.github.with(authorization: "Bearer #{user.token}").users.repos('octocat').run
953
+ ```
954
+
955
+ The reader returns what the nearest level assigned:
487
956
 
488
957
  ```ruby
489
- ApiRecipes.github.users.repos('octocat', headers: { 'Authorization' => "Bearer #{user.token}" }).run
958
+ ApiRecipes.github.authorization = 'Bearer abc'
959
+ ApiRecipes.github.authorization
960
+ # => "Bearer abc"
490
961
  ```
491
962
 
492
- > Set credentials on `ApiRecipes.github`, not on `MyClass.github`. The second form
493
- > returns a new object at every call, so the value is lost.
963
+ **No credential.** Assigning `nil` means "send none" and ends the search: it
964
+ does not fall back to a level farther away. The same goes for
965
+ `with(authorization: nil)`:
966
+
967
+ ```ruby
968
+ AdminClient.github.authorization = nil # this class sends none
969
+ ApiRecipes.github.with(authorization: nil).users.run # this chain sends none
970
+ ```
971
+
972
+ `authorization=`, `basic_auth=` and `variables=` change the level of the object
973
+ they are called on. They raise on an API that `with` returned: use
974
+ `with(authorization: ...)` there.
975
+
976
+ A credential is valid only for the origin it was set for: the scheme, the host
977
+ and the port. If a nearer level changes the destination (its own `host`,
978
+ `protocol` or `port`, or a variable of the host) and does not set a credential of
979
+ its own, the request raises `ApiRecipes::CredentialOriginMismatch` instead of
980
+ sending the credential somewhere else. Set the credential where you change the
981
+ destination:
982
+
983
+ ```ruby
984
+ class EnterpriseClient
985
+ include ApiRecipes
986
+ api :github, host: 'github.example.com'
987
+ end
988
+
989
+ EnterpriseClient.github.authorization = "Bearer #{ENV.fetch('ENTERPRISE_TOKEN')}"
990
+ ```
991
+
992
+ An API or an endpoint kept in a variable keeps the destination it was created
993
+ with. If a later `configure` moves the API to another origin, a request made
994
+ through it raises the same error instead of sending a credential of the levels
995
+ to the old origin: ask `ApiRecipes` (or the class, or the object) for the API
996
+ again. A `configure` that does not move the origin changes nothing for it.
997
+
998
+ The readers `authorization` and `basic_auth` return the nearest credential that
999
+ was assigned. They do not apply that check: only a request does.
1000
+
1001
+ A credential with a line break or another control character raises
1002
+ `ApiRecipes::InvalidCredential`. The message never contains the value. A client
1003
+ restored from a serialized form has no credential.
1004
+
1005
+ An API can say where its credential goes with `auth`:
1006
+
1007
+ | `auth.type` | The credential assigned with `authorization=` goes |
1008
+ | --- | --- |
1009
+ | none of these, or `none`, `bearer`, `basic` | in the `Authorization` header, as it is written |
1010
+ | `header`, with a `name` | in the header called `name` |
1011
+ | `query`, with a `name` | in the query parameter called `name` |
1012
+
1013
+ ```yaml
1014
+ weather:
1015
+ host: api.weather.test
1016
+ auth:
1017
+ type: query
1018
+ name: api_key
1019
+ endpoints:
1020
+ forecast:
1021
+ ```
1022
+
1023
+ Basic auth cannot be sent to an API of type `header` or `query`: the request
1024
+ raises `ApiRecipes::InvalidCredential`. Assign the value with `authorization=`.
1025
+
1026
+ A credential written in `headers:` or in `default_headers` is sent as it is.
1027
+ ApiRecipes does not check its origin, so prefer the levels above.
494
1028
 
495
1029
  ## Logging and debugging
496
1030
 
497
1031
  ```ruby
498
1032
  ApiRecipes.configure do |config|
499
- config.logger = Rails.logger # any Logger; set it before the files
500
- config.print_urls = true # print every URL to STDOUT as it is built
1033
+ config.logger = Rails.logger # any Logger
1034
+ config.print_urls = true # log the URL of every request
501
1035
  config.apis_files_paths = ['config/apis/github.yml']
502
1036
  end
503
1037
  ```
504
1038
 
505
- Without `logger`, ApiRecipes logs to STDOUT at debug level. `config.log_to`
506
- (a path or an IO) and `config.log_level` (`:debug`, `:info`, `:warn`, `:error`,
507
- `:fatal`) change that without building a Logger.
1039
+ Without `logger`, ApiRecipes logs to STDERR at warn level, so normal use prints
1040
+ nothing and a problem shows up. `config.log_to` (a path or an IO) and
1041
+ `config.log_level` (`:debug`, `:info`, `:warn`, `:error`, `:fatal`) change that
1042
+ without building a Logger. Without `log_level`, the `LOG_LEVEL` environment
1043
+ variable is used, in any letter case; a value that is not a level is ignored.
1044
+
1045
+ - The level of the default logger is, in this order: `log_level`; the `LOG_LEVEL`
1046
+ variable; info when `print_urls` is on; otherwise warn. A level you chose is
1047
+ never lowered by `print_urls`. A logger you provide keeps its own level.
1048
+ - `print_urls = true` logs the URL of each request at info level.
1049
+ - At debug level, every request logs one line: the verb, the URL, the status and
1050
+ the time it took. A response with a bad status that raises is logged too. A
1051
+ request whose connection fails or times out logs nothing.
1052
+ - A log line never contains a query string, a header, a body or a credential.
1053
+ - `ApiRecipes.logger` is the logger in use, and `ApiRecipes.configuration` is the
1054
+ current configuration. Change the configuration only inside `configure`.
1055
+
1056
+ At the start, ApiRecipes logs one warning for each endpoint whose name cannot
1057
+ become a method, when the configuration is loaded (see
1058
+ [Good to know](#good-to-know)).
1059
+
1060
+ It also warns, once for each endpoint, when the value of a path parameter
1061
+ contains a `/` (it is sent as `%2F`) or looks already percent-encoded (it is
1062
+ encoded again). The warning names the endpoint and never the value.
1063
+ `config.upgrade_warnings = false` turns these two warnings off.
1064
+
1065
+ ## Inspecting an API
1066
+
1067
+ `inspect` is made for the console. It shows the name and the origin, and never a
1068
+ credential, a header, a body or a query string:
1069
+
1070
+ ```ruby
1071
+ ApiRecipes.github.inspect
1072
+ # => "#<ApiRecipes::Api github https://api.github.com endpoints: users, repos, search>"
1073
+
1074
+ ApiRecipes.github.users.show('octocat').inspect
1075
+ # => "#<ApiRecipes::Endpoint github.users.show GET https://api.github.com/users/octocat>"
1076
+ ```
1077
+
1078
+ `definition` returns a read-only description of an API or of an endpoint:
1079
+
1080
+ ```ruby
1081
+ ApiRecipes.github.definition.host
1082
+ # => "api.github.com"
1083
+
1084
+ ApiRecipes.github.users.show('octocat').definition.full_path
1085
+ # => "/users/:login"
1086
+ ```
1087
+
1088
+ For an API: `name`, `protocol`, `host`, `port`, `base_url`, `timeout`,
1089
+ `on_bad_code`, `mime_type`, `verify_with`, `default_headers`, `auth`,
1090
+ `variables`, `endpoints`, `routes` and `to_h`. For an endpoint: `name`,
1091
+ `full_name`, `path`, `full_path`, `path_params`, `verb`, `route?`, `ok_code`,
1092
+ `timeout`, `on_bad_code`, `mime_type`, `verify_with`, `parent`, `endpoints` and
1093
+ `to_h`. A definition never holds a credential assigned with `authorization=`,
1094
+ `basic_auth=` or `with`, nor the value of a variable. It does return the
1095
+ `default_headers` as they are configured, so do not write a credential there if
1096
+ you pass definitions around; `to_h` and `inspect` hide the values of the headers.
1097
+
1098
+ `routes` lists every endpoint that can be called, with the call that reaches it:
1099
+
1100
+ ```ruby
1101
+ route = ApiRecipes.github.definition.routes.find { |r| r.call.end_with?('.contributors') }
1102
+ [route.call, route.verb, route.url].join(' ')
1103
+ # => "github.repos(owner, repo).contributors get https://api.github.com/repos/:owner/:repo/contributors"
1104
+ ```
1105
+
1106
+ The command line gives the same list for the recipes in one or more files,
1107
+ which is handy after an import:
1108
+
1109
+ ```
1110
+ $ api_recipes routes config/apis/github.yml
1111
+ github.users GET https://api.github.com/users
1112
+ github.users.show(username) GET https://api.github.com/users/:username
1113
+ github.repos.issues(owner, repo).create POST https://api.github.com/repos/:owner/:repo/issues
1114
+ ```
1115
+
1116
+ A file that contains ERB is read only with `--erb`, because that runs the code
1117
+ in it.
508
1118
 
509
1119
  ## Recipes
510
1120
 
@@ -525,11 +1135,11 @@ ApiRecipes.github.authorization = "Bearer #{Rails.application.credentials.github
525
1135
  Keep one file and let ERB pick the values:
526
1136
 
527
1137
  ```yaml
528
- billing:
529
- protocol: <%= ENV.fetch('BILLING_PROTOCOL', 'https') %>
530
- host: <%= ENV.fetch('BILLING_HOST', 'billing.example.com') %>
1138
+ reports:
1139
+ protocol: <%= ENV.fetch('REPORTS_PROTOCOL', 'https') %>
1140
+ host: <%= ENV.fetch('REPORTS_HOST', 'reports.example.com') %>
531
1141
  endpoints:
532
- invoices:
1142
+ monthly:
533
1143
  ```
534
1144
 
535
1145
  ### Every page of a list
@@ -559,19 +1169,22 @@ response.code # => 201
559
1169
  response.data['number'] # => 1347
560
1170
  ```
561
1171
 
562
- ### A token per user in a multi-threaded application
1172
+ ### A token per user
563
1173
 
564
- Credentials set with `authorization=` are shared by the whole process. When each
565
- user has a token, pass it with the request instead:
1174
+ Give each user's object its own credential, or pass it with the chain, and the
1175
+ users never see each other's token:
566
1176
 
567
1177
  ```ruby
568
1178
  class UserRepos
1179
+ include ApiRecipes
1180
+ api :github
1181
+
569
1182
  def initialize(user)
570
- @headers = { 'Authorization' => "Bearer #{user.github_token}" }
1183
+ @token = user.github_token
571
1184
  end
572
1185
 
573
1186
  def names
574
- ApiRecipes.github.users.repos('octocat', headers: @headers).run.data.map { |repo| repo['name'] }
1187
+ github.with(authorization: "Bearer #{@token}").users.repos('octocat').run.data.map { |repo| repo['name'] }
575
1188
  end
576
1189
  end
577
1190
  ```
@@ -589,7 +1202,7 @@ status:
589
1202
 
590
1203
  ```ruby
591
1204
  def service_up?
592
- ApiRecipes.status.health.run.status.success?
1205
+ ApiRecipes.status.health.run.success?
593
1206
  rescue HTTP::Error # timeout, refused connection, DNS failure
594
1207
  false
595
1208
  end
@@ -628,8 +1241,8 @@ end
628
1241
  ```
629
1242
 
630
1243
  If your tests configure ApiRecipes themselves, `ApiRecipes.reset!` removes the
631
- global configuration and the API methods defined on the module, so each example
632
- can start clean:
1244
+ global configuration, the API methods defined on the module and every credential
1245
+ and variable value that was assigned, so each example can start clean:
633
1246
 
634
1247
  ```ruby
635
1248
  RSpec.configure do |config|
@@ -637,6 +1250,58 @@ RSpec.configure do |config|
637
1250
  end
638
1251
  ```
639
1252
 
1253
+ ## Security
1254
+
1255
+ What ApiRecipes does:
1256
+
1257
+ - **Path parameters** are encoded one by one. A value cannot add a segment, a
1258
+ query string or a fragment. `nil`, an empty value, `.` and `..` are refused.
1259
+ - **Variables** are checked for the place where they end up: a host, a path or a
1260
+ header.
1261
+ - **Credentials** are sent only to the origin they were set for, and a request
1262
+ that would send one elsewhere raises. A value with a control character is
1263
+ refused, so a credential cannot add a header.
1264
+ - **Redirects.** With `follow`, a redirect to another origin drops the
1265
+ credentials, the `Cookie` header and the credential query parameter. They are
1266
+ not sent again if the chain comes back.
1267
+ - **Before sending**, the address that http.rb will contact is checked against
1268
+ the origin that was validated.
1269
+ - **`api_recipes import`** reads one local file, follows only the references
1270
+ inside it, never uses the network and runs nothing of the description. Text of
1271
+ the description cannot add keys to the recipe and cannot become ERB in it.
1272
+ - **Logs, errors and `inspect`.** A log line and an error message of the gem
1273
+ never contain a credential, a header value, a body or a query string. Neither
1274
+ does the `inspect` or the `pp` of an API, an endpoint, a response, a
1275
+ definition or the configuration, nor their `to_s`, except that the `to_s` of
1276
+ a response is its body, as for the http.rb response. `definition` never holds
1277
+ a credential that was assigned with `authorization=`, `basic_auth=` or `with`.
1278
+ It does hold the values of `default_headers`, which its readers return; its
1279
+ `inspect`, its `to_h` and its JSON show them as `[FILTERED]`.
1280
+ - **Serialization.** An API, an endpoint and a response refuse `Marshal.dump`,
1281
+ `YAML.dump`, `as_json` and `to_json`, and raise `TypeError`: serialize
1282
+ `response.data` or `response.body.to_s` instead. A definition refuses
1283
+ `Marshal.dump` and `YAML.dump`, and its JSON is the one of `to_h`.
1284
+ - **`fill`** calls only public writers and skips keys that are not plain
1285
+ attribute names.
1286
+ - **Configuration files** are read with `YAML.safe_load`, and the options are
1287
+ validated when they are loaded.
1288
+
1289
+ What stays with your application:
1290
+
1291
+ - ApiRecipes checks the form of a host, not who owns it. Never pass a value
1292
+ chosen by an end user as a whole host: not in `with(host: ...)`, and not in a
1293
+ variable that is the entire host. Check it against a list of hosts you know. A
1294
+ variable that is only a part of a host, like the shop name in
1295
+ `{shop}.myshopify.com`, is the intended use.
1296
+ - `response.original_response` is the raw http.rb response, and it gives access
1297
+ to the request that was sent, headers included. Do not log or serialize it.
1298
+ - ERB in a configuration file runs code. Load only files you trust.
1299
+ - Do not put a credential in the source of an application or in a file of the
1300
+ repository: read it from the place where your application keeps secrets.
1301
+
1302
+ Every protection has an example in [`spec/security`](spec/security); its
1303
+ [README](spec/security/README.md) maps each one to the example that proves it.
1304
+
640
1305
  ## Options reference
641
1306
 
642
1307
  ### `ApiRecipes.configure`
@@ -645,24 +1310,28 @@ end
645
1310
  | --- | --- |
646
1311
  | `apis_files_paths` | Array of YAML files, evaluated with ERB |
647
1312
  | `apis_configs` | Hash of API descriptions |
1313
+ | `variables` | Hash of default variable values, as `{ api_name: { variable: value } }` |
648
1314
  | `logger` | a Logger to use |
649
- | `log_to` | path or IO for the default logger (default: STDOUT) |
650
- | `log_level` | level of the default logger (default: the `LOG_LEVEL` variable, or debug) |
651
- | `print_urls` | print each URL to STDOUT when it is built (default: false) |
1315
+ | `log_to` | path or IO for the default logger (default: STDERR) |
1316
+ | `log_level` | level of the default logger (default: the `LOG_LEVEL` variable, or warn) |
1317
+ | `print_urls` | log the URL of each request at info level (default: false) |
1318
+ | `upgrade_warnings` | warn when a path parameter value contains `/` or looks already percent-encoded (default: true) |
652
1319
 
653
1320
  ### API
654
1321
 
655
1322
  | Option | Default | Meaning |
656
1323
  | --- | --- | --- |
657
1324
  | `protocol` | `https` | `http` or `https` |
658
- | `host` | `localhost` | host name |
1325
+ | `host` | `localhost` | host name, which can contain `{variables}` |
659
1326
  | `port` | port of the protocol | port number |
660
- | `base_url` | none | prefix of every path, for example `api/v1` |
1327
+ | `base_url` | none | prefix of every path, for example `api/v1`; can contain `{variables}` |
661
1328
  | `timeout` | `3` | seconds allowed for the whole request |
662
- | `default_headers` | none | headers sent with every request |
1329
+ | `default_headers` | none | headers sent with every request; a value can contain `{variables}` |
663
1330
  | `on_bad_code` | `raise` | `raise` or `ignore` when the response is not a success |
664
1331
  | `mime_type` | from the response | content type used by `response.data` |
665
1332
  | `verify_with` | none | method that decides whether a response is a success |
1333
+ | `auth` | none | where the credential goes: `type` (`none`, `bearer`, `basic`, `header`, `query`) and `name` (for `header` and `query`) |
1334
+ | `variables` | none | the variables of the API, each with an optional `default` and `description` |
666
1335
  | `endpoints` | none | the endpoints of the API |
667
1336
 
668
1337
  ### Endpoint
@@ -672,7 +1341,7 @@ end
672
1341
  | `path` | the endpoint name | segment added to the parent path; `''` adds nothing |
673
1342
  | `verb` | `get` | HTTP verb |
674
1343
  | `route` | `yes` | `no` makes the endpoint a group that cannot be called |
675
- | `ok_code` | any 2xx | the only status accepted as a success |
1344
+ | `ok_code` | any 2xx | the status, or the list of statuses, accepted as a success |
676
1345
  | `timeout` | the API value | seconds allowed for the whole request |
677
1346
  | `on_bad_code` | the API value | `raise` or `ignore` |
678
1347
  | `mime_type` | the API value | content type used by `response.data` |
@@ -684,26 +1353,49 @@ the endpoint that contains it.
684
1353
 
685
1354
  ## Good to know
686
1355
 
687
- - **Configure before the first request.** A class keeps the configuration it saw
688
- the first time it used its API.
689
- - **Unknown options are ignored without a message.** If an option seems to have
690
- no effect, check its spelling: the verb is `verb`, not `method`.
691
- - **Path parameters are not encoded.** A value containing `/` spans two path
692
- segments, and `nil` or an empty string produce the URL of the parent
693
- (`/users/`). Check values that come from user input, and encode them with
694
- `ERB::Util.url_encode` when they can contain reserved characters.
695
- - **Credentials are shared by the whole process.** For a token per user, see
696
- [the recipe above](#a-token-per-user-in-a-multi-threaded-application).
697
- - **Some names are taken.** An endpoint cannot be called like a method its parent
698
- already has. Directly under the API, such an endpoint (`name`, `configs`,
699
- `object`) is skipped without a message; a nested one (`url`, `run`, `name`,
700
- `params`, `route`, `children`) raises `RouteNameClashWithExistentMethod`. An
701
- API must not be called `configure`, `configuration`, `logger` or `print_urls`:
702
- it would replace that method of the module.
703
- - **Core extensions.** The gem adds a few methods to `Hash` and `Array`
704
- (`deep_symbolize_keys`, `deep_merge`, `extract_options!` and similar, with the
705
- same behaviour as in ActiveSupport). With the uri gem older than 1.0 it also
706
- makes `URI` accept underscores in host names.
1356
+ - **Configure once, at startup.** Calling `configure` again replaces the whole
1357
+ configuration. A class sees the new configuration at its next call.
1358
+ - **Mistakes are reported, not ignored.** An unknown option, a wrong value or a
1359
+ verb that does not exist raises `ApiRecipes::ConfigurationError` when the
1360
+ configuration is loaded. The only free keys start with `x-`.
1361
+ - **Sharing a name.** An endpoint can have any name, and it is always reachable
1362
+ with `[]`. When the name is also a method of the object (`with`, `definition`,
1363
+ `authorization`, `basic_auth` or `variables` on an API; `run`, `url`, `with` or `definition`
1364
+ on an endpoint) or one of the names that Ruby and common libraries call on any
1365
+ object by themselves (`to_ary`, `to_str`, `to_json`...), no method is generated
1366
+ for it and ApiRecipes logs a warning when the configuration is loaded. Reach
1367
+ it with `[]`, as in `ApiRecipes.github[:with]`. Private methods of Ruby's
1368
+ `Kernel`, such as `test`, `open` and `format`, are not a problem. An API or an
1369
+ endpoint name cannot be empty or contain control characters.
1370
+ - **An API name can be a method of the module.** An API called `configure`,
1371
+ `configuration`, `logger`, `apis` or `reset!` gets no method of its own, so the
1372
+ method of the module keeps working, and a warning is logged. Reach the API with
1373
+ `ApiRecipes[:logger]`. In a class, `api :open` raises
1374
+ `ApiRecipes::ApiNameClashError` because `open` is already a method of the
1375
+ class: give the API another method name with `as:`.
1376
+ - **One declaration per API.** An API name is declared once in a class and its
1377
+ ancestors, modules included. A subclass that needs other options uses `with`.
1378
+ A credential or a variable set through one declaration is never seen by another
1379
+ declaration of the same API name.
1380
+ - **Serialization is refused.** An API, an endpoint and a response cannot be
1381
+ dumped with `Marshal` or `YAML`.
1382
+ - **Internationalized hosts.** A redirect to a host with non-ASCII characters
1383
+ needs the [addressable](https://github.com/sporkmonger/addressable) gem; without
1384
+ it http.rb raises `LoadError`.
1385
+ - **Constants seen by a class that includes `ApiRecipes`.** Ruby looks a constant
1386
+ up in the ancestors of a class before the top level, so inside a class that
1387
+ includes `ApiRecipes` the constants of the gem win over the constants of your
1388
+ application with the same name: `Api`, `Endpoint`, `Response`, `Configuration`,
1389
+ `Internals`, `VERSION`, `Error` and the error classes (`ApiConfigIsNotAnHash`,
1390
+ `ApiNameClashError`, `ConfigurationError`, `CredentialOriginMismatch`,
1391
+ `InvalidCredential`, `InvalidPathParameter`, `InvalidUrl`, `InvalidVariable`,
1392
+ `MissingVariable`, `NoRouteExists`, `PathParamsMismatch`, `RecipeFileError`,
1393
+ `ResponseCodeNotAsExpected` and `UnknownEndpoint`). If your application has a
1394
+ class with one of these names, write it with a leading `::` inside the classes
1395
+ that include `ApiRecipes`, for example `::Response`. The internal classes of
1396
+ the gem are all under `ApiRecipes::Internals`, so they hide nothing else.
1397
+ - **No changes to Ruby.** The gem adds no method to `Hash`, `Array` or any other
1398
+ class of Ruby, and does not touch `URI`.
707
1399
 
708
1400
  ## Runnable examples
709
1401
 
@@ -717,7 +1409,7 @@ The [`examples`](examples) folder contains scripts that call public APIs:
717
1409
  | `multiple_endpoints.rb` | two APIs from two files |
718
1410
  | `authorization.rb` | token authorization |
719
1411
  | `basic_auth.rb` | basic auth |
720
- | `authorization_with_default_headers.rb` | a token for one class, through default headers |
1412
+ | `authorization_for_a_class.rb` | a token for one class |
721
1413
 
722
1414
  Run one from the root of the repository:
723
1415
 
@@ -728,10 +1420,17 @@ configuration file with every option commented.
728
1420
 
729
1421
  ## Compatibility
730
1422
 
731
- - Ruby 2.7 or higher. The test suite runs on the maintained versions: 3.3, 3.4 and 4.0
732
- - http.rb from 4.4 to 5.x
1423
+ - Ruby 3.3 or higher. The test suite runs on the maintained versions: 3.3, 3.4 and 4.0
1424
+ - http.rb 6 (6.0.4 or higher)
733
1425
  - uri 0.x and 1.x
734
1426
 
1427
+ ## Upgrading from 2.x
1428
+
1429
+ [UPGRADING.md](UPGRADING.md) lists what stops with a message, what changes
1430
+ silently and what is new, and explains the `api_recipes upgrade` command, which
1431
+ looks for the changes in your code. A YAML file that is valid for 2.x keeps
1432
+ working, apart from the cases listed there.
1433
+
735
1434
  ## Development
736
1435
 
737
1436
  $ bundle install
@@ -742,8 +1441,11 @@ uri gem:
742
1441
 
743
1442
  $ URI_VERSION='~> 1.0' bundle exec rspec
744
1443
 
745
- What is planned for the next releases is in the [roadmap](docs/ROADMAP.md); the
746
- reasons behind the main design choices are in [docs/decisions](docs/decisions).
1444
+ The examples in this README and in UPGRADING.md are checked by
1445
+ `spec/docs/examples_spec.rb`. The protections described in the Security section
1446
+ are proved by the examples in [`spec/security`](spec/security).
1447
+
1448
+ What is planned for the next releases is in the [roadmap](docs/ROADMAP.md).
747
1449
 
748
1450
  Bug reports and pull requests are welcome on
749
1451
  [GitHub](https://github.com/madAle/api_recipes). Contributors are expected to