ampost 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/CHANGELOG.md +7 -0
- data/LICENSE +21 -0
- data/README.md +281 -0
- data/lib/ampost/client.rb +215 -0
- data/lib/ampost/errors.rb +162 -0
- data/lib/ampost/generated/resources.rb +922 -0
- data/lib/ampost/media.rb +130 -0
- data/lib/ampost/page.rb +85 -0
- data/lib/ampost/resource.rb +28 -0
- data/lib/ampost/transport.rb +56 -0
- data/lib/ampost/version.rb +5 -0
- data/lib/ampost.rb +19 -0
- metadata +63 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 3f90b464b10a44a8c6f9ca948c13accc8b68980e360b998a9f64190d6cb5e5e7
|
|
4
|
+
data.tar.gz: 585acc7eac2e151680ecf0022636bcc92cce33b33809da05cf2792a281ec4082
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: d74592339f9b17c951421ca34a4f6c6aeeabea1a8b7e244a60617b9f7a1946d37dc382ab07d9b65c9cc9ea47a6f196f3e78aa8dd6184c60538bc355d4524f0a8
|
|
7
|
+
data.tar.gz: 754699ac421b2e03d6cfb82ce14b3214ded3e4aa02426b2c9d8acd34a78bacc06b83fce626f441595fb646fc9ddfbf8a4ccc562633944de669252ea8cbb4c71c
|
data/CHANGELOG.md
ADDED
data/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Amlabs Artur Muszyński (Ampost)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
data/README.md
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
# Ampost Ruby SDK
|
|
2
|
+
|
|
3
|
+
The official Ruby client for the [Ampost API](https://ampost.io/docs?ref=github): publish, schedule
|
|
4
|
+
and track posts on Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky, Telegram and Discord
|
|
5
|
+
with one call.
|
|
6
|
+
|
|
7
|
+
- Every endpoint, generated from the [OpenAPI document](https://api.ampost.io/openapi.json), with YARD docs
|
|
8
|
+
- Retries on 429 and 5xx with `Retry-After`, automatic `Idempotency-Key`s, typed errors
|
|
9
|
+
- Pagination with `each` and a one-call media upload
|
|
10
|
+
- Ruby 3.1+, no runtime dependencies (`net/http` and `json` from the standard library)
|
|
11
|
+
|
|
12
|
+
## Install
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
gem install ampost
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Or in your `Gemfile`:
|
|
19
|
+
|
|
20
|
+
```ruby
|
|
21
|
+
gem "ampost"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Until the gem is on RubyGems, install it from this repo: `gem "ampost", github: "ampost-io/ampost-ruby"`.
|
|
25
|
+
|
|
26
|
+
## Quick start
|
|
27
|
+
|
|
28
|
+
Create an API key in [Settings, API keys](https://ampost.io/app/settings/api-keys?ref=github), connect
|
|
29
|
+
Bluesky and Threads in the [dashboard](https://ampost.io/app?ref=github), then:
|
|
30
|
+
|
|
31
|
+
```ruby
|
|
32
|
+
require "ampost"
|
|
33
|
+
|
|
34
|
+
client = Ampost::Client.new(api_key: ENV.fetch("AMPOST_API_KEY"))
|
|
35
|
+
|
|
36
|
+
post = client.posts.create({
|
|
37
|
+
text: "Hello from the Ampost API 👋",
|
|
38
|
+
targets: [{ platforms: ["bluesky", "threads"] }],
|
|
39
|
+
publishNow: true
|
|
40
|
+
})
|
|
41
|
+
puts post["id"], post["status"]
|
|
42
|
+
post["platformPosts"].each { |p| puts "#{p["platform"]}: #{p["status"]}" }
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Request bodies are Hashes with the API's field names (`publishNow`, `scheduledFor`), with symbol or
|
|
46
|
+
string keys; pass them in braces, as above. Responses are Hashes with string keys, exactly as the
|
|
47
|
+
[API docs](https://ampost.io/docs?ref=github) show them.
|
|
48
|
+
|
|
49
|
+
Leave out `publishNow` for a draft, or schedule the post (paid plans):
|
|
50
|
+
|
|
51
|
+
```ruby
|
|
52
|
+
client.posts.create({
|
|
53
|
+
text: "See you at the launch",
|
|
54
|
+
targets: [{ platforms: ["bluesky"] }],
|
|
55
|
+
scheduledFor: Time.utc(2026, 12, 1, 9) # or "2026-12-01T09:00:00Z"
|
|
56
|
+
})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Check a post against every platform's rules and your accounts without creating it:
|
|
60
|
+
|
|
61
|
+
```ruby
|
|
62
|
+
result = client.posts.validate({ text: "x" * 400, targets: [{ platforms: ["bluesky"] }] })
|
|
63
|
+
result["valid"] # => false, with the reasons in result["errors"] and result["targets"]
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
List your connected accounts:
|
|
67
|
+
|
|
68
|
+
```ruby
|
|
69
|
+
client.accounts.list.each do |account|
|
|
70
|
+
puts "#{account["platform"]} #{account["status"]}"
|
|
71
|
+
end
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Authentication
|
|
75
|
+
|
|
76
|
+
Every request sends the key as `Authorization: Bearer <key>`. Without `api_key:` the client reads
|
|
77
|
+
`AMPOST_API_KEY`, and `AMPOST_BASE_URL` overrides `https://api.ampost.io`.
|
|
78
|
+
|
|
79
|
+
```ruby
|
|
80
|
+
client = Ampost::Client.new(
|
|
81
|
+
api_key: "amp_...",
|
|
82
|
+
base_url: "https://api.ampost.io",
|
|
83
|
+
max_retries: 2, # after a 429, a 5xx or a network error
|
|
84
|
+
timeout: 60 # seconds per attempt
|
|
85
|
+
)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
A key has scopes (`posts:write`, `analytics:read`, ...) and can be limited to some platform sets. A
|
|
89
|
+
call outside them raises `Ampost::PermissionDeniedError` with `code` `INSUFFICIENT_SCOPE` or
|
|
90
|
+
`PLATFORM_SET_NOT_ALLOWED`. See [scopes](https://ampost.io/docs?ref=github#scopes).
|
|
91
|
+
|
|
92
|
+
The client holds no connection (each request opens its own), so one client can be shared between
|
|
93
|
+
threads. Proxies come from `https_proxy` as usual for `Net::HTTP`.
|
|
94
|
+
|
|
95
|
+
## Media upload
|
|
96
|
+
|
|
97
|
+
`media.upload` takes a path, a `Pathname` or an IO (`File`, `StringIO`), sends the file straight to
|
|
98
|
+
storage (your API key is not sent there), waits until Ampost has checked it and returns a `media` item:
|
|
99
|
+
|
|
100
|
+
```ruby
|
|
101
|
+
video = client.media.upload("launch.mp4")
|
|
102
|
+
client.posts.create({
|
|
103
|
+
text: "We launched 🚀",
|
|
104
|
+
media: [video],
|
|
105
|
+
targets: [{ platforms: ["youtube", "threads"] }],
|
|
106
|
+
options: { youtube: { title: "Launch day" } }
|
|
107
|
+
})
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
The MIME type comes from the file name; pass `content_type:` (and `file_name:` for an IO) otherwise.
|
|
111
|
+
Public URLs work without an upload: `media: [{ url: "https://example.com/a.jpg", type: "image" }]`.
|
|
112
|
+
For files on a user's device, show `uploadPageUrl` from `client.media.create_upload` and call
|
|
113
|
+
`client.media.wait_for_upload(upload_id)`. A refused or expired upload raises `Ampost::MediaUploadError`
|
|
114
|
+
with a `reason`. See [media upload](https://ampost.io/docs?ref=github#media-upload).
|
|
115
|
+
|
|
116
|
+
## Errors
|
|
117
|
+
|
|
118
|
+
Every API error is `{"error": {"code", "message", "details"}}`, raised as a subclass of `Ampost::APIError`:
|
|
119
|
+
|
|
120
|
+
```ruby
|
|
121
|
+
begin
|
|
122
|
+
client.posts.create({ text: "x" * 500, targets: [{ platforms: ["bluesky"] }] })
|
|
123
|
+
rescue Ampost::BadRequestError => e
|
|
124
|
+
puts e.code, e.details # CONTENT_TOO_LONG, ...
|
|
125
|
+
rescue Ampost::RateLimitError => e
|
|
126
|
+
puts "retry in #{e.retry_after} s"
|
|
127
|
+
rescue Ampost::APIError => e
|
|
128
|
+
puts e.status, e.code, e.api_message, e.request_id
|
|
129
|
+
end
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
| Status | Class | Typical `code` |
|
|
133
|
+
| ------ | ----- | -------------- |
|
|
134
|
+
| 400 | `BadRequestError` | `VALIDATION_FAILED`, `CONTENT_TOO_LONG`, `PLATFORM_NOT_CONNECTED` |
|
|
135
|
+
| 401 | `AuthenticationError` | `UNAUTHORIZED` |
|
|
136
|
+
| 403 | `PermissionDeniedError` | `INSUFFICIENT_SCOPE`, `UPGRADE_REQUIRED`, `PLATFORM_COMING_SOON` |
|
|
137
|
+
| 404 | `NotFoundError` | `POST_NOT_FOUND`, `ACCOUNT_NOT_FOUND` |
|
|
138
|
+
| 409 | `ConflictError` | `INVALID_STATUS_TRANSITION`, `IDEMPOTENCY_KEY_REUSED` |
|
|
139
|
+
| 413 | `PayloadTooLargeError` | `PAYLOAD_TOO_LARGE` |
|
|
140
|
+
| 422 | `UnprocessableEntityError` | `ANALYTICS_NOT_AVAILABLE_ON_PLATFORM` |
|
|
141
|
+
| 429 | `RateLimitError` | `RATE_LIMITED`, `QUOTA_EXCEEDED` |
|
|
142
|
+
| 5xx | `InternalServerError` | `INTERNAL_ERROR`, `PLATFORM_REQUEST_FAILED` |
|
|
143
|
+
|
|
144
|
+
`e.message` is `"<status> <code>: <message>"`; `e.api_message` is the API's message alone. No
|
|
145
|
+
response at all is `Ampost::APIConnectionError` (`Ampost::APITimeoutError` after `timeout`). All of
|
|
146
|
+
them extend `Ampost::Error`. Quote `e.request_id` when you contact support. Every code is listed in
|
|
147
|
+
[the docs](https://ampost.io/docs?ref=github#errors).
|
|
148
|
+
|
|
149
|
+
A post that was accepted can still fail on one platform: check `post["platformPosts"][i]["status"]` and
|
|
150
|
+
`["error"]`, or subscribe to webhooks (below).
|
|
151
|
+
|
|
152
|
+
## Idempotency
|
|
153
|
+
|
|
154
|
+
`posts.create`, `posts.publish`, `posts.retry`, `posts.import_csv`, `accounts.connect`,
|
|
155
|
+
`platform_sets.create`, `webhooks.create` and `feedback.submit` take an `Idempotency-Key`. The SDK
|
|
156
|
+
sends a new key with each call and keeps it across that call's retries, so a retried request never
|
|
157
|
+
posts twice. To stay safe across restarts too (a cron job, a Sidekiq worker), pass your own key:
|
|
158
|
+
|
|
159
|
+
```ruby
|
|
160
|
+
client.posts.create(
|
|
161
|
+
{ text: "v1.4.0 is out", targets: [{ platforms: ["bluesky"] }], publishNow: true },
|
|
162
|
+
idempotency_key: "release-v1.4.0"
|
|
163
|
+
)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The same key with the same request returns the first result for 24 hours; with a different request
|
|
167
|
+
it is `Ampost::ConflictError` `IDEMPOTENCY_KEY_REUSED`. See
|
|
168
|
+
[idempotency](https://ampost.io/docs?ref=github#idempotency).
|
|
169
|
+
|
|
170
|
+
## Retries
|
|
171
|
+
|
|
172
|
+
| What happened | Retried? |
|
|
173
|
+
| ------------- | -------- |
|
|
174
|
+
| 429 `RATE_LIMITED`, `QUOTA_EXCEEDED` | Yes, after `Retry-After`, if it is under `max_retry_delay` (60 s) |
|
|
175
|
+
| 409 `IDEMPOTENCY_REQUEST_IN_PROGRESS` | Yes |
|
|
176
|
+
| 5xx, timeout, network error | Reads and calls with an `Idempotency-Key` only |
|
|
177
|
+
| Anything else | No |
|
|
178
|
+
|
|
179
|
+
Waits without `Retry-After` back off from 0.5 s to 8 s. Set `max_retries:` on the client or per call:
|
|
180
|
+
`client.posts.get(post_id, max_retries: 0)`. Every method also takes `timeout:` and `extra_headers:`.
|
|
181
|
+
|
|
182
|
+
## Pagination
|
|
183
|
+
|
|
184
|
+
List methods return an `Ampost::Page`: `data` is the first page, and `each` (with every `Enumerable`
|
|
185
|
+
method) walks every item, fetching the next pages as it goes:
|
|
186
|
+
|
|
187
|
+
```ruby
|
|
188
|
+
page = client.posts.list(status: "failed", limit: 50)
|
|
189
|
+
page.data # this page
|
|
190
|
+
page.total # items across all pages
|
|
191
|
+
page.next_page? # => true / false
|
|
192
|
+
|
|
193
|
+
client.posts.list(status: "failed").each do |post|
|
|
194
|
+
client.posts.retry(post["id"])
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
client.accounts.list.first(5) # fetches only the pages it needs
|
|
198
|
+
client.posts.list.each_page { |p| puts p.size }
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
Query parameters are keyword arguments in snake_case: `platform_set_id:` for `platformSetId`.
|
|
202
|
+
|
|
203
|
+
## Webhooks
|
|
204
|
+
|
|
205
|
+
Subscribe a URL to events instead of polling:
|
|
206
|
+
|
|
207
|
+
```ruby
|
|
208
|
+
webhook = client.webhooks.create({
|
|
209
|
+
url: "https://example.com/ampost/webhooks",
|
|
210
|
+
events: ["post.published", "post.failed", "account.needs_reconnect"]
|
|
211
|
+
})
|
|
212
|
+
secret = webhook["secret"] # shown only in this response: store it
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
`client.webhooks.list`, `get`, `update`, `delete`, `test`, `list_deliveries` and `redeliver` manage
|
|
216
|
+
them. Ampost signs each delivery: `Ampost-Signature` is `sha256=` plus the hex HMAC-SHA256 of
|
|
217
|
+
`<Ampost-Timestamp>.<raw body>` with the webhook's secret. Check it on the raw body, before parsing:
|
|
218
|
+
|
|
219
|
+
```ruby
|
|
220
|
+
require "openssl"
|
|
221
|
+
|
|
222
|
+
# raw_body: the request body as received (request.raw_post in Rails), before JSON.parse.
|
|
223
|
+
def verify_ampost_webhook(raw_body, timestamp, signature, secret)
|
|
224
|
+
return false unless timestamp.to_s.match?(/\A\d+\z/) && signature
|
|
225
|
+
# Reject old requests so a captured one cannot be replayed.
|
|
226
|
+
return false if (Time.now.to_i - timestamp.to_i).abs > 300
|
|
227
|
+
|
|
228
|
+
expected = "sha256=#{OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp}.#{raw_body}")}"
|
|
229
|
+
expected.bytesize == signature.bytesize && OpenSSL.fixed_length_secure_compare(expected, signature)
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
# In a Rails controller:
|
|
233
|
+
# verify_ampost_webhook(request.raw_post, request.headers["Ampost-Timestamp"],
|
|
234
|
+
# request.headers["Ampost-Signature"], ENV["AMPOST_WEBHOOK_SECRET"])
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Events and their `data` are in [webhooks](https://ampost.io/docs?ref=github#webhooks).
|
|
238
|
+
|
|
239
|
+
## Everything else
|
|
240
|
+
|
|
241
|
+
Each tag of the API is a reader on the client: `posts`, `accounts`, `platform_sets` (and posting
|
|
242
|
+
queues), `media`, `analytics`, `webhooks`, `platforms`, `docs`, `feedback`, with one method per
|
|
243
|
+
operation. Every method's YARD docs list its parameters and body fields, from the OpenAPI document.
|
|
244
|
+
`Ampost::OPERATIONS` lists them all with their HTTP method and path.
|
|
245
|
+
|
|
246
|
+
`client.platforms.list` returns each platform's limits and options. AI agents can use the same API
|
|
247
|
+
through the hosted MCP server at `https://api.ampost.io/mcp` ([setup](https://ampost.io/docs/mcp?ref=github)).
|
|
248
|
+
|
|
249
|
+
To send requests through your own HTTP code (instrumentation, another HTTP library), pass
|
|
250
|
+
`transport:`, an object whose `call(request)` takes an `Ampost::Transport::Request` and returns an
|
|
251
|
+
`Ampost::Transport::Response`; see `lib/ampost/transport.rb`.
|
|
252
|
+
|
|
253
|
+
## Development
|
|
254
|
+
|
|
255
|
+
`lib/ampost/generated/` comes from `openapi.json`; never edit it by hand.
|
|
256
|
+
|
|
257
|
+
```sh
|
|
258
|
+
bundle install
|
|
259
|
+
ruby scripts/generate.rb # from the committed openapi.json
|
|
260
|
+
ruby scripts/generate.rb --spec https://api.ampost.io/openapi.json # refresh the snapshot, then generate
|
|
261
|
+
bundle exec rake test
|
|
262
|
+
AMPOST_API_KEY=amp_... bundle exec ruby -Ilib -Itest test/smoke_test.rb # reads and validates only
|
|
263
|
+
gem build ampost.gemspec
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
Why this generator: OpenAPI Generator's Ruby client emits a model class and a file per schema and
|
|
267
|
+
depends on Typhoeus; the result is large and reads unlike the API docs. `scripts/generate.rb` uses
|
|
268
|
+
only the standard library and writes one method per operation with its docs, so requests and
|
|
269
|
+
responses stay the plain JSON the docs show. The hand-written client (`lib/ampost/client.rb`) adds
|
|
270
|
+
auth, retries, idempotency, errors and pagination on `Net::HTTP`.
|
|
271
|
+
|
|
272
|
+
## Links
|
|
273
|
+
|
|
274
|
+
- [API docs](https://ampost.io/docs?ref=github) and [llms.txt](https://ampost.io/llms.txt?ref=github)
|
|
275
|
+
- [MCP server](https://ampost.io/docs/mcp?ref=github)
|
|
276
|
+
- [Pricing](https://ampost.io/pricing?ref=github)
|
|
277
|
+
- [Node.js SDK](https://github.com/ampost-io/ampost-node), [Python SDK](https://github.com/ampost-io/ampost-python), [CLI](https://github.com/ampost-io/ampost-cli)
|
|
278
|
+
|
|
279
|
+
## License
|
|
280
|
+
|
|
281
|
+
MIT
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "date"
|
|
4
|
+
require "json"
|
|
5
|
+
require "securerandom"
|
|
6
|
+
require "uri"
|
|
7
|
+
|
|
8
|
+
module Ampost
|
|
9
|
+
DEFAULT_BASE_URL = "https://api.ampost.io"
|
|
10
|
+
|
|
11
|
+
# The Ampost API client.
|
|
12
|
+
#
|
|
13
|
+
# client = Ampost::Client.new # reads AMPOST_API_KEY
|
|
14
|
+
# post = client.posts.create({ text: "Hello", targets: [{ platforms: ["bluesky"] }], publishNow: true })
|
|
15
|
+
#
|
|
16
|
+
# Each tag of the API is a reader (`posts`, `accounts`, `platform_sets`, `media`, `analytics`,
|
|
17
|
+
# `webhooks`, `platforms`, `docs`, `feedback`) with one method per operation. Request bodies are
|
|
18
|
+
# Hashes with the API's field names (symbol or string keys); responses are Hashes with string keys.
|
|
19
|
+
# A client holds no connection, so one client can serve many threads.
|
|
20
|
+
class Client
|
|
21
|
+
include Resources::Readers
|
|
22
|
+
|
|
23
|
+
# Per-call options every method takes as keyword arguments.
|
|
24
|
+
REQUEST_OPTIONS = %i[timeout max_retries extra_headers].freeze
|
|
25
|
+
# Operations that take an `Idempotency-Key` also take `idempotency_key:`.
|
|
26
|
+
IDEMPOTENT_OPTIONS = (REQUEST_OPTIONS + %i[idempotency_key]).freeze
|
|
27
|
+
|
|
28
|
+
# @return [String]
|
|
29
|
+
attr_reader :base_url
|
|
30
|
+
# @return [Integer] retries after a 429, a 5xx or a network error (see README, "Retries")
|
|
31
|
+
attr_reader :max_retries
|
|
32
|
+
# @return [Numeric] seconds per attempt
|
|
33
|
+
attr_reader :timeout
|
|
34
|
+
# @return [Numeric] a longer `Retry-After` is not waited for: the error is raised
|
|
35
|
+
attr_reader :max_retry_delay
|
|
36
|
+
|
|
37
|
+
# @param api_key [String, nil] An API key from https://ampost.io/app/settings/api-keys. Default: `AMPOST_API_KEY`.
|
|
38
|
+
# @param base_url [String, nil] Default: `AMPOST_BASE_URL`, else `https://api.ampost.io`.
|
|
39
|
+
# @param max_retries [Integer] Retries after a 429, a 5xx or a network error.
|
|
40
|
+
# @param timeout [Numeric] Seconds per attempt.
|
|
41
|
+
# @param max_retry_delay [Numeric] A longer `Retry-After` is not waited for: the error is raised.
|
|
42
|
+
# @param default_headers [Hash{String => String}] Headers sent with every request.
|
|
43
|
+
# @param transport [#call] The HTTP layer; default Ampost::Transport::NetHTTP.
|
|
44
|
+
def initialize(api_key: nil, base_url: nil, max_retries: 2, timeout: 60, max_retry_delay: 60,
|
|
45
|
+
default_headers: {}, transport: nil)
|
|
46
|
+
api_key = blank_to_nil(api_key) || blank_to_nil(ENV.fetch("AMPOST_API_KEY", nil))
|
|
47
|
+
unless api_key
|
|
48
|
+
raise Error, "Missing API key: pass api_key: or set AMPOST_API_KEY. " \
|
|
49
|
+
"Create one at https://ampost.io/app/settings/api-keys?ref=github"
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
@api_key = api_key
|
|
53
|
+
@base_url = (blank_to_nil(base_url) || blank_to_nil(ENV.fetch("AMPOST_BASE_URL", nil)) || DEFAULT_BASE_URL).chomp("/")
|
|
54
|
+
@max_retries = max_retries
|
|
55
|
+
@timeout = timeout
|
|
56
|
+
@max_retry_delay = max_retry_delay
|
|
57
|
+
@default_headers = default_headers.to_h
|
|
58
|
+
@transport = transport || Transport::NetHTTP.new
|
|
59
|
+
init_resources
|
|
60
|
+
@media = MediaResource.new(self)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# Never shows the key.
|
|
64
|
+
def inspect
|
|
65
|
+
"#<#{self.class.name} base_url=#{@base_url.inspect}>"
|
|
66
|
+
end
|
|
67
|
+
alias to_s inspect
|
|
68
|
+
|
|
69
|
+
# Sends one API call with auth, the idempotency key and retries. The generated methods call this.
|
|
70
|
+
#
|
|
71
|
+
# @param method [String] the HTTP method
|
|
72
|
+
# @param path [String] the path, already encoded
|
|
73
|
+
# @param query [Hash{String => Object}] nil values are left out
|
|
74
|
+
# @param body [Hash, nil] sent as JSON
|
|
75
|
+
# @param idempotent [Boolean] the operation takes an `Idempotency-Key`
|
|
76
|
+
# @param options [Hash] `timeout:`, `max_retries:`, `extra_headers:`, and `idempotency_key:` when idempotent
|
|
77
|
+
# @return [Hash, Array, nil] the parsed JSON response
|
|
78
|
+
def request(method, path, query: nil, body: nil, idempotent: false, options: {})
|
|
79
|
+
check_options(options, idempotent)
|
|
80
|
+
request = build_request(method, path, query, body, idempotent, options)
|
|
81
|
+
# Without a key, a write that timed out may have been done: only reads and keyed writes repeat.
|
|
82
|
+
repeatable = method == "GET" || idempotent
|
|
83
|
+
max_retries = options.fetch(:max_retries, @max_retries)
|
|
84
|
+
attempt = 0
|
|
85
|
+
loop do
|
|
86
|
+
begin
|
|
87
|
+
response = @transport.call(request)
|
|
88
|
+
rescue APIConnectionError
|
|
89
|
+
raise if !repeatable || attempt >= max_retries
|
|
90
|
+
|
|
91
|
+
sleep_for(backoff(attempt))
|
|
92
|
+
attempt += 1
|
|
93
|
+
next
|
|
94
|
+
end
|
|
95
|
+
return parse(response) if response.success?
|
|
96
|
+
|
|
97
|
+
error = APIError.from_response(response)
|
|
98
|
+
delay = retry_delay(error, attempt, repeatable)
|
|
99
|
+
raise error if delay.nil? || attempt >= max_retries
|
|
100
|
+
|
|
101
|
+
sleep_for(delay)
|
|
102
|
+
attempt += 1
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Like #request for a list operation: returns its first Page.
|
|
107
|
+
#
|
|
108
|
+
# @return [Ampost::Page]
|
|
109
|
+
def paginate(method, path, query: nil, options: {})
|
|
110
|
+
fetch = lambda do |offset|
|
|
111
|
+
request(method, path, query: (query || {}).merge("offset" => offset), options: options)
|
|
112
|
+
end
|
|
113
|
+
Page.new(request(method, path, query: query, options: options), fetch)
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
# One request outside the API (the media PUT): no auth header, no retries.
|
|
117
|
+
#
|
|
118
|
+
# @return [Ampost::Transport::Response]
|
|
119
|
+
def send_raw(method, url, headers:, body:, timeout:)
|
|
120
|
+
@transport.call(Transport::Request.new(method: method, url: url, headers: headers, body: body, timeout: timeout))
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
private
|
|
124
|
+
|
|
125
|
+
def check_options(options, idempotent)
|
|
126
|
+
unknown = options.keys - (idempotent ? IDEMPOTENT_OPTIONS : REQUEST_OPTIONS)
|
|
127
|
+
return if unknown.empty?
|
|
128
|
+
|
|
129
|
+
raise ArgumentError, "unknown keyword#{"s" if unknown.size > 1}: #{unknown.map(&:inspect).join(", ")} " \
|
|
130
|
+
"(pass the request body as a Hash: method({ ... }))"
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def build_request(method, path, query, body, idempotent, options)
|
|
134
|
+
headers = {
|
|
135
|
+
"Accept" => "application/json",
|
|
136
|
+
"User-Agent" => "ampost-ruby/#{VERSION}"
|
|
137
|
+
}
|
|
138
|
+
headers.merge!(@default_headers.transform_keys(&:to_s))
|
|
139
|
+
headers.merge!(options.fetch(:extra_headers, {}).to_h.transform_keys(&:to_s))
|
|
140
|
+
headers.delete_if { |name, _| name.casecmp?("authorization") }
|
|
141
|
+
headers["Authorization"] = "Bearer #{@api_key}"
|
|
142
|
+
payload = nil
|
|
143
|
+
unless body.nil?
|
|
144
|
+
headers["Content-Type"] = "application/json"
|
|
145
|
+
payload = JSON.generate(json_value(body))
|
|
146
|
+
end
|
|
147
|
+
headers["Idempotency-Key"] = options[:idempotency_key] || SecureRandom.uuid if idempotent
|
|
148
|
+
Transport::Request.new(
|
|
149
|
+
method: method,
|
|
150
|
+
url: "#{@base_url}#{path}#{query_string(query)}",
|
|
151
|
+
headers: headers,
|
|
152
|
+
body: payload,
|
|
153
|
+
timeout: options.fetch(:timeout, @timeout)
|
|
154
|
+
)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def query_string(query)
|
|
158
|
+
pairs = (query || {}).reject { |_, value| value.nil? }.map { |name, value| [name.to_s, query_value(value)] }
|
|
159
|
+
pairs.empty? ? "" : "?#{URI.encode_www_form(pairs)}"
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def query_value(value)
|
|
163
|
+
case value
|
|
164
|
+
when Array then value.map { |item| query_value(item) }
|
|
165
|
+
when Time, Date then value.iso8601
|
|
166
|
+
else value.to_s
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# Times and dates become ISO 8601 strings; everything else goes to JSON as is.
|
|
171
|
+
def json_value(value)
|
|
172
|
+
case value
|
|
173
|
+
when Hash then value.to_h { |k, v| [k.to_s, json_value(v)] }
|
|
174
|
+
when Array then value.map { |item| json_value(item) }
|
|
175
|
+
when Time, Date then value.iso8601
|
|
176
|
+
else value
|
|
177
|
+
end
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
# Seconds to wait before retrying, or nil to give up.
|
|
181
|
+
def retry_delay(error, attempt, repeatable)
|
|
182
|
+
retryable = error.status == 429 || # refused before anything ran
|
|
183
|
+
error.code == "IDEMPOTENCY_REQUEST_IN_PROGRESS" || # the first request with this key still runs
|
|
184
|
+
((error.status >= 500 || error.status == 408) && repeatable)
|
|
185
|
+
return nil unless retryable
|
|
186
|
+
|
|
187
|
+
retry_after = Ampost.parse_retry_after(error.headers["retry-after"])
|
|
188
|
+
return backoff(attempt) if retry_after.nil?
|
|
189
|
+
|
|
190
|
+
# A quota reset days away is not worth blocking on.
|
|
191
|
+
retry_after <= @max_retry_delay ? retry_after : nil
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
# Exponential backoff with jitter: about 0.5 s, 1 s, 2 s, ... up to 8 s.
|
|
195
|
+
def backoff(attempt)
|
|
196
|
+
[0.5 * (2**attempt), 8.0].min * (0.75 + (rand * 0.5))
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
def sleep_for(seconds)
|
|
200
|
+
sleep(seconds)
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
def parse(response)
|
|
204
|
+
return nil if response.body.nil? || response.body.empty?
|
|
205
|
+
|
|
206
|
+
JSON.parse(response.body)
|
|
207
|
+
rescue JSON::ParserError
|
|
208
|
+
raise Error, "Expected JSON from the API, got: #{response.body[0, 200]}"
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
def blank_to_nil(value)
|
|
212
|
+
value.nil? || value.to_s.strip.empty? ? nil : value.to_s
|
|
213
|
+
end
|
|
214
|
+
end
|
|
215
|
+
end
|