### Install Dependencies and Setup Source: https://github.com/lineofflight/peddler/blob/main/README.md Installs project dependencies and sets up the RBS collection for type checking. ```bash bundle install bundle exec rbs collection install ``` -------------------------------- ### Get Full Catalog Item Details by ASIN Source: https://context7.com/lineofflight/peddler/llms.txt Retrieve comprehensive details for a specific ASIN, including summaries, images, attributes, and dimensions. ```ruby # Retrieve full detail for a specific ASIN item = api.get_catalog_item( "B08N5WRWNW", Peddler::Marketplace.ids("US"), included_data: ["summaries", "images", "attributes", "dimensions"], ).parse puts item.summaries.first.item_name puts item.summaries.first.manufacturer item.images.first.images.each { |img| puts "#{img.variant}: #{img.link}" } ``` -------------------------------- ### Get Current Listing Item State Source: https://context7.com/lineofflight/peddler/llms.txt Retrieve the current state of a listing item, including summaries and issues. Requires seller ID, SKU, and marketplace IDs. ```ruby # Fetch current listing state item = api.get_listings_item(seller_id, sku, mp_ids, included_data: ["summaries", "issues"]).parse puts item.summaries.first.status # => "BUYABLE" ``` -------------------------------- ### Partially Update a Listing Item Source: https://context7.com/lineofflight/peddler/llms.txt Perform a partial update (PATCH) on an existing listing, for example, to change the price. This method requires the seller ID, SKU, marketplace IDs, and a list of patches. ```ruby # Partial update (PATCH): change price only api.patch_listings_item(seller_id, sku, mp_ids, { "productType" => "LUGGAGE", "patches" => [{ "op" => "replace", "path" => "/attributes/list_price", "value" => [{ "currency" => "USD", "value" => 69.99 }], }], }) ``` -------------------------------- ### Vendor Orders API - Get Purchase Orders Source: https://github.com/lineofflight/peddler/blob/main/README.md Retrieves purchase orders for vendors. This is useful for managing vendor-specific orders. ```APIDOC ## Vendor Orders API - Get Purchase Orders ### Description Retrieves purchase orders for vendors. ### Method `get_purchase_orders` ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of orders to return. - **createdAfter** (string) - Optional - Filters orders created after the specified date and time (ISO 8601 format). ### Request Example ```ruby api = Peddler.vendor_orders.new(aws_region, access_token) orders = api.get_purchase_orders(limit: 10, createdAfter: "2023-01-01T00:00:00Z").parse ``` ``` -------------------------------- ### Get Catalog Item using Catalog Items API Source: https://github.com/lineofflight/peddler/blob/main/README.md Access Amazon's catalog data by instantiating the Catalog Items API. The response payload contains item details. ```ruby api = Peddler.catalog_items.new(aws_region, access_token) response = api.get_catalog_item("..."=> "...") item = response.parse.payload ``` -------------------------------- ### Get Orders and Parse as Hash Source: https://github.com/lineofflight/peddler/blob/main/README.md Retrieve orders and convert the response to a plain Ruby Hash for traditional hash-based access. Alternatively, use the `.dig` method for nested hash traversal. ```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") ``` -------------------------------- ### Handle SP-API Errors Source: https://context7.com/lineofflight/peddler/llms.txt Handle HTTP 4xx and 5xx responses by rescuing Peddler::Error or its subclasses. This example shows how to catch specific errors like QuotaExceeded and InvalidInput, as well as a general catch-all for other API errors. ```ruby api = Peddler.orders.new("us-east-1", access_token, retries: 3) begin orders = api.search_orders( created_after: 30.days.ago.iso8601, marketplace_ids: Peddler::Marketplace.ids("US"), ).parse rescue Peddler::Errors::QuotaExceeded => e # 429 — retries already exhausted (if retries: N was set) puts "Rate limited: #{e.message}" puts "HTTP status: #{e.response.status}" rescue Peddler::Errors::InvalidInput => e puts "Bad request: #{e.message}" rescue Peddler::Error => e # Catch-all for any other SP-API or HTTP error puts "API error (#{e.response.status}): #{e.message}" if e.response.status >= 500 # Server error — consider re-queuing the job raise end end ``` -------------------------------- ### Get Vendor Purchase Orders Source: https://github.com/lineofflight/peddler/blob/main/README.md Retrieve purchase orders for vendors using the Vendor Orders API. Instantiate the API with AWS region and access token, then call get_purchase_orders with parameters like limit and createdAfter. ```ruby api = Peddler.vendor_orders.new(aws_region, access_token) orders = api.get_purchase_orders(limit: 10, createdAfter: "2023-01-01T00:00:00Z").parse ``` -------------------------------- ### Get Orders with Typed Response Parsing Source: https://github.com/lineofflight/peddler/blob/main/README.md Fetch orders using the Peddler client and parse the response into typed Data objects for runtime type checking and better IDE support. Access attributes directly on the parsed objects. ```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" ``` -------------------------------- ### Request and Download a Report Source: https://context7.com/lineofflight/peddler/llms.txt Demonstrates how to request a flat file report, poll for its completion, and then download the content. Handles report creation, status checking, and content retrieval. ```ruby create_resp = api.create_report({ "reportType" => "GET_FLAT_FILE_OPEN_LISTINGS_DATA", "marketplaceIds" => Peddler::Marketplace.ids("US"), }).parse report_id = create_resp.report_id # => "54517018502" # Poll until processing is complete loop do report = api.get_report(report_id).parse break if report.processing_status == "DONE" raise "Report failed" if report.processing_status == "FATAL" sleep 30 end # Get the download URL and fetch content doc_id = api.get_report(report_id).parse.report_document_id content = api.download_report_document(doc_id).to_s # Or if you already have the URL url = api.get_report_document(doc_id).parse.url content = api.download_report_document(url).to_s ``` -------------------------------- ### Instantiate API Client Source: https://github.com/lineofflight/peddler/blob/main/README.md Instantiate an API client for a specific API and version. You can use a specific version or the latest available version. ```ruby api = Peddler._.new(aws_region, access_token, **options) ``` ```ruby api = Peddler..new(aws_region, access_token, **options) ``` -------------------------------- ### Orders API - Get Orders Source: https://github.com/lineofflight/peddler/blob/main/README.md Retrieves orders using the Orders API. This is a common operation for managing order data. ```APIDOC ## Orders API - Get Orders ### Description Retrieves and manages orders from Amazon. ### Method `get_orders` ### Parameters #### Query Parameters - **"..."** (string) - Required - Placeholder for actual query parameters. ### Request Example ```ruby api = Peddler.orders.new(aws_region, access_token) response = api.get_orders("...": "...") ``` ### Response #### Success Response - **payload.orders** - Contains the list of orders. ### Response Example ```ruby orders = response.parse.payload.orders ``` ``` -------------------------------- ### Create a Scheduled Report Source: https://context7.com/lineofflight/peddler/llms.txt Shows how to set up a report to be generated on a recurring schedule. Specify the report type, marketplaces, and the desired interval. ```ruby api.create_report_schedule({ "reportType" => "GET_MERCHANT_LISTINGS_ALL_DATA", "marketplaceIds" => Peddler::Marketplace.ids("US"), "period" => "PT48H", # every 48 hours }) ``` -------------------------------- ### Catalog Items API - Get Catalog Item Source: https://github.com/lineofflight/peddler/blob/main/README.md Accesses Amazon's catalog data to retrieve information about a specific catalog item. ```APIDOC ## Catalog Items API - Get Catalog Item ### Description Accesses Amazon's catalog data to retrieve information about a specific item. ### Method `get_catalog_item` ### Parameters #### Query Parameters - **"..."** (string) - Required - Placeholder for actual query parameters. ### Request Example ```ruby api = Peddler.catalog_items.new(aws_region, access_token) response = api.get_catalog_item("...": "...") ``` ### Response #### Success Response - **payload** - Contains the catalog item details. ### Response Example ```ruby item = response.parse.payload ``` ``` -------------------------------- ### API Initialization - Peddler::API#initialize Source: https://context7.com/lineofflight/peddler/llms.txt Initializes a new SP-API wrapper instance. Accepts AWS region, access token, and optional retry count or custom HTTP client. ```APIDOC ## API Initialization - `Peddler::API#initialize` ### Description Base class for all SP-API wrappers. Every generated API class inherits from it. Accepts an AWS region, an LWA access token, optional retry count, and an optional pre-configured `HTTP::Client`. ### Method `Peddler::API.new` (or specific API class initialization like `Peddler.orders.new`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby aws_region = "us-east-1" # North America; "eu-west-1" = Europe; "us-west-2" = Far East access_token = seller.access_token # Default: no retries on throttling api = Peddler.orders.new(aws_region, access_token) # With 3 automatic retries + exponential backoff on HTTP 429 api = Peddler.orders.new(aws_region, access_token, retries: 3) # Custom HTTP client (e.g. with middleware/logging) custom_http = HTTP.use(:auto_inflate).timeout(connect: 5, read: 30) api = Peddler.orders.new(aws_region, access_token, http: custom_http) ``` ### Response #### Success Response (200) An initialized API client object. #### Response Example (No specific response example, as this is an initialization method.) ``` -------------------------------- ### Initialize Peddler with Sandbox Source: https://context7.com/lineofflight/peddler/llms.txt Use the .sandbox method to initialize the Catalog Items API client for test calls in Amazon's SP-API sandbox environment. ```ruby api = Peddler.catalog_items.new(aws_region, access_token).sandbox ``` -------------------------------- ### Get a Single Order by ID Source: https://context7.com/lineofflight/peddler/llms.txt Fetch a specific order using its Amazon Order ID. The response can be parsed into typed objects or accessed as a raw hash. ```ruby # Fetch a single order by ID order = api.get_order("113-1234567-7654321").parse puts order.order.buyer_info.buyer_email # PII requires RDT — see Tokens API # Raw Hash access (no typed objects) order_hash = api.get_order("113-1234567-7654321").to_h puts order_hash.dig("payload", "AmazonOrderId") ``` -------------------------------- ### Create or Replace a Listing Item Source: https://context7.com/lineofflight/peddler/llms.txt Create a new listing or fully replace an existing one. Requires seller ID, SKU, marketplace IDs, product type, and attributes. Issues are included in the response. ```ruby api = Peddler.listings_items.new("us-east-1", access_token) seller_id = "A1B2C3D4E5F6G7" sku = "MY-SKU-001" mp_ids = Peddler::Marketplace.ids("US") # Create / fully replace a listing response = api.put_listings_item(seller_id, sku, mp_ids, { "productType" => "LUGGAGE", "requirements" => "LISTING", "attributes" => { "item_name" => [{ "value" => "My Amazing Suitcase", "language_tag" => "en_US" }], "brand" => [{ "value" => "MyBrand" }], "list_price" => [{ "currency" => "USD", "value" => 79.99 }], "fulfillment_availability" => [{ "fulfillment_channel_code" => "DEFAULT", "quantity" => 100 }], }, }, included_data: ["issues"]).parse puts response.status # => "ACCEPTED" response.issues.each { |i| puts "#{i.severity}: #{i.message}" } ``` -------------------------------- ### Get Orders using Orders API Source: https://github.com/lineofflight/peddler/blob/main/README.md Retrieve orders using the Orders API. Requires AWS region and access token for instantiation. The response payload contains the orders. ```ruby api = Peddler.orders.new(aws_region, access_token) response = api.get_orders("..."=> "...") orders = response.parse.payload.orders ``` -------------------------------- ### Run Tests and Linting Source: https://github.com/lineofflight/peddler/blob/main/README.md Executes all project tests and linting checks. ```bash bundle exec rake ``` -------------------------------- ### Create Data Kiosk Query Source: https://github.com/lineofflight/peddler/blob/main/README.md Create a query for the Data Kiosk API to access analytical data. The query string uses GraphQL syntax. After creation, you need to poll for completion and download the document. ```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 ``` -------------------------------- ### Initialize Peddler API Client Source: https://context7.com/lineofflight/peddler/llms.txt Initialize SP-API clients by providing the AWS region and LWA access token. Optional parameters include the number of retries for throttling (429 errors) and a custom `HTTP::Client` instance. ```ruby aws_region = "us-east-1" # North America; "eu-west-1" = Europe; "us-west-2" = Far East access_token = seller.access_token # Default: no retries on throttling api = Peddler.orders.new(aws_region, access_token) # With 3 automatic retries + exponential backoff on HTTP 429 api = Peddler.orders.new(aws_region, access_token, retries: 3) # Custom HTTP client (e.g. with middleware/logging) custom_http = HTTP.use(:auto_inflate).timeout(connect: 5, read: 30) api = Peddler.orders.new(aws_region, access_token, http: custom_http) ``` -------------------------------- ### Initialize Peddler with Latest Orders API Version Source: https://context7.com/lineofflight/peddler/llms.txt Use the shortcut Peddler.orders to automatically resolve to the latest version of the Orders API. ```ruby api = Peddler.orders.new(aws_region, access_token) ``` -------------------------------- ### Parse SP-API Notifications Source: https://context7.com/lineofflight/peddler/llms.txt Parse Amazon SP-API push notifications from SQS into type-safe Data objects. This example demonstrates parsing different notification types like AnyOfferChanged, FeedProcessingFinished, and DataKioskQueryProcessingFinished. ```ruby require "json" # Consume from an SQS queue (e.g. via aws-sdk-sqs) raw_body = sqs_message.body notification_hash = JSON.parse(raw_body) # Determine type and parse accordingly case notification_hash["notificationType"] when "ANY_OFFER_CHANGED" notification = Peddler::Notifications::AnyOfferChanged.parse(notification_hash) notification.payload.offers.each do |offer| puts "Condition: #{offer.condition}" puts "Price: #{offer.listing_price.amount} #{offer.listing_price.currency_code}" puts "Ships from: #{offer.ship_from_location.country}" puts "Prime? #{offer.prime_information&.is_prime}" end when "FEED_PROCESSING_FINISHED" notification = Peddler::Notifications::FeedProcessingFinished.parse(notification_hash) puts "Feed #{notification.payload.feed_id} → #{notification.payload.processing_status}" puts "Result doc: #{notification.payload.result_feed_document_id}" when "DATA_KIOSK_QUERY_PROCESSING_FINISHED" notification = Peddler::Notifications::DataKioskQueryProcessingFinished.parse(notification_hash) puts "Query #{notification.payload.query_id}: #{notification.payload.processing_status}" ``` -------------------------------- ### Initialize Reports API Client Source: https://context7.com/lineofflight/peddler/llms.txt Initialize the Reports API client with the specified AWS region and access token. ```ruby api = Peddler.reports.new("us-east-1", access_token) ``` -------------------------------- ### Feeds API - Create Feed Document, Upload, and Submit Source: https://github.com/lineofflight/peddler/blob/main/README.md Demonstrates the process of creating a feed document, uploading content, and submitting a feed for data processing. ```APIDOC ## Feeds API - Feed Operations ### Description Handles the creation, upload, and submission of feeds for various data operations like inventory updates. ### Methods - `create_feed_document` - `upload_feed_document` - `create_feed` ### Parameters #### `create_feed_document` - **contentType** (string) - Required - The MIME type of the feed document (e.g., "text/xml; charset=UTF-8"). #### `upload_feed_document` - **url** (string) - Required - The URL obtained from `create_feed_document`. - **content** (string) - Required - The content of the feed file. - **contentType** (string) - Required - The MIME type of the feed content. #### `create_feed` - **feedType** (string) - Required - The type of feed (e.g., "POST_INVENTORY_AVAILABILITY_DATA"). - **marketplaceIds** (array of strings) - Required - List of marketplace identifiers. - **inputFeedDocumentId** (string) - Required - The ID of the feed document created earlier. ### Request Example ```ruby 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")) ``` ``` -------------------------------- ### Set LWA Credentials in Environment Source: https://github.com/lineofflight/peddler/blob/main/README.md Set your Login with Amazon (LWA) client ID and secret as environment variables before making authorization requests. ```shell export LWA_CLIENT_ID= export LWA_CLIENT_SECRET= ``` -------------------------------- ### Hash-based Response Access in v5.0 (v4.x Equivalent) Source: https://github.com/lineofflight/peddler/blob/main/UPGRADING.md To maintain v4.x's default Hash-based behavior in v5.0, use the `.to_h` method instead of `.parse`. ```ruby response = api.get_catalog_item(asin: "B08N5WRWNW") item = response.to_h # Hash - same behavior as v4's parse title = item["summaries"].first["itemName"] ``` -------------------------------- ### Zeitwerk Autoloading Comparison Source: https://github.com/lineofflight/peddler/blob/main/UPGRADING.md Illustrates the difference in API loading between older versions of Peddler (all APIs loaded at require time) and the new Zeitwerk-based approach (APIs loaded on-demand). No code changes are required for this optimization. ```ruby # Before: All 61 APIs loaded at require time require "peddler" # After: APIs loaded on-demand require "peddler" api = Peddler.orders.new(...) # Only OrdersV0 loaded here ``` -------------------------------- ### Type Check with Steep Source: https://github.com/lineofflight/peddler/blob/main/README.md Performs a type check on the project using Steep with a hint severity level. ```bash bundle exec steep check --severity-level=hint ``` -------------------------------- ### Submit GraphQL Query for Data Kiosk Source: https://context7.com/lineofflight/peddler/llms.txt Submits a GraphQL query to the Data Kiosk API for analytical datasets. Includes steps for submitting the query, polling for completion, and downloading the results. ```ruby api = Peddler.data_kiosk.new("us-east-1", access_token) # Submit a GraphQL query query_resp = api.create_query({ "query" => <<~GQL, query MyQuery { analytics_salesAndTraffic_2023_11_15 { salesAndTrafficByDate( startDate: "2024-01-01" endDate: "2024-01-31" marketplaceIds: ["ATVPDKIKX0DER"] granularity: DAY ) { startDate endDate sales { orderedProductSales { amount currencyCode } totalOrderItems } traffic { browserSessions browserPageViews } } } } GQL }).parse query_id = query_resp.query_id # Poll until the query finishes loop do q = api.get_query(query_id).parse break if q.processing_status == "DONE" raise "Query failed" if q.processing_status == "FATAL" sleep 30 end # Download the result document doc_id = api.get_query(query_id).parse.data_document_id doc_url = api.get_document(doc_id).parse.document_url data = HTTP.get(doc_url).parse(:json) data["salesAndTrafficByDate"].each do |day| puts "#{day["startDate"]}: #{day["sales"]["orderedProductSales"]["amount"]}" end ``` -------------------------------- ### Configure API with Retries for Rate Limiting Source: https://github.com/lineofflight/peddler/blob/main/README.md Initialize an API client with a specified number of retries to handle rate limiting. Peddler will automatically retry with exponential backoff if throttled. ```ruby api = Peddler.orders_v0.new(aws_region, access_token, retries: 3) api.get_orders("..."=> "...") ``` -------------------------------- ### Initialize Peddler with Specific API Version Source: https://context7.com/lineofflight/peddler/llms.txt Explicitly specify the API version when initializing a client. The Orders API version 2026-01-01 is used here. ```ruby api = Peddler.orders_2026_01_01.new(aws_region, access_token) ``` -------------------------------- ### Search Catalog Items by Keyword Source: https://context7.com/lineofflight/peddler/llms.txt Search for catalog items using keywords. Specify marketplace, desired included data fields (e.g., summaries, images, salesRanks), and page size. ```ruby api = Peddler.catalog_items.new("us-east-1", access_token) # Search by keyword results = api.search_catalog_items( Peddler::Marketplace.ids("US"), keywords: ["wireless headphones"], included_data: ["summaries", "images", "salesRanks"], page_size: 20, ).parse results.items.each do |item| puts item.asin puts item.summaries.first.item_name puts item.summaries.first.brand_name end ``` -------------------------------- ### Enable Sandbox Mode for SP-API Source: https://context7.com/lineofflight/peddler/llms.txt Switch any Peddler API instance to the Amazon SP-API sandbox environment for safe testing. Sandbox mode returns static, pre-defined responses and uses faster rate-limit delays. ```ruby # Enable sandbox on any API api = Peddler.orders.new("us-east-1", access_token).sandbox puts api.sandbox? # => true puts api.endpoint_uri # => https://sandbox.sellingpartnerapi-na.amazon.com # Sandbox calls use faster rate-limit delays (0.2s vs real rate limit) sandbox_api = Peddler.catalog_items.new("us-east-1", access_token, retries: 2).sandbox # Static sandbox response for get_catalog_item item = sandbox_api.get_catalog_item("B08N5WRWNW", Peddler::Marketplace.ids("US")).parse puts item.summaries.first.item_name # pre-defined sandbox value ``` -------------------------------- ### Upload Feed Document and Create Feed Source: https://context7.com/lineofflight/peddler/llms.txt A six-step process to upload data using the Feeds API. This snippet covers creating a feed document placeholder, uploading content to S3, submitting the feed, and polling for completion. ```ruby api = Peddler.feeds.new("us-east-1", access_token) # Step 1: Create a feed document placeholder (get upload URL) doc = api.create_feed_document({ "contentType" => "text/xml; charset=UTF-8" }).parse upload_url = doc.url feed_doc_id = doc.feed_document_id # Step 2: Upload feed content to S3 presigned URL xml_content = <<~XML
1.01A1B2C3
Inventory 1 MY-SKU-00150
XML api.upload_feed_document(upload_url, xml_content, "text/xml; charset=UTF-8") # Step 3: Submit the feed feed = api.create_feed({ "feedType" => "POST_INVENTORY_AVAILABILITY_DATA", "marketplaceIds" => Peddler::Marketplace.ids("US"), "inputFeedDocumentId" => feed_doc_id, }).parse feed_id = feed.feed_id # => "23492394230" # Step 4: Poll until done loop do status = api.get_feed(feed_id).parse.processing_status break if status == "DONE" raise "Feed failed: #{status}" if status == "FATAL" sleep 60 end # Step 5: Retrieve result document URL result_doc_id = api.get_feed(feed_id).parse.result_feed_document_id result_doc_url = api.get_feed_document(result_doc_id).parse.url # Step 6: Download and inspect the processing report result_content = api.download_result_feed_document(result_doc_url).to_s ``` -------------------------------- ### Request Access Token with Direct Credentials Source: https://github.com/lineofflight/peddler/blob/main/README.md Alternatively, provide client ID, client secret, and refresh token directly when requesting an access token, bypassing environment variables. ```ruby response = Peddler::LWA.request( client_id: "", client_secret: "", refresh_token: "", ) access_token = response.parse.access_token ``` -------------------------------- ### Run Tests Only Source: https://github.com/lineofflight/peddler/blob/main/README.md Executes only the project's test suite. ```bash bundle exec rake test ``` -------------------------------- ### Request Access Token using Refresh Token Source: https://github.com/lineofflight/peddler/blob/main/README.md Generate a temporary access token by providing a refresh token. Access tokens are valid for one hour and should be cached for performance. ```ruby response = Peddler::LWA.request( refresh_token: "", ) access_token = response.parse.access_token ``` -------------------------------- ### Create Restricted Data Token Source: https://context7.com/lineofflight/peddler/llms.txt Demonstrates how to create a restricted data token (RDT) scoped to specific PII paths using the `tokens_api.create_restricted_data_token` method. The RDT can then be used as an access token for restricted operations. ```APIDOC ## Create Restricted Data Token ### Description Requests an RDT scoped to specific PII paths. This token is short-lived (1 hour) and can be used as an access token for restricted operations. ### Method `tokens_api.create_restricted_data_token` ### Parameters #### Request Body - **restrictedResources** (Array) - Required - A list of resources to restrict the token to. - **method** (String) - Required - The HTTP method for the resource (e.g., "GET"). - **path** (String) - Required - The API path for the resource (e.g., "/orders/v0/orders/{orderId}/address"). - **dataElements** (Array of Strings) - Required - A list of data elements to include (e.g., ["shippingAddress"]). ### Request Example ```ruby rdt_resp = tokens_api.create_restricted_data_token({ "restrictedResources" => [ { "method" => "GET", "path" => "/orders/v0/orders/{orderId}/address", "dataElements" => ["shippingAddress"], }, { "method" => "GET", "path" => "/orders/v0/orders/{orderId}/buyerInfo", "dataElements" => ["buyerEmail"], }, ], }).parse ``` ### Response #### Success Response (200) - **restricted_data_token** (String) - The generated short-lived RDT. ### Usage Example ```ruby rdt = rdt_resp.restricted_data_token # short-lived token (1 hour) # Use RDT as the access token for the restricted operation orders_api = Peddler.orders.new("us-east-1", rdt) address = orders_api.get_order("113-1234567-7654321", included_data: ["shippingAddress"]).parse puts address.order.shipping_address.name puts address.order.shipping_address.city ``` ``` -------------------------------- ### Data Kiosk API - Create Query Source: https://github.com/lineofflight/peddler/blob/main/README.md Creates a GraphQL query to access analytical data. This includes creating the query and then polling for results. ```APIDOC ## Data Kiosk API - Create Query ### Description Provides access to Amazon's analytical data through GraphQL queries. This example shows how to initiate a query. ### Method `create_query` ### Parameters #### Request Body - **query** (string) - Required - The GraphQL query string. ### Request Example ```ruby api = Peddler.data_kiosk.new(aws_region, access_token) response = api.create_query(query: "query { salesAndTrafficByDate(...) { data { date sales } } }") ``` ### Response #### Success Response - **payload.queryId** - The ID of the created query, used for polling. ### Response Example ```ruby query_id = response.dig("payload", "queryId") # Poll for completion and download document ``` ``` -------------------------------- ### Handle HTTP Errors in v4.x (Before v5.0) Source: https://github.com/lineofflight/peddler/blob/main/UPGRADING.md Before v5.0, 5xx errors returned response objects that needed manual status checking. You could opt into v5 behavior by setting `raise_on_server_errors` to true. ```ruby # 5xx errors returned response objects response = api.get_orders(marketplaceIds: ["ATVPDKIKX0DER"]) if response.status >= 500 # Handle error end # Or opt-in to v5 behavior Peddler.configure do |config| config.raise_on_server_errors = true end ``` -------------------------------- ### Handle Operations Not Allowed in Sandbox Source: https://context7.com/lineofflight/peddler/llms.txt This snippet demonstrates how to catch and handle specific exceptions when attempting to run operations that are not permitted in a sandbox environment. It prints the error message associated with the `CannotSandbox` exception. ```ruby begin sandbox_api.some_production_only_operation rescue Peddler::API::CannotSandbox => e puts e.message # => "cannot run in a sandbox" end ``` -------------------------------- ### Sandbox Mode Source: https://context7.com/lineofflight/peddler/llms.txt Enables sandbox mode for any API instance, which uses Amazon's SP-API sandbox environment for safe testing with static responses. ```APIDOC ## Sandbox Mode — `API#sandbox` ### Description Switches any API instance to Amazon's SP-API sandbox environment, which returns static, pre-defined responses for safe testing without affecting live data. ### Usage Example ```ruby # Enable sandbox on any API api = Peddler.orders.new("us-east-1", access_token).sandbox puts api.sandbox? # => true puts api.endpoint_uri # => https://sandbox.sellingpartnerapi-na.amazon.com # Sandbox calls use faster rate-limit delays (0.2s vs real rate limit) sandbox_api = Peddler.catalog_items.new("us-east-1", access_token, retries: 2).sandbox # Static sandbox response for get_catalog_item item = sandbox_api.get_catalog_item("B08N5WRWNW", Peddler::Marketplace.ids("US")).parse puts item.summaries.first.item_name # pre-defined sandbox value ``` ``` -------------------------------- ### Hash-based Response Access in v4.x Source: https://github.com/lineofflight/peddler/blob/main/UPGRADING.md In v4.x, `.parse` returned a Hash by default. Access data using standard hash key notation. ```ruby response = api.get_catalog_item(asin: "B08N5WRWNW") item = response.parse # Hash in v4 title = item["summaries"].first["itemName"] ``` -------------------------------- ### Cache Access Token for Performance Source: https://github.com/lineofflight/peddler/blob/main/README.md Cache the generated access token for one hour to optimize performance by reusing it across multiple API calls. ```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 ``` -------------------------------- ### Data Kiosk API Source: https://context7.com/lineofflight/peddler/llms.txt This section explains how to use the Data Kiosk API to access analytical datasets via GraphQL queries, including submitting queries, polling for results, and downloading data. ```APIDOC ## Data Kiosk API — `create_query` / `get_query` / `get_document` This API provides access to Amazon's analytical datasets through GraphQL queries. It supports various schemas and offers type-safe response parsing. ### Submitting a GraphQL query Submit a GraphQL query to retrieve analytical data. #### Method ```ruby api.create_query ``` #### Parameters - **query** (string) - Required - The GraphQL query string. #### Response - **query_id** (string) - The ID of the submitted query. ### Polling for query status Check the status of a submitted query. #### Method ```ruby api.get_query ``` #### Parameters - **query_id** (string) - Required - The ID of the query. #### Response - **processing_status** (string) - The current processing status of the query (e.g., "DONE", "FATAL"). - **data_document_id** (string) - The ID of the data document containing the query results. ### Downloading the result document Retrieve the data document containing the query results. #### Method ```ruby api.get_document ``` #### Parameters - **doc_id** (string) - Required - The ID of the data document. #### Response - **document_url** (string) - The URL to download the data document. ### Example Usage ```ruby api = Peddler.data_kiosk.new("us-east-1", access_token) # Submit a GraphQL query query_resp = api.create_query({ "query" => <<~GQL, query MyQuery { analytics_salesAndTraffic_2023_11_15 { salesAndTrafficByDate( startDate: "2024-01-01" endDate: "2024-01-31" marketplaceIds: ["ATVPDKIKX0DER"] granularity: DAY ) { startDate endDate sales { orderedProductSales { amount currencyCode } totalOrderItems } traffic { browserSessions browserPageViews } } } } GQL }).parse query_id = query_resp.query_id # Poll until the query finishes loop do q = api.get_query(query_id).parse break if q.processing_status == "DONE" raise "Query failed" if q.processing_status == "FATAL" sleep 30 end # Download the result document doc_id = api.get_query(query_id).parse.data_document_id doc_url = api.get_document(doc_id).parse.document_url data = HTTP.get(doc_url).parse(:json) data["salesAndTrafficByDate"].each do |day| puts "#{day["startDate"]}: #{day["sales"]["orderedProductSales"]["amount"]}" end ``` ``` -------------------------------- ### Search Orders within a Time Window Source: https://context7.com/lineofflight/peddler/llms.txt Search for orders created or updated within the last 24 hours. Specify marketplace, fulfillment status, and page size. The response can be parsed into typed objects. ```ruby api = Peddler.orders.new("us-east-1", access_token, retries: 2) # Search orders created in the last 24 hours response = api.search_orders( created_after: 24.hours.ago.iso8601, marketplace_ids: Peddler::Marketplace.ids("US"), fulfillment_statuses: ["Unshipped", "PartiallyShipped"], max_results_per_page: 50, ) # Typed response via .parse result = response.parse result.orders.each do |order| puts order.amazon_order_id # => "113-1234567-7654321" puts order.order_status # => "Unshipped" puts order.order_total.amount # => "29.99" puts order.order_total.currency_code # => "USD" end ``` ```ruby # Paginate with next token if result.next_token next_page = api.search_orders( created_after: 24.hours.ago.iso8601, marketplace_ids: Peddler::Marketplace.ids("US"), pagination_token: result.next_token, ).parse end ``` -------------------------------- ### Typed Response Access in v5.0 (Recommended) Source: https://github.com/lineofflight/peddler/blob/main/UPGRADING.md With v5.0's typed responses, access attributes directly using dot notation for type-safe operations, e.g., `item.summaries.first.item_name`. ```ruby response = api.get_catalog_item(asin: "B08N5WRWNW") item = response.parse # Typed Structure object title = item.summaries.first.item_name # Type-safe attribute access ``` -------------------------------- ### Feeds API Source: https://context7.com/lineofflight/peddler/llms.txt This section describes the six-step workflow for uploading data using the Feeds API, including creating feed documents, uploading content, submitting feeds, and retrieving results. ```APIDOC ## Feeds API — `create_feed_document` / `upload_feed_document` / `create_feed` / `get_feed` / `download_result_feed_document` This API facilitates uploading data such as listings, prices, and inventory to Amazon. It involves a six-step process, with helper methods for S3 presigned URL operations. ### Step 1: Create a feed document placeholder This step obtains an upload URL and a feed document ID. #### Method ```ruby api.create_feed_document ``` #### Parameters - **contentType** (string) - Required - The content type of the feed (e.g., "text/xml; charset=UTF-8"). #### Response - **url** (string) - The S3 presigned URL for uploading the feed content. - **feed_document_id** (string) - The ID for the feed document. ### Step 2: Upload feed content to S3 Upload the prepared feed content to the provided S3 URL. #### Method ```ruby api.upload_feed_document ``` #### Parameters - **upload_url** (string) - Required - The S3 presigned URL obtained from `create_feed_document`. - **content** (string) - Required - The feed content (e.g., XML data). - **contentType** (string) - Required - The content type of the feed. ### Step 3: Submit the feed Submit the feed for processing after uploading the content. #### Method ```ruby api.create_feed ``` #### Parameters - **feedType** (string) - Required - The type of feed (e.g., "POST_INVENTORY_AVAILABILITY_DATA"). - **marketplaceIds** (array of strings) - Required - A list of marketplace IDs. - **inputFeedDocumentId** (string) - Required - The ID of the feed document created in Step 1. #### Response - **feed_id** (string) - The ID of the submitted feed. ### Step 4: Poll until done Periodically check the status of the feed until it is processed. #### Method ```ruby api.get_feed ``` #### Parameters - **feed_id** (string) - Required - The ID of the feed. #### Response - **processing_status** (string) - The current processing status of the feed (e.g., "DONE", "FATAL"). ### Step 5: Retrieve result document URL Get the URL for the result document once the feed processing is complete. #### Method ```ruby api.get_feed ``` #### Parameters - **feed_id** (string) - Required - The ID of the feed. #### Response - **result_feed_document_id** (string) - The ID of the result feed document. ### Step 6: Download and inspect the processing report Download the result content using the obtained URL. #### Method ```ruby api.download_result_feed_document ``` #### Parameters - **result_doc_url** (string) - Required - The URL of the result document. #### Response The content of the processing report. ``` -------------------------------- ### Manage Inventory Feed using Feeds API Source: https://github.com/lineofflight/peddler/blob/main/README.md Manage inventory feeds using the Feeds API. This involves creating a feed document, uploading the document, and then submitting the feed. Ensure the feed XML file is correctly formatted. ```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")) ``` -------------------------------- ### Request a report Source: https://context7.com/lineofflight/peddler/llms.txt This section details how to request and retrieve reports using the Peddler API. It covers creating a report, polling for its completion status, and downloading the report content. ```APIDOC ## Request a report This operation allows users to request and retrieve reports from the Peddler API. ### Method ```ruby api.create_report ``` ### Parameters - **reportType** (string) - Required - The type of report to generate (e.g., "GET_FLAT_FILE_OPEN_LISTINGS_DATA"). - **marketplaceIds** (array of strings) - Required - A list of marketplace IDs for which to generate the report. ### Request Example ```ruby create_resp = api.create_report({ "reportType" => "GET_FLAT_FILE_OPEN_LISTINGS_DATA", "marketplaceIds" => Peddler::Marketplace.ids("US") }).parse ``` ### Response - **report_id** (string) - The ID of the created report. ### Retrieving Report Status and Content After creating a report, you can poll its status and download the content using the `get_report` and `download_report_document` methods. ```ruby report_id = create_resp.report_id loop do report = api.get_report(report_id).parse break if report.processing_status == "DONE" raise "Report failed" if report.processing_status == "FATAL" sleep 30 end doc_id = api.get_report(report_id).parse.report_document_id content = api.download_report_document(doc_id).to_s # Alternatively, get the URL and download url = api.get_report_document(doc_id).parse.url content = api.download_report_document(url).to_s ``` ### Creating Scheduled Reports This operation allows users to schedule recurring reports. ### Method ```ruby api.create_report_schedule ``` ### Parameters - **reportType** (string) - Required - The type of report to schedule. - **marketplaceIds** (array of strings) - Required - A list of marketplace IDs. - **period** (string) - Required - The schedule period (e.g., "PT48H" for every 48 hours). ### Request Example ```ruby api.create_report_schedule({ "reportType" => "GET_MERCHANT_LISTINGS_ALL_DATA", "marketplaceIds" => Peddler::Marketplace.ids("US") "period" => "PT48H" }) ``` ``` -------------------------------- ### Reports API - create_report / get_report / get_report_document / download_report_document Source: https://context7.com/lineofflight/peddler/llms.txt Request and download various types of SP-API reports, such as orders, inventory, and financial reports. Includes a helper function to download report document content directly. ```APIDOC ## Reports API — `create_report` / `get_report` / `get_report_document` / `download_report_document` Requests and downloads SP-API reports (orders, inventory, financial, fulfillment, etc.). Includes a `download_report_document` helper that resolves a document ID to content in one call. ### Method ```ruby api = Peddler.reports.new("us-east-1", access_token) ``` ``` -------------------------------- ### Search Catalog Items by ASIN Source: https://context7.com/lineofflight/peddler/llms.txt Search for catalog items using ASINs. Specify the identifier type and the data to be included in the response. ```ruby # Search by ASIN identifier results = api.search_catalog_items( Peddler::Marketplace.ids("US"), identifiers: ["B08N5WRWNW"], identifiers_type: "ASIN", included_data: ["summaries", "attributes"], ).parse ```