Peddler Ruby Interface for Amazon SP-API

repository·main·Indexed 43 days ago

https://github.com/lineofflight/peddler

A Ruby interface for the Amazon Selling Partner API (SP-API) that provides programmatic access to seller and vendor data, including orders, shipments, and payments. It features automatically generated clients from Amazon OpenAPI models, type-safe responses using the Structure gem, and built-in support for Login with Amazon (LWA) authentication, Restricted Data Tokens (RDT) for PII access, and automatic retry logic with exponential backoff.

Tokens
9.2K
Snippets
33
Records
41
Agent score
55%

What's inside Peddler

  1. What is Peddler

    main

    Peddler is a Ruby interface for the Amazon Selling Partner API (SP-API). It allows developers to programmatically access Amazon seller and vendor data, including orders, shipments, payments, and more.

    Key features:

    • Automatically Generated: Built from the latest Amazon OpenAPI models via a nightly sync process.
    • Comprehensive Coverage: Includes all SP-API endpoints, reports, notifications, and feeds.
    • Lightweight: Uses Zeitwerk for autoloading, ensuring only the code you actually use is loaded into memory.
  2. Understand the Generator System architecture

    main

    The generator follows a pipeline architecture to transform Amazon's raw specifications into a usable Ruby client. The process follows these stages:

    1. Sync Specs: The Specs orchestrator clones the Amazon selling-partner-api-models repository at the specific revision recorded in selling-partner-api-models.sha.
    2. Generate Code: Orchestrators (API, Notification, Report, Feed) parse JSON/OpenAPI specs. They use Parsers (like JsonSchemaExtractor) to extract data, Builders (like Type and Operation) to construct Ruby classes, and ERB templates to write the files.
    3. Generate RBS: The system introspects the newly generated Ruby classes (using the structure gem and IntrospectionLoader) to produce RBS type signatures.
    4. Format: Files are processed through RuboCop and RBS files are sorted.

    Core Components

    ComponentResponsibility
    OrchestratorsMain entry points (e.g., api.rb, notification.rb) that manage the high-level generation flow.
    BuildersConstruct the actual code logic (e.g., type.rb for classes, operation.rb for methods).
    ParsersExtract raw data from specs (e.g., rate_limit_parser.rb, path.rb).
    ResolversTranslate representations (e.g., type_resolver.rb maps OpenAPI types to Ruby types).
    AnalyzersInspect code structure (e.g., circular_dependency_detector.rb).
    SupportShared utilities for I/O, logging, and configuration.
  3. Locate API response types in v5.0

    main

    In v5.0, API response types have been moved from the global Peddler::Types::* namespace to be nested directly under their respective API namespaces. This improves discoverability and colocates types with their APIs.

    Example Mapping:

    • Old: Peddler::Types::OrdersV0::Order
    • New: Peddler::APIs::OrdersV0::Order
  4. Understand the Reports and Data Kiosk lifecycle

    main

    Reports and Data Kiosk queries are asynchronous 3-step operations. For historical or bulk data, prefer these over deep endpoint pagination.

    1. Request: Call create_report or create_query.
    2. Await completion: Listen for REPORT_PROCESSING_FINISHED notifications via webhooks, or poll the processing status using exponential backoff.
    3. Retrieve: Call get_report_document to obtain the document URL, then download and parse the payload.
  5. Install Peddler Agent Skills

    main

    Peddler provides specific 'skills' for use with agent-based workflows. You can install both skills at once or select them individually using npx skills.

    Available Skills:

    • building-with-peddler: Provides Ruby integration, token caching, retries, and pagination.
    • amazon-sp-api: Provides language-agnostic OpenAPI spec research, issue hunting, and discussions.
    # 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
  6. Configure Sandbox and Custom Endpoints

    main

    You can redirect Peddler API clients to different environments for testing.

    Use Amazon's Hosted Sandbox

    Switch a client to the official Amazon sandbox environment using the .sandbox method:

    api = Peddler.orders_v0.new(aws_region, access_token).sandbox

    Use a Custom Backend (Local Mock/Proxy)

    To point a client at a local mock, a recording proxy, or a specific service like the Sample AI Sandbox, pass the base_url option.

    Note: base_url is mutually exclusive with .sandbox. Only the scheme, host, and port are used; any path provided in base_url is ignored.

    api = Peddler.orders_v0.new(aws_region, access_token, base_url: "http://localhost:9001")
  7. Locate Amazon SP-API OpenAPI spec files

    main

    OpenAPI models are hosted in the amzn/selling-partner-api-models repository. You can locate specific files using the GitHub CLI (gh) by searching for an operationId or an endpoint path.

    # Find by operation ID
    gh search code --repo amzn/selling-partner-api-models "operationId: confirmShipment"
    
    # Find by endpoint path
    gh search code --repo amzn/selling-partner-api-models '"/orders/v0/orders"'
  8. Use Restricted Data Tokens (RDT) for PII access

    main

    Certain Amazon SP-API operations return Personally Identifiable Information (PII), such as buyer names or shipping addresses. To access these, you must exchange your standard access_token for a Restricted Data Token (RDT) scoped to specific resources.

    1. Create the RDT

    Use the Peddler.tokens API to request an RDT. You must specify the HTTP method, the path, and for Orders, the required dataElements (e.g., buyerInfo, shippingAddress).

    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

    2. Use the RDT

    Pass the restricted_data_token in place of the access_token when initializing the target API client.

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

    RDTs are valid for one hour and should be cached.

    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
  9. Handle LWA access tokens and Restricted Data Tokens (RDT)

    main

    LWA access tokens and Restricted Data Tokens (RDTs) have a 1-hour lifetime. To avoid unnecessary requests, cache and reuse them.

    When dealing with PII (Personally Identifiable Information) such as buyer names or shipping addresses, request an RDT. Instead of requesting an RDT per order, batch multiple resource paths in a single call to create_restricted_data_token.

    # Example: Fetching and caching an LWA access token
    def current_access_token(refresh_token)
      Rails.cache.fetch("sp_api/lwa_token/#{refresh_token}", expires_in: 50.minutes) do
        Peddler::LWA.request(refresh_token:).parse.access_token
      end
    end
    
    # Example: Creating an RDT
    Peddler.tokens(...).create_restricted_data_token(restricted_resources: [:path1, :path2])