Amazon Selling Partner API (SP-API) in Ruby
Peddler is a Ruby interface to the [Amazon Selling Partner API (SP-API)][api-docs]. The SP-API enables Amazon sellers and vendors to programmatically access their data on orders, shipments, payments, and more.
Peddler is automatically generated from the latest Open API models provided by Amazon. A nightly job tracks Amazon's spec changes, so new endpoints and fields land shortly after Amazon publishes them. Model changes are not considered breaking and don't trigger a major version bump.
Peddler covers all SP-API endpoints, reports, notifications, and feeds. It's also lightweight: thanks to Zeitwerk, only the code you use gets loaded.
Add to your Gemfile.
Install the skills for agents:
# Install both skills
npx skills add lineofflight/peddler
# Or install individually
npx skills add lineofflight/peddler -s building-with-peddler
npx skills add lineofflight/peddler -s amazon-sp-apibuilding-with-peddler: Ruby integration, token caching, retries, and pagination.amazon-sp-api: Language-agnostic OpenAPI spec research, issue hunting, and discussions.Before using Peddler, you must [register as a developer][register-as-developer], [register your application][register-application], and [obtain your Login with Amazon (LWA) credentials][view-credentials]; Amazon's [official SP-API code samples][api-samples] can help you get started.
Set your LWA credentials in your environment.
export LWA_CLIENT_ID=
export LWA_CLIENT_SECRET=A seller or vendor [provides you a refresh token][authorization] to access their data on Amazon.
response = Peddler::LWA.request(
code: ""
)
refresh_token = response.parse.refresh_tokenUse this to generate a temporary access token to authenticate individual requests.
response = Peddler::LWA.request(
refresh_token: "",
)
access_token = response.parse.access_tokenSimilarly, you can request a token for grantless operations.
response = Peddler::LWA.request(
scope: "sellingpartnerapi::notifications",
)
access_token = response.parse.access_tokenIn place of environment variables, you can set them directly when requesting the token.
response = Peddler::LWA.request(
client_id: "",
client_secret: "",
refresh_token: "",
)
access_token = response.parse.access_tokenAccess tokens are valid for one hour. To optimize performance, cache and reuse across calls.
For example,
class Seller
attr_reader :refresh_token
def access_token
Rails.cache.fetch("#{cache_key}/access_key", expires_in: 1.hour) do
Peddler::LWA.request(refresh_token:).parse.access_token
end
end
endSome operations are restricted because they return Personally Identifiable Information (PII), such as a buyer's name and shipping address. To call one, exchange your access token for a Restricted Data Token (RDT) scoped to the specific resources you need, then pass the RDT in place of the access token.
api = Peddler.tokens.new(aws_region, access_token)
response = api.create_restricted_data_token({
"restrictedResources" => [
{
"method" => "GET",
"path" => "/orders/v0/orders/123-1234567-1234567/address",
},
],
})
restricted_data_token = response.parse.restricted_data_tokenUse the RDT exactly where you would normally pass the access token.
api = Peddler.orders.new(aws_region, restricted_data_token)
address = api.get_order_address("123-1234567-1234567").parse.payload.shipping_addressFor the Orders API, also specify which dataElements you need (buyerInfo, shippingAddress, or buyerTaxInformation).
api = Peddler.tokens.new(aws_region, access_token)
response = api.create_restricted_data_token({
"restrictedResources" => [
{
"method" => "GET",
"path" => "/orders/v0/orders",
"dataElements" => ["buyerInfo", "shippingAddress"],
},
],
})
restricted_data_token = response.parse.restricted_data_tokenAn RDT is valid for one hour. Like access tokens, cache and reuse it across calls. See the [Tokens API Use Case Guide][tokens-guide] for the full list of restricted operations.
Amazon's SP-API imposes [rate limits][rate-limits] on operations. Override the default value by passing a :rate_limit parameter when calling an operation.
Provide an optional :retries argument when initializing an API to specify retry attempts if throttled. Default is 0 (no retries). If set, Peddler retries with exponential backoff.
api = Peddler.orders_v0.new(aws_region, access_token, retries: 3)
api.get_orders("...": "...")Peddler provides typed response parsing using the Structure gem, offering runtime type checking and better IDE support. Types are based on Ruby's Data class and are lazy-loaded.
api = Peddler.orders.new(aws_region, access_token)
# Get orders with type-safe response
response = api.get_orders("...": "...")
# Use .parse to get typed Data objects
orders = response.parse.payload.orders # Returns array of Order Data objects
order = orders.first
# Type-safe attribute access
order.amazon_order_id # => "123-4567890-1234567"
order.order_status # => "Shipped"
order.prime? # => true
order.order_total # => Money object (automatic coercion)
order.order_total.cents # => 9999
order.order_total.currency.iso_code # => "USD"If you prefer working with plain hashes instead of typed Data objects:
api = Peddler.orders.new(aws_region, access_token)
response = api.get_orders(marketplaceIds: ["ATVPDKIKX0DER"])
# Use .to_h to get raw Hash
orders = response.to_h["payload"]["orders"]
# Or use .dig directly (delegates to .to_h)
orders = response.dig("payload", "orders")All HTTP errors (4xx and 5xx) raise Peddler::Error. Errors expose Amazon's message and the underlying response, and support pattern matching on status:
begin
response = api.get_orders(marketplaceIds: ["ATVPDKIKX0DER"])
rescue Peddler::Error => e
case e
in status: 429
backoff_and_retry
in status: 500..599
retry_later
else
raise
end
endPeddler raises a specific subclass per Amazon error code and predefines one for every code we have seen Amazon return (e.g., Peddler::Errors::QuotaExceeded, Peddler::Errors::InvalidInput). Unknown codes get a subclass created at runtime; this is rare, and worth reporting so we can predefine it. To rescue one without a boot-time NameError, define it beforehand:
# config/initializers/peddler_errors.rb
module Peddler
module Errors
class NewAmazonErrorCode .new(aws_region, access_token, **options)You can also simply use the latest version:
api = Peddler..new(aws_region, access_token, **options)Available APIs by category:
api = Peddler.orders.new(aws_region, access_token)
response = api.get_orders("...": "...")
orders = response.parse.payload.ordersapi = Peddler.catalog_items.new(aws_region, access_token)
response = api.get_catalog_item("...": "...")
item = response.parse.payloadapi = Peddler.fulfillment_outbound.new(aws_region, access_token)
response = api.create_fulfillment_order(body: { "...": "..." })# Feeds API - create feed document, upload, submit
api = Peddler.feeds.new(aws_region, access_token)
document = api.create_feed_document(contentType: "text/xml; charset=UTF-8")
api.upload_feed_document(document.dig("url"), File.read("feed.xml"), "text/xml")
feed = api.create_feed(feedType: "POST_INVENTORY_AVAILABILITY_DATA", marketplaceIds: ["ATVPDKIKX0DER"], inputFeedDocumentId: document.dig("feedDocumentId"))The Data Kiosk API provides access to Amazon's analytical data through GraphQL queries. Peddler supports four Data Kiosk schema versions, each with type-safe classes for parsing responses.
Available Schemas:
api = Peddler.data_kiosk.new(aws_region, access_token)
response = api.create_query(query: "query { salesAndTrafficByDate(...) { data { date sales } } }")
query_id = response.dig("payload", "queryId")
# Poll for completion and download documentapi = Peddler.vendor_orders.new(aws_region, access_token)
orders = api.get_purchase_orders(limit: 10, createdAfter: "2023-01-01T00:00:00Z").parseDetailed workflows are available in test files with VCR cassettes:
No open issues yet, or sync has not completed.