api_recipes 2.10.3 → 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.
data/README.md CHANGED
@@ -1,57 +1,1305 @@
1
- [![Code Climate](https://codeclimate.com/github/madAle/api_recipes/badges/gpa.svg)](https://codeclimate.com/github/madAle/api_recipes)
1
+ [![Gem Version](https://img.shields.io/gem/v/api_recipes)](https://rubygems.org/gems/api_recipes)
2
+ [![CI](https://github.com/madAle/api_recipes/actions/workflows/ci.yml/badge.svg)](https://github.com/madAle/api_recipes/actions/workflows/ci.yml)
2
3
 
3
4
  # ApiRecipes
4
5
 
5
- <p align="center">
6
+ <p align="center">
6
7
  <img width="300" height="160" src="api_recipes.png"/>
7
8
  </p>
8
9
 
9
- Create your HTTP APIs recipes and tastefully consume it!
10
+ Describe an HTTP API once, in YAML, and call it with plain Ruby methods.
11
+
12
+ ```ruby
13
+ ApiRecipes.github.users.repos('octocat') do |response|
14
+ response.data.each { |repo| puts repo['name'] }
15
+ end
16
+ # GET https://api.github.com/users/octocat/repos
17
+ # prints "Hello-World" and the other repository names
18
+ ```
19
+
20
+ There are no client classes to write. Hosts, paths, verbs, timeouts and expected
21
+ status codes live in a configuration file, and ApiRecipes turns them into a chain
22
+ of methods. Requests are made with [http.rb](https://github.com/httprb/http).
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
+
29
+ ## Contents
30
+
31
+ - [Installation](#installation)
32
+ - [Quick start](#quick-start)
33
+ - [Describing an API](#describing-an-api)
34
+ - [Variables](#variables)
35
+ - [Loading the configuration](#loading-the-configuration)
36
+ - [Where an API is available](#where-an-api-is-available)
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-)
40
+ - [Reading the response](#reading-the-response)
41
+ - [Deciding what counts as success](#deciding-what-counts-as-success)
42
+ - [Handling errors](#handling-errors)
43
+ - [Authorization](#authorization)
44
+ - [Logging and debugging](#logging-and-debugging)
45
+ - [Inspecting an API](#inspecting-an-api)
46
+ - [Recipes](#recipes)
47
+ - [Security](#security)
48
+ - [Options reference](#options-reference)
49
+ - [Good to know](#good-to-know)
50
+ - [Runnable examples](#runnable-examples)
51
+ - [Compatibility](#compatibility)
52
+ - [Upgrading from 2.x](#upgrading-from-2x)
53
+ - [Development](#development)
10
54
 
11
- Api recipes lets you easily describe and consume an HTTP API.
12
-
13
55
  ## Installation
14
56
 
15
- Add this line to your application's Gemfile:
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:
59
+
60
+ ```ruby
61
+ gem 'api_recipes', '>= 3.0.0.beta1'
62
+ ```
63
+
64
+ Or install it directly:
65
+
66
+ $ gem install api_recipes --pre
67
+
68
+ ## Quick start
69
+
70
+ **1. Describe the API** in a YAML file, for example `config/apis/github.yml`:
71
+
72
+ ```yaml
73
+ github:
74
+ host: api.github.com
75
+ endpoints:
76
+ users: # GET /users
77
+ endpoints:
78
+ show: # GET /users/:login
79
+ path: /:login
80
+ repos: # GET /users/:login/repos
81
+ path: /:login/repos
82
+ ```
83
+
84
+ **2. Load it** once, when your application starts:
85
+
86
+ ```ruby
87
+ require 'api_recipes'
88
+
89
+ ApiRecipes.configure do |config|
90
+ config.apis_files_paths = ['config/apis/github.yml']
91
+ end
92
+ ```
93
+
94
+ **3. Call it:**
95
+
96
+ ```ruby
97
+ response = ApiRecipes.github.users.show('octocat').run
98
+
99
+ response.code # => 200
100
+ response.data['name']
101
+ # => "The Octocat"
102
+ ```
103
+
104
+ Each endpoint in the file becomes a method, arguments fill the `:placeholders`
105
+ of the path, and `run` sends the request.
106
+
107
+ ## Describing an API
108
+
109
+ The examples in this guide share one configuration. It is longer than the quick
110
+ start because it shows every way of shaping an endpoint:
111
+
112
+ ```yaml
113
+ github:
114
+ host: api.github.com
115
+ default_headers:
116
+ Accept: application/vnd.github+json
117
+ endpoints:
118
+ users: # GET /users
119
+ endpoints:
120
+ show: # GET /users/:login
121
+ path: /:login
122
+ repos: # GET /users/:login/repos
123
+ path: /:login/repos
124
+ repos:
125
+ route: no # groups the endpoints below, is not callable itself
126
+ path: /repos/:owner/:repo
127
+ endpoints:
128
+ show: # GET /repos/:owner/:repo
129
+ path: ''
130
+ contributors: # GET /repos/:owner/:repo/contributors
131
+ contents: # GET /repos/:owner/:repo/contents/*path
132
+ path: /contents/*path
133
+ issues: # GET /repos/:owner/:repo/issues
134
+ endpoints:
135
+ create: # POST /repos/:owner/:repo/issues
136
+ path: ''
137
+ verb: post
138
+ ok_code: 201
139
+ search:
140
+ route: no
141
+ endpoints:
142
+ repositories: # GET /search/repositories
143
+ ```
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
+
151
+ ### How a path is built
152
+
153
+ The path of an endpoint is the path of its parent followed by its own segment:
154
+
155
+ | In the file | Segment added |
156
+ | --- | --- |
157
+ | no `path` | the endpoint name: `contributors` adds `/contributors` |
158
+ | `path: /something` | that text: `path: /:login/repos` adds `/:login/repos` |
159
+ | `path: ''` | nothing: the endpoint has the same URL as its parent |
160
+
161
+ `path: ''` is how two endpoints share a URL with different verbs, like `issues`
162
+ (GET) and `issues.create` (POST) above.
163
+
164
+ ### Path parameters
165
+
166
+ A `:name` in a path is a placeholder. Values are given, in order, to the method
167
+ of the endpoint whose `path` declares them:
168
+
169
+ ```ruby
170
+ ApiRecipes.github.users.show('octocat').url.to_s
171
+ # => "https://api.github.com/users/octocat"
172
+
173
+ ApiRecipes.github.repos('rails', 'rails').contributors.url.to_s
174
+ # => "https://api.github.com/repos/rails/rails/contributors"
175
+ ```
176
+
177
+ The wrong number of values raises `ApiRecipes::PathParamsMismatch`.
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
+
204
+ ### Endpoints that only group others
205
+
206
+ With `route: no` an endpoint exists only to hold nested endpoints. `search` above
207
+ is not callable, `search.repositories` is. Calling `run` on it raises
208
+ `ApiRecipes::NoRouteExists`.
209
+
210
+ ### Settings for the whole API
211
+
212
+ ```yaml
213
+ billing:
214
+ protocol: http # default: https
215
+ host: billing_service # underscores are accepted
216
+ port: 3000 # default: the port of the protocol
217
+ base_url: api/v1 # prefix of every path
218
+ timeout: 5 # seconds for the whole request, default: 3
219
+ default_headers:
220
+ Accept: application/json
221
+ endpoints:
222
+ invoices:
223
+ endpoints:
224
+ show:
225
+ path: /:id
226
+ ```
227
+
228
+ ```ruby
229
+ ApiRecipes.billing.invoices.show(42).url.to_s
230
+ # => "http://billing_service:3000/api/v1/invoices/42"
231
+ ```
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
+
237
+ All options are listed in the [options reference](#options-reference).
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
+
337
+ ## Loading the configuration
338
+
339
+ Configure ApiRecipes once, when your application starts.
340
+
341
+ ### From YAML files
342
+
343
+ ```ruby
344
+ ApiRecipes.configure do |config|
345
+ config.apis_files_paths = ['config/apis/github.yml', 'config/apis/billing.yml']
346
+ end
347
+ ```
348
+
349
+ A file can describe one API or several. If two files describe the same API, the
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.
357
+
358
+ Files are evaluated with ERB before being parsed, so values can come from the
359
+ environment:
360
+
361
+ ```yaml
362
+ billing:
363
+ host: <%= ENV.fetch('BILLING_HOST', 'billing.example.com') %>
364
+ timeout: <%= ENV.fetch('BILLING_TIMEOUT', 3) %>
365
+ endpoints:
366
+ invoices:
367
+ ```
368
+
369
+ Only files you wrote and trust should be loaded: ERB runs the Ruby code in them.
370
+
371
+ ### From a Hash
372
+
373
+ ```ruby
374
+ ApiRecipes.configure do |config|
375
+ config.apis_configs = {
376
+ github: {
377
+ host: 'api.github.com',
378
+ endpoints: {
379
+ users: { endpoints: { show: { path: '/:login' } } }
380
+ }
381
+ }
382
+ }
383
+ end
384
+ ```
385
+
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.
390
+
391
+ ## Where an API is available
392
+
393
+ ### On the `ApiRecipes` module
394
+
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:
397
+
398
+ ```ruby
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]"
408
+ ```
409
+
410
+ ### In your classes
411
+
412
+ Include the module and declare the APIs the class uses. They become available to
413
+ the class and to its instances:
414
+
415
+ ```ruby
416
+ class GithubProfile
417
+ include ApiRecipes
418
+ api :github
419
+
420
+ def self.all
421
+ github.users.run.data
422
+ end
423
+
424
+ def initialize(login)
425
+ @login = login
426
+ end
427
+
428
+ def repo_names
429
+ github.users.repos(@login).run.data.map { |repo| repo['name'] }
430
+ end
431
+ end
432
+ ```
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
+
448
+ ### With settings of its own
449
+
450
+ A class can change the configuration it uses. The Hash is merged over the global
451
+ one, so only the differences are needed:
452
+
453
+ ```ruby
454
+ class EnterpriseProfile
455
+ include ApiRecipes
456
+ api :github, host: 'github.example.com', timeout: 10
457
+ end
458
+
459
+ EnterpriseProfile.github.users.url.to_s
460
+ # => "https://github.example.com/users"
461
+ ```
462
+
463
+ A class can also declare an API that is not in the global configuration at all:
464
+
465
+ ```ruby
466
+ class Forecast
467
+ include ApiRecipes
468
+ api :weather, host: 'api.weather.test',
469
+ endpoints: { forecast: { path: '/forecast/:city' } }
470
+ end
471
+
472
+ Forecast.weather.forecast('rome').url.to_s
473
+ # => "https://api.weather.test/forecast/rome"
474
+ ```
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
+
480
+ ## Making requests
481
+
482
+ ### `run` or a block
483
+
484
+ `run` sends the request and returns the response:
485
+
486
+ ```ruby
487
+ response = ApiRecipes.github.users.show('octocat').run
488
+ ```
489
+
490
+ A block does the same and receives the response:
491
+
492
+ ```ruby
493
+ ApiRecipes.github.users.show('octocat') do |response|
494
+ puts response.data['name']
495
+ end
496
+ ```
497
+
498
+ Use `run` when you need the returned value: the block form returns the endpoint,
499
+ not the response. `run` with a block yields the response and returns it.
500
+
501
+ ### Query string, body and headers
502
+
503
+ After the path parameters, an endpoint method takes one Hash of request options.
504
+ They are the options of
505
+ [http.rb](https://github.com/httprb/http/wiki/Passing-Parameters):
506
+
507
+ | Option | Sends |
508
+ | --- | --- |
509
+ | `params:` | a query string |
510
+ | `json:` | a JSON body, with `Content-Type: application/json` |
511
+ | `form:` | a form-encoded body |
512
+ | `body:` | a raw body |
513
+ | `headers:` | extra headers for this request only |
514
+ | `follow:` | follow redirects: `true`, or a Hash with `strict`, `max_hops` and `on_redirect` |
515
+
516
+ ```ruby
517
+ # GET /search/repositories?q=api%20language:ruby&per_page=5
518
+ ApiRecipes.github.search.repositories(params: { q: 'api language:ruby', per_page: 5 }).run
519
+
520
+ # GET /users/octocat/repos?type=owner
521
+ ApiRecipes.github.users.repos('octocat', params: { type: 'owner' }).run
522
+
523
+ # POST /repos/rails/rails/issues with a JSON body
524
+ ApiRecipes.github.repos('rails', 'rails').issues.create(json: { title: 'Found a bug' }).run
525
+
526
+ # One more header, only for this request
527
+ ApiRecipes.github.users.show('octocat', headers: { 'X-Request-Id' => 'abc123' }).run
528
+ ```
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
+
540
+ ### Verbs
541
+
542
+ The verb is part of the endpoint description (`verb: post`, `put`, `patch`,
543
+ `delete`, `head`...). The default is `get`.
544
+
545
+ ### Looking at the URL without calling it
546
+
547
+ ```ruby
548
+ ApiRecipes.github.users.repos('octocat').url.to_s
549
+ # => "https://api.github.com/users/octocat/repos"
550
+ ```
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
+
605
+ ## Reading the response
606
+
607
+ `run` returns an `ApiRecipes::Response`. It adds `data` and forwards everything
608
+ else to the [http.rb response](https://github.com/httprb/http/wiki/Response-Handling):
609
+
610
+ ```ruby
611
+ response = ApiRecipes.github.users.show('octocat').run
612
+
613
+ response.data # => { "login" => "octocat", ... } parsed JSON
614
+ response.code # => 200
615
+ response.status.success? # => true
616
+ response.headers['Content-Type'] # => "application/json; charset=utf-8"
617
+ response.body.to_s # => "{\"login\":\"octocat\", ...}"
618
+ ```
619
+
620
+ `data` parses the body according to the `Content-Type` of the response. For
621
+ anything that is not JSON, or for an empty body, it raises `HTTP::Error`: read
622
+ `response.body.to_s` instead. If a server sends JSON with the wrong
623
+ `Content-Type`, set `mime_type: application/json` on the endpoint or on the API.
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
+
664
+ ## Deciding what counts as success
665
+
666
+ By default any 2xx status is a success and anything else raises
667
+ `ApiRecipes::ResponseCodeNotAsExpected`. Three options change that, for one
668
+ endpoint or for the whole API.
669
+
670
+ **Expect given statuses** with `ok_code`, one status or a list:
671
+
672
+ ```yaml
673
+ create:
674
+ path: ''
675
+ verb: post
676
+ ok_code: 201 # a 200 is now an error
677
+ ```
678
+
679
+ ```yaml
680
+ refresh:
681
+ ok_code: [200, 304]
682
+ ```
683
+
684
+ **Never raise** with `on_bad_code: ignore`, and inspect the response yourself:
685
+
686
+ ```yaml
687
+ health:
688
+ on_bad_code: ignore
689
+ ```
690
+
691
+ ```ruby
692
+ response = ApiRecipes.status.health.run
693
+ response.success? # => false, and no exception
694
+ ```
695
+
696
+ **Decide in Ruby** with `verify_with`, the name of a method of the object that
697
+ makes the call. It receives the response; a false or nil result makes the call
698
+ fail:
699
+
700
+ ```yaml
701
+ me:
702
+ path: /user
703
+ verify_with: valid_user?
704
+ ```
705
+
706
+ ```ruby
707
+ class Account
708
+ include ApiRecipes
709
+ api :github
710
+
711
+ def current
712
+ github.me.run.data
713
+ end
714
+
715
+ private
716
+
717
+ def valid_user?(response)
718
+ response.code == 200 && response.data.key?('login')
719
+ end
720
+ end
721
+ ```
722
+
723
+ The method can be private. It is looked up on the caller, so `verify_with` is
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.
726
+
727
+ ## Handling errors
728
+
729
+ ```ruby
730
+ begin
731
+ ApiRecipes.github.users.show('nobody-here').run
732
+ rescue ApiRecipes::ResponseCodeNotAsExpected => e
733
+ e.response.code # => 404
734
+ e.response.data # => { "message" => "Not Found", ... }
735
+ e.path # => "/users/nobody-here"
736
+ e.expected_code # => "200 <= CODE < 300"
737
+ rescue HTTP::TimeoutError
738
+ # the request took longer than `timeout`
739
+ rescue HTTP::ConnectionError
740
+ # the server could not be reached
741
+ end
742
+ ```
743
+
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`.
748
+
749
+ | Error | Raised when |
750
+ | --- | --- |
751
+ | `ApiRecipes::ResponseCodeNotAsExpected` | the response is not a success; has `response`, `path` and `expected_code` |
752
+ | `ApiRecipes::PathParamsMismatch` | an endpoint gets the wrong number of path parameters |
753
+ | `ApiRecipes::InvalidPathParameter` | a path parameter is `nil`, empty, `.` or `..` |
754
+ | `ApiRecipes::NoRouteExists` | `run` is called on an endpoint with `route: no` |
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 |
764
+ | `ApiRecipes::ApiConfigIsNotAnHash` | the second argument of `api` is not a Hash |
765
+ | `HTTP::TimeoutError`, `HTTP::ConnectionError` | http.rb network errors |
766
+
767
+ ## Authorization
768
+
769
+ A credential belongs to a level, and a request uses the nearest one. From the
770
+ nearest to the farthest:
771
+
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:
778
+
779
+ ```ruby
780
+ ApiRecipes.github.authorization = "Bearer #{ENV.fetch('GITHUB_TOKEN')}"
781
+ ```
782
+
783
+ **Basic auth:**
784
+
785
+ ```ruby
786
+ ApiRecipes.github.basic_auth = { user: 'me', pass: 'secret' }
787
+ ```
788
+
789
+ **A different token for one class.** It applies to the class and its instances:
790
+
791
+ ```ruby
792
+ class AdminClient
793
+ include ApiRecipes
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
810
+ end
811
+ ```
812
+
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)`:
830
+
831
+ ```ruby
832
+ AdminClient.github.authorization = nil # this class sends none
833
+ ApiRecipes.github.with(authorization: nil).users.run # this chain sends none
834
+ ```
835
+
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.
892
+
893
+ ## Logging and debugging
894
+
895
+ ```ruby
896
+ ApiRecipes.configure do |config|
897
+ config.logger = Rails.logger # any Logger
898
+ config.print_urls = true # log the URL of every request
899
+ config.apis_files_paths = ['config/apis/github.yml']
900
+ end
901
+ ```
902
+
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
+ ```
969
+
970
+ ## Recipes
971
+
972
+ ### Rails setup
973
+
974
+ ```ruby
975
+ # config/initializers/api_recipes.rb
976
+ ApiRecipes.configure do |config|
977
+ config.logger = Rails.logger
978
+ config.apis_files_paths = Dir[Rails.root.join('config', 'apis', '*.yml').to_s]
979
+ end
980
+
981
+ ApiRecipes.github.authorization = "Bearer #{Rails.application.credentials.github_token}"
982
+ ```
983
+
984
+ ### One host per environment
985
+
986
+ Keep one file and let ERB pick the values:
987
+
988
+ ```yaml
989
+ reports:
990
+ protocol: <%= ENV.fetch('REPORTS_PROTOCOL', 'https') %>
991
+ host: <%= ENV.fetch('REPORTS_HOST', 'reports.example.com') %>
992
+ endpoints:
993
+ monthly:
994
+ ```
995
+
996
+ ### Every page of a list
997
+
998
+ ```ruby
999
+ def all_repos(login)
1000
+ repos = []
1001
+ page = 1
1002
+ loop do
1003
+ batch = ApiRecipes.github.users.repos(login, params: { per_page: 100, page: page }).run.data
1004
+ repos.concat(batch)
1005
+ break if batch.size < 100
1006
+ page += 1
1007
+ end
1008
+ repos
1009
+ end
1010
+ ```
1011
+
1012
+ ### Creating a resource
16
1013
 
17
1014
  ```ruby
18
- gem 'api_recipes'
1015
+ response = ApiRecipes.github.repos('rails', 'rails').issues.create(
1016
+ json: { title: 'Found a bug', labels: ['bug'] }
1017
+ ).run
1018
+
1019
+ response.code # => 201
1020
+ response.data['number'] # => 1347
19
1021
  ```
20
1022
 
21
- And then execute:
1023
+ ### A token per user
1024
+
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:
22
1027
 
23
- $ bundle
1028
+ ```ruby
1029
+ class UserRepos
1030
+ include ApiRecipes
1031
+ api :github
24
1032
 
25
- Or install it yourself as:
1033
+ def initialize(user)
1034
+ @token = user.github_token
1035
+ end
1036
+
1037
+ def names
1038
+ github.with(authorization: "Bearer #{@token}").users.repos('octocat').run.data.map { |repo| repo['name'] }
1039
+ end
1040
+ end
1041
+ ```
1042
+
1043
+ ### A health check that never raises
1044
+
1045
+ ```yaml
1046
+ status:
1047
+ host: status.example.com
1048
+ timeout: 1
1049
+ on_bad_code: ignore
1050
+ endpoints:
1051
+ health:
1052
+ ```
1053
+
1054
+ ```ruby
1055
+ def service_up?
1056
+ ApiRecipes.status.health.run.success?
1057
+ rescue HTTP::Error # timeout, refused connection, DNS failure
1058
+ false
1059
+ end
1060
+ ```
1061
+
1062
+ ### Returning nil when a record does not exist
1063
+
1064
+ ```ruby
1065
+ def find_user(login)
1066
+ ApiRecipes.github.users.show(login).run.data
1067
+ rescue ApiRecipes::ResponseCodeNotAsExpected => e
1068
+ raise unless e.response.code == 404
1069
+ nil
1070
+ end
1071
+ ```
1072
+
1073
+ ### Testing code that uses ApiRecipes
1074
+
1075
+ Stub the HTTP layer with [WebMock](https://github.com/bblimke/webmock); nothing in
1076
+ ApiRecipes needs to be mocked. Send a `Content-Type`, or `data` cannot parse the
1077
+ body:
1078
+
1079
+ ```ruby
1080
+ require 'webmock/rspec'
1081
+
1082
+ RSpec.describe GithubProfile do
1083
+ it 'lists the repository names' do
1084
+ stub_request(:get, 'https://api.github.com/users/octocat/repos')
1085
+ .to_return(status: 200,
1086
+ body: [{ name: 'hello-world' }].to_json,
1087
+ headers: { 'Content-Type' => 'application/json' })
1088
+
1089
+ expect(GithubProfile.new('octocat').repo_names).to eq(['hello-world'])
1090
+ end
1091
+ end
1092
+ ```
1093
+
1094
+ If your tests configure ApiRecipes themselves, `ApiRecipes.reset!` removes the
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:
1097
+
1098
+ ```ruby
1099
+ RSpec.configure do |config|
1100
+ config.before(:each) { ApiRecipes.reset! }
1101
+ end
1102
+ ```
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
+
1153
+ ## Options reference
1154
+
1155
+ ### `ApiRecipes.configure`
1156
+
1157
+ | Option | Meaning |
1158
+ | --- | --- |
1159
+ | `apis_files_paths` | Array of YAML files, evaluated with ERB |
1160
+ | `apis_configs` | Hash of API descriptions |
1161
+ | `variables` | Hash of default variable values, as `{ api_name: { variable: value } }` |
1162
+ | `logger` | a Logger to use |
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) |
1167
+
1168
+ ### API
1169
+
1170
+ | Option | Default | Meaning |
1171
+ | --- | --- | --- |
1172
+ | `protocol` | `https` | `http` or `https` |
1173
+ | `host` | `localhost` | host name, which can contain `{variables}` |
1174
+ | `port` | port of the protocol | port number |
1175
+ | `base_url` | none | prefix of every path, for example `api/v1`; can contain `{variables}` |
1176
+ | `timeout` | `3` | seconds allowed for the whole request |
1177
+ | `default_headers` | none | headers sent with every request; a value can contain `{variables}` |
1178
+ | `on_bad_code` | `raise` | `raise` or `ignore` when the response is not a success |
1179
+ | `mime_type` | from the response | content type used by `response.data` |
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` |
1183
+ | `endpoints` | none | the endpoints of the API |
1184
+
1185
+ ### Endpoint
1186
+
1187
+ | Option | Default | Meaning |
1188
+ | --- | --- | --- |
1189
+ | `path` | the endpoint name | segment added to the parent path; `''` adds nothing |
1190
+ | `verb` | `get` | HTTP verb |
1191
+ | `route` | `yes` | `no` makes the endpoint a group that cannot be called |
1192
+ | `ok_code` | any 2xx | the status, or the list of statuses, accepted as a success |
1193
+ | `timeout` | the API value | seconds allowed for the whole request |
1194
+ | `on_bad_code` | the API value | `raise` or `ignore` |
1195
+ | `mime_type` | the API value | content type used by `response.data` |
1196
+ | `verify_with` | the API or parent value | method that decides whether a response is a success |
1197
+ | `endpoints` | none | nested endpoints |
1198
+
1199
+ An endpoint takes `timeout`, `on_bad_code` and `mime_type` from the API, not from
1200
+ the endpoint that contains it.
1201
+
1202
+ ## Good to know
1203
+
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`.
1247
+
1248
+ ## Runnable examples
1249
+
1250
+ The [`examples`](examples) folder contains scripts that call public APIs:
1251
+
1252
+ | Script | Shows |
1253
+ | --- | --- |
1254
+ | `simple_usage.rb` | configuration from a YAML file; class, instance and module access |
1255
+ | `direct_configuration.rb` | an API described directly in a class |
1256
+ | `manual_configs.rb` | configuration from a Hash; nested endpoints with path parameters |
1257
+ | `multiple_endpoints.rb` | two APIs from two files |
1258
+ | `authorization.rb` | token authorization |
1259
+ | `basic_auth.rb` | basic auth |
1260
+ | `authorization_for_a_class.rb` | a token for one class |
1261
+
1262
+ Run one from the root of the repository:
1263
+
1264
+ $ bundle exec ruby examples/simple_usage.rb
1265
+
1266
+ [`examples/config/github.yml.erb`](examples/config/github.yml.erb) is a
1267
+ configuration file with every option commented.
26
1268
 
27
- $ gem install api_recipes
28
-
29
1269
  ## Compatibility
30
1270
 
31
- Ruby 2.7.0 or higher.
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)
1273
+ - uri 0.x and 1.x
32
1274
 
33
- ## Usage
1275
+ ## Upgrading from 2.x
34
1276
 
35
- Help needed.
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.
36
1281
 
37
- In the meantime take a look at the ``` examples ``` folder. Thank you.
1282
+ ## Development
38
1283
 
39
- ## TODO
1284
+ $ bundle install
1285
+ $ bundle exec rspec
40
1286
 
41
- * Re-write specs
42
- * Write a good Usage
43
- * Add more examples
44
- * Add documentation
45
- * Delete this TODO section
1287
+ The specs never use the network. To run them against a specific version of the
1288
+ uri gem:
46
1289
 
47
- ## Contributing
1290
+ $ URI_VERSION='~> 1.0' bundle exec rspec
48
1291
 
49
- Bug reports and pull requests are welcome on GitHub at https://github.com/madAle/api_recipes.
50
- This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to
51
- the [Contributor Covenant](contributor-covenant.org) code of conduct.
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).
52
1295
 
1296
+ What is planned for the next releases is in the [roadmap](docs/ROADMAP.md).
53
1297
 
54
- ## License
1298
+ Bug reports and pull requests are welcome on
1299
+ [GitHub](https://github.com/madAle/api_recipes). Contributors are expected to
1300
+ follow the [Contributor Covenant](CODE_OF_CONDUCT.md).
55
1301
 
56
- The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
1302
+ ## License
57
1303
 
1304
+ The gem is available as open source under the terms of the
1305
+ [MIT License](http://opensource.org/licenses/MIT).