Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

peddler

> 编程语言
Open source

Amazon Selling Partner API (SP-API) in Ruby

318 stars0 likes2 views
WebsiteGitHub

About

Amazon Selling Partner API (SP-API) in Ruby

Peddler

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.

Installation

Add to your Gemfile.

Agent skills

Install the skills for agents:

bash
# 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-api
  • building-with-peddler: Ruby integration, token caching, retries, and pagination.
  • amazon-sp-api: Language-agnostic OpenAPI spec research, issue hunting, and discussions.

Usage

Authorization

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.

bash
export LWA_CLIENT_ID=
export LWA_CLIENT_SECRET=

A seller or vendor [provides you a refresh token][authorization] to access their data on Amazon.

ruby
response = Peddler::LWA.request(
  code: ""
)
refresh_token = response.parse.refresh_token

Use this to generate a temporary access token to authenticate individual requests.

ruby
response = Peddler::LWA.request(
  refresh_token: "",
)
access_token = response.parse.access_token

Similarly, you can request a token for grantless operations.

ruby
response = Peddler::LWA.request(
  scope: "sellingpartnerapi::notifications",
)
access_token = response.parse.access_token

In place of environment variables, you can set them directly when requesting the token.

ruby
response = Peddler::LWA.request(
  client_id: "",
  client_secret: "",
  refresh_token: "",
)
access_token = response.parse.access_token

Access tokens are valid for one hour. To optimize performance, cache and reuse across calls.

For example,

ruby
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
end

Restricted Data Tokens (RDT) and PII

Some 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.

ruby
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_token

Use the RDT exactly where you would normally pass the access token.

ruby
api = Peddler.orders.new(aws_region, restricted_data_token)
address = api.get_order_address("123-1234567-1234567").parse.payload.shipping_address

For the Orders API, also specify which dataElements you need (buyerInfo, shippingAddress, or buyerTaxInformation).

ruby
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_token

An 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.

Rate limiting

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.

ruby
api = Peddler.orders_v0.new(aws_region, access_token, retries: 3)
api.get_orders("...": "...")

Typed Responses

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.

ruby
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"

Hash Access

If you prefer working with plain hashes instead of typed Data objects:

ruby
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")

Error Handling

All HTTP errors (4xx and 5xx) raise Peddler::Error. Errors expose Amazon's message and the underlying response, and support pattern matching on status:

ruby
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
end

Rescuing Specific Errors

Peddler 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:

ruby
# 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:

ruby
api = Peddler..new(aws_region, access_token, **options)

Available APIs by category:

Orders and Financial APIs

  • Orders API: Retrieve and manage orders
  • Finances API: Financial data, payments, refunds
  • Invoices API: Manage billing invoices
  • Sales API: Order metrics and sales data
ruby
api = Peddler.orders.new(aws_region, access_token)
response = api.get_orders("...": "...")
orders = response.parse.payload.orders

Catalog and Listing APIs

  • Catalog Items API: Access Amazon's catalog data
  • Listings Items API: Create and update listings
  • Listings Restrictions API: Check listing eligibility
  • Product Type Definitions API: Get schema requirements for listings
  • A+ Content API: Create and manage enhanced marketing content
  • Product Pricing API: Get pricing information
  • Product Fees API: Retrieve fee estimates for products
ruby
api = Peddler.catalog_items.new(aws_region, access_token)
response = api.get_catalog_item("...": "...")
item = response.parse.payload

Fulfillment and Inventory APIs

  • Fulfillment Inbound API: Send inventory to FBA
  • Fulfillment Outbound API: Create and track FBA orders
  • FBA Inventory API: Manage FBA inventory quantities
  • FBA Inbound Eligibility API: Check product eligibility for FBA
  • Merchant Fulfillment API: Create shipping labels for self-fulfilled orders
  • Easy Ship API: Manage Amazon's carrier service
  • Shipping APIs: Create shipments and purchase shipping labels
  • Replenishment API: Manage inventory replenishment
  • Amazon Warehousing and Distribution API: Manage fulfillment warehousing
  • Supply Sources API: Manage supply/inventory sources
  • Shipment Invoicing API: Manage shipment-related invoices
ruby
api = Peddler.fulfillment_outbound.new(aws_region, access_token)
response = api.create_fulfillment_order(body: { "...": "..." })

Data Management APIs

  • Feeds API: Upload data to Amazon (listings, prices, inventory, etc.)
  • Reports API: Request and download reports (orders, inventory, fulfillment, etc.)
  • Uploads API: Upload files for various SP-API operations
  • Data Kiosk API: Access analytical data with GraphQL queries
ruby
# 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"))

Data Kiosk API

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:

  • SalesAndTraffic20231115: Sales and traffic metrics by ASIN and date
  • SalesAndTraffic20240424: Enhanced sales and traffic data (2024)
  • Economics20240315: Economics and profitability data
  • VendorAnalytics20240930: Vendor-specific analytics and forecasting data
ruby
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 document

Vendor APIs

  • Vendor Orders API: Retrieve purchase orders
  • Vendor Direct Fulfillment Orders API: Manage direct fulfillment orders
  • Vendor Direct Fulfillment Shipping API: Manage shipping for direct fulfillment
  • Vendor Direct Fulfillment Payments API: Process payments for direct fulfillment
  • Vendor Direct Fulfillment Inventory API: Manage inventory for direct fulfillment
  • Vendor Direct Fulfillment Transactions API: Track transaction status
  • Vendor Direct Fulfillment Sandbox Test Data API: Generate test data in sandbox
  • Vendor Shipments API: Track vendor shipments
  • Vendor Invoices API: Submit and track invoices
  • Vendor Transaction Status API: Check transaction status
ruby
api = Peddler.vendor_orders.new(aws_region, access_token)
orders = api.get_purchase_orders(limit: 10, createdAfter: "2023-01-01T00:00:00Z").parse

Authorization and Account Management APIs

  • Application Management API: Manage application authorization
  • Tokens API: Generate restricted data tokens for accessing PII
  • Sellers API: Get seller account information and marketplace participation
  • Services API: Manage seller services and subscriptions
  • Seller Wallet API: Manage seller financial accounts
  • Application Integrations API: Manage app integrations
  • Vehicles API: Manage vehicle data for automotive products

Complex Workflows

Detailed workflows are available in test files with VCR cassettes:

  • Feeds API: [test/p

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyamazonecommercerubyselling-partner-api

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言