paapi5

package module
v0.17.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 7, 2026 License: Apache-2.0 Imports: 14 Imported by: 2

README

pa-api -- Go client for the Amazon Creators API

check vulns lint status GitHub license GitHub release

A Go client for Amazon's Creators API, the OAuth2-based replacement for the now-retired Product Advertising API v5 (PA-API). The package keeps the import path github.com/goark/pa-api and the package name paapi5 so existing call sites need only minor changes; under the hood the wire protocol, authentication and host all change.

This package requires Go 1.25 or later.

Go version policy
  • The source of truth for the minimum supported Go version is go.mod.
  • README and CI are kept aligned with go.mod.
  • If the go directive changes, update this README line in the same change.

Migrating from PA-API v5

Amazon retired PA-API v5 on 2026-05-15 and replaced it with the Creators API. The two big differences:

PA-API v5 (old) Creators API (new)
Host webservices.amazon.<tld> per locale Single creatorsapi.amazon for every marketplace
Marketplace selection Marketplace body field x-marketplace request header
Auth AWS SigV4 (Access Key + Secret Key) OAuth2 client_credentials (Credential ID + Credential Secret + Version)
Body keys PascalCase lowerCamelCase
Resource enums Images.Primary.Medium images.primary.medium
Offers (V1) Available Removed; use OffersV2

Code-level changes you should expect when upgrading:

  • CreateClient / DefaultClient arguments: the second/third positional arguments are now credentialID and credentialSecret (Creators API credentials issued via Associates Central) instead of AWS access/secret keys.
  • q.EnableOffers() is now an alias for q.EnableOffersV2() with a deprecation comment; the V1 Offers resource is gone.
  • Server.Region() is deprecated and is no longer used by the client; it remains for back-compat callers that record it as metadata.
  • Response JSON keys returned by the Creators API are lowerCamelCase. The existing Go field names in entity.Response decode case-insensitively from these new keys, but if your code re-serialises a Response value you'll see PascalCase output for some fields and lowerCamelCase for the explicitly tagged ones (notably id).
  • SearchItems filters Marketplace, PartnerType, Merchant, and OfferCount are silently ignored — those fields are not accepted by the Creators API. Existing code using those filters compiles but the values are dropped.
  • Query constructor marketplace arguments are compatibility-only (NewGetItems, NewSearchItems, NewGetVariations, NewGetBrowseNodes). Actual routing always uses the client's configured marketplace via the x-marketplace header, so set marketplace on Server/Client (creatorsapi.WithMarketplace(...)) rather than per-query.
Ignored legacy request fields

The library keeps several legacy knobs for source compatibility, but the Creators API does not accept them in request bodies. They are currently treated as no-ops.

Legacy field / option Previous behavior (PA-API v5) Current behavior (Creators API)
Marketplace request body field Selected target marketplace in-body Ignored in-body. Routing is done by x-marketplace header
PartnerType (Associates) Explicit body parameter Ignored. Partner type is implicit
Merchant Offer filtering selector Ignored
OfferCount Offer summary limiter Ignored
Marketplace routing precedence

Marketplace selection is evaluated in this order:

  1. Server/Client marketplace (for example creatorsapi.WithMarketplace(...))
  2. Request header x-marketplace sent by the client

Query constructor marketplace arguments are retained only for compatibility and are not used to route requests.

Credential Version map

Creators API credentials are region-group scoped. Use credentials that match the marketplace group you call.

New applications typically receive v3.x credentials (Login with Amazon token endpoints). v2.x credentials use regional Cognito endpoints and a different OAuth scope and catalog Authorization header shape; if Associates Central still shows 2.1/2.2/2.3, pass creatorsapi.WithCredentialVersion("2.1") (etc.) on CreateClient.

Credential Version Region group Token endpoint (default) Catalog Authorization
3.1 North America https://api.amazon.com/auth/o2/token Bearer <token>
3.2 Europe / Middle East / India https://api.amazon.co.uk/auth/o2/token Bearer <token>
3.3 Far East https://api.amazon.co.jp/auth/o2/token Bearer <token>
2.1 North America https://creatorsapi.auth.us-east-1.amazoncognito.com/oauth2/token Bearer <token>, Version 2.1
2.2 Europe / Middle East / India https://creatorsapi.auth.eu-south-2.amazoncognito.com/oauth2/token Bearer <token>, Version 2.2
2.3 Far East https://creatorsapi.auth.us-west-2.amazoncognito.com/oauth2/token Bearer <token>, Version 2.3

Example marketplace groups (same as before): NA — www.amazon.com, www.amazon.ca, www.amazon.com.mx, www.amazon.com.br; EU — www.amazon.co.uk, www.amazon.de, www.amazon.fr, www.amazon.in, www.amazon.sa, www.amazon.ae; FE — www.amazon.co.jp, www.amazon.sg, www.amazon.com.au.

If token acquisition fails with an auth error, verify that your credential version and marketplace group match.

Rate limits and retry guidance

Amazon starts new credential sets with low throughput (commonly around 1 TPS; check your Associates Central quota for authoritative limits). Build callers with backpressure and retry control.

Recommended client behavior:

  • Treat 429 and transient 5xx as retryable.
  • Use exponential backoff with jitter.
  • Cap retry attempts and total request timeout.
  • Avoid synchronized retries across workers.
  • Consider per-credential rate limiting in your application.
Getting Creators API credentials

Only the primary Amazon Associates account owner can mint credentials. From Associates Central go to ToolsCreators APICreate Application, then Add New Credential. Copy the Credential Secret immediately — it is only shown once. Note the Credential Version shown for your credential (3.1/3.2/3.3 for Login with Amazon, or legacy 2.1/2.2/2.3 for Cognito). You'll need it if you call multiple regions from the same process or if your credential region group does not match the configured marketplace.

Quick migration checklist

Use this path when migrating existing PA-API v5 call sites:

  1. Keep the import path as github.com/goark/pa-api (alias as creatorsapi in examples if preferred).
  2. Replace client credential inputs: AWS Access Key / Secret Key -> Creators API Credential ID / Credential Secret.
  3. Configure marketplace on Server/Client (WithMarketplace) and do not rely on per-query marketplace arguments.
  4. Replace V1 offers usage with OffersV2 (EnableOffersV2; EnableOffers remains as a compatibility alias).
  5. Remove expectations around Merchant, OfferCount, and PartnerType request effects; these are ignored.
  6. Confirm Credential Version matches the marketplace group you call (3.1/3.2/3.3 by default per marketplace, or 2.1/2.2/2.3 for legacy Cognito credentials via WithCredentialVersion).
  7. Add retry and rate-limit control for 429 and transient 5xx responses.
  8. Run local verification with your project's standard test/lint workflow before opening a PR.

Usage

Create a server configuration
sv := creatorsapi.New() // default: US marketplace, NA credential version 3.1 (Login with Amazon)
fmt.Println("Marketplace:", sv.Marketplace())
fmt.Println("CredentialVersion:", sv.CredentialVersion())
fmt.Println("URL:", sv.URL(creatorsapi.GetItems.Path()))
// Output:
// Marketplace: www.amazon.com
// CredentialVersion: 3.1
// URL: https://creatorsapi.amazon/catalog/v1/getItems

For another marketplace:

sv := creatorsapi.New(creatorsapi.WithMarketplace(creatorsapi.LocaleJapan)) // Japan -> credential version 3.3
fmt.Println("Marketplace:", sv.Marketplace())
fmt.Println("CredentialVersion:", sv.CredentialVersion())
// Output:
// Marketplace: www.amazon.co.jp
// CredentialVersion: 3.3

The credential version is auto-derived from the configured marketplace's region group (3.1/3.2/3.3). Override with creatorsapi.WithCredentialVersion("2.2") when using legacy Cognito credentials (2.1/2.2/2.3), or when your credential group differs from the marketplace default.

Create a client
client := creatorsapi.DefaultClient("mytag-20", "YOUR_CREDENTIAL_ID", "YOUR_CREDENTIAL_SECRET")
fmt.Println("Marketplace:", client.Marketplace())
// Output:
// Marketplace: www.amazon.com

For a different marketplace plus a custom *http.Client:

client := creatorsapi.New(
    creatorsapi.WithMarketplace(creatorsapi.LocaleJapan),
).CreateClient(
    "mytag-20",
    "YOUR_CREDENTIAL_ID",
    "YOUR_CREDENTIAL_SECRET",
    creatorsapi.WithHttpClient(http.DefaultClient),
)

The client transparently obtains and caches an OAuth2 access token from the appropriate Cognito endpoint (expires_in minus a 30-second leeway) and forwards it to the API as Authorization: Bearer <token>, Version <2.x>.

Sample code

GetItems
package main

import (
    "context"
    "fmt"

    creatorsapi "github.com/goark/pa-api"
    "github.com/goark/pa-api/entity"
    "github.com/goark/pa-api/query"
)

func main() {
    client := creatorsapi.New(
        creatorsapi.WithMarketplace(creatorsapi.LocaleJapan),
    ).CreateClient(
        "mytag-20",
        "YOUR_CREDENTIAL_ID",
        "YOUR_CREDENTIAL_SECRET",
    )

    q := query.NewGetItems(
        client.Marketplace(),
        client.PartnerTag(),
        client.PartnerType(),
    ).ASINs([]string{"B07YCM5K55"}).EnableImages().EnableItemInfo().EnableParentASIN()

    body, err := client.RequestContext(context.Background(), q)
    if err != nil {
        fmt.Printf("%+v\n", err)
        return
    }

    res, err := entity.DecodeResponse(body)
    if err != nil {
        fmt.Printf("%+v\n", err)
        return
    }
    fmt.Println(res.String())
}
GetVariations
q := query.NewGetVariations(
    client.Marketplace(),
    client.PartnerTag(),
    client.PartnerType(),
).ASIN("B07YCM5K55").EnableImages().EnableItemInfo().EnableParentASIN()

body, err := client.RequestContext(context.Background(), q)
SearchItems
q := query.NewSearchItems(
    client.Marketplace(),
    client.PartnerTag(),
    client.PartnerType(),
).Search(query.Keywords, "数学ガール").EnableImages().EnableItemInfo().EnableParentASIN()

body, err := client.RequestContext(context.Background(), q)
GetBrowseNodes
q := query.NewGetBrowseNodes(
    client.Marketplace(),
    client.PartnerTag(),
    client.PartnerType(),
).BrowseNodeIds([]string{"3040", "3045"}).EnableBrowseNodes()

body, err := client.RequestContext(context.Background(), q)

Contributors

Many thanks for contributors

Documentation

Overview

Package paapi5 APIs for Amazon Product Advertising API v5 client

Index

Examples

Constants

View Source
const (
	CredentialVersionNA = "2.1" // North America — Cognito pool (legacy)
	CredentialVersionEU = "2.2" // Europe / Middle East / India — Cognito
	CredentialVersionFE = "2.3" // Far East — Cognito

	CredentialVersionNAv3 = "3.1" // North America — Login with Amazon
	CredentialVersionEUv3 = "3.2" // Europe / Middle East / India — LwA
	CredentialVersionFEv3 = "3.3" // Far East — LwA
)

Credential version codes for the Amazon Creators API.

v2.x values select the regional Cognito (`…amazoncognito.com/oauth2/token`) token endpoint and require `Authorization: Bearer <token>, Version <v>` on catalog requests.

v3.x values select the regional Login with Amazon (`api.amazon…/auth/o2/token`) endpoint; tokens are obtained with HTTP Basic auth and scope `creatorsapi::default`, and catalog requests use `Authorization: Bearer <token>` without a Version suffix.

Variables

This section is empty.

Functions

func AuthEndpointFor added in v0.16.0

func AuthEndpointFor(version string) string

AuthEndpointFor returns the default OAuth2 token endpoint URL for the given credential version. Returns the empty string for unknown versions.

Types

type Client

type Client interface {
	Marketplace() string
	PartnerTag() string
	PartnerType() string
	Request(Query) ([]byte, error)
	RequestContext(context.Context, Query) ([]byte, error)
}

Client interface

Example
package main

import (
	"context"
	"fmt"
	"net/http"

	paapi5 "github.com/goark/pa-api"
)

func main() {
	//Create client for Japan marketplace
	client := paapi5.New(
		paapi5.WithMarketplace(paapi5.LocaleJapan),
	).CreateClient(
		"mytag-20",
		"CRED-ID",
		"CRED-SECRET",
		paapi5.WithContext(context.Background()),
		paapi5.WithHttpClient(http.DefaultClient),
	)
	fmt.Println("Marketplace:", client.Marketplace())
}
Output:
Marketplace: www.amazon.co.jp

func DefaultClient

func DefaultClient(associateTag, credentialID, credentialSecret string) Client

DefaultClient function returns a default Client instance using the supplied associate tag and Creators API credential pair.

Example
package main

import (
	"fmt"

	paapi5 "github.com/goark/pa-api"
)

func main() {
	client := paapi5.DefaultClient("mytag-20", "CRED-ID", "CRED-SECRET") //Create default client
	fmt.Println("Marketplace:", client.Marketplace())
}
Output:
Marketplace: www.amazon.com

type ClientOptFunc

type ClientOptFunc func(*client)

ClientOptFunc type is self-referential function type for Server.CreateClient method. (functional options pattern)

func WithAuthEndpoint added in v0.16.0

func WithAuthEndpoint(endpoint string) ClientOptFunc

WithAuthEndpoint overrides the OAuth2 token endpoint. Defaults to the token endpoint resolved from the credential version (or LWA for v3.x).

func WithContext deprecated

func WithContext(ctx context.Context) ClientOptFunc

WithContext is retained as a no-op for backward compatibility. Pass a context to RequestContext instead.

Deprecated: this option does nothing.

func WithCredentialVersion added in v0.16.0

func WithCredentialVersion(version string) ClientOptFunc

WithCredentialVersion overrides the credential version derived from the marketplace. Use this when your Creators API credential set was issued for a different region than the configured marketplace would imply.

func WithHttpClient

func WithHttpClient(hc *http.Client) ClientOptFunc

WithHttpClient function returns a ClientOptFunc that configures the underlying http.Client used for both API and OAuth2 token requests.

type Error

type Error int

Error is error codes for paapi5 package

const (
	ErrNullPointer Error = iota + 1 //Null reference instance
	ErrHTTPStatus                   //Bad HTTP status
	ErrNoData                       //No response data
)

func (Error) Error

func (e Error) Error() string

Error method returns error message. This method is a implementation of error interface.

type Marketplace

type Marketplace interface {
	String() string
	HostName() string
	Region() string
	Language() string
}

Marketplace is the interface implemented by locale providers.

Note: this interface is deliberately kept compatible with the pre-Creators API contract. The Creators API credential version is reported via the optional credentialVersioner type-assertion (satisfied by MarketplaceEnum) rather than added to this interface, so external implementations of Marketplace continue to compile unchanged.

func MarketplaceOf

func MarketplaceOf(s string) Marketplace

MarketplaceOf function returns Marketplace instance from service domain.

type MarketplaceEnum

type MarketplaceEnum int

MarketplaceEnum is enumeration of locale information.

const (
	LocaleUnknown            MarketplaceEnum = iota //Unknown local
	LocaleAustralia                                 //Australia
	LocaleBrazil                                    //Brazil
	LocaleCanada                                    //Canada
	LocaleEgypt                                     //Egypt
	LocaleFrance                                    //France
	LocaleGermany                                   //Germany
	LocaleIndia                                     //India
	LocaleIreland                                   //Ireland
	LocaleItaly                                     //Italy
	LocaleJapan                                     //Japan
	LocaleMexico                                    //Mexico
	LocaleNetherlands                               //Netherlands
	LocalePoland                                    //Poland
	LocaleSingapore                                 //Singapore
	LocaleSaudiArabia                               //SaudiArabia
	LocaleSpain                                     //Spain
	LocaleSweden                                    //Sweden
	LocaleTurkey                                    //Turkey
	LocaleUnitedArabEmirates                        //United Arab Emirates
	LocaleUnitedKingdom                             //United Kingdom
	LocaleUnitedStates                              //United States
	DefaultMarketplace       = LocaleUnitedStates
)

func (MarketplaceEnum) CredentialVersion added in v0.16.0

func (m MarketplaceEnum) CredentialVersion() string

CredentialVersion returns the Creators API credential version code that must be paired with credentials used to call this marketplace.

func (MarketplaceEnum) HostName

func (m MarketplaceEnum) HostName() string

HostName returns the Creators API service host. The host is the same for every marketplace; the marketplace itself is communicated via the `x-marketplace` request header.

func (MarketplaceEnum) Language

func (m MarketplaceEnum) Language() string

Language returns language name of Marketplace.

func (MarketplaceEnum) Region deprecated

func (m MarketplaceEnum) Region() string

Region returns the historical AWS region associated with this marketplace.

Deprecated: the Creators API does not use AWS SigV4 signing; this value is no longer used for request construction. Use CredentialVersion() to choose the right Creators API credential set instead.

func (MarketplaceEnum) String

func (m MarketplaceEnum) String() string

String returns marketplace name of Marketplace.

type Operation

type Operation int

Operation is enumeration of Creators API operations.

const (
	NullOperation  Operation = iota //Unknown
	GetVariations                   //GetVariations
	GetItems                        //GetItems
	SearchItems                     //SearchItems
	GetBrowseNodes                  //GetBrowseNodes
)

func (Operation) MarshalJSON

func (c Operation) MarshalJSON() ([]byte, error)

MarshalJSON method implements the json.Marshaler interface.

func (Operation) Path

func (c Operation) Path() string

Path method returns the URL path of the Creators API operation.

func (Operation) String

func (c Operation) String() string

String method is an implementation of fmt.Stringer interface.

func (Operation) Target deprecated

func (c Operation) Target() string

Target returns the value historically used for the X-Amz-Target header under PA-API v5 SigV4 signing.

Deprecated: the Creators API does not use the X-Amz-Target header (the operation is selected via URL path; see Path). This method returns the historical PA-API v5 value for back-compat callers only and will be removed in a future major version.

func (*Operation) UnmarshalJSON

func (c *Operation) UnmarshalJSON(b []byte) error

UnmarshalJSON method implements json.Unmarshaler interface.

type Query

type Query interface {
	Operation() Operation
	Payload() ([]byte, error)
}

Query interface for Client type

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server type is a configuration of the Amazon Creators API service.

Example
package main

import (
	"fmt"

	paapi5 "github.com/goark/pa-api"
)

func main() {
	sv := paapi5.New() //Create default server
	fmt.Println("Marketplace:", sv.Marketplace())
	fmt.Println("Region:", sv.Region())
	fmt.Println("AcceptLanguage:", sv.AcceptLanguage())
	fmt.Println("CredentialVersion:", sv.CredentialVersion())
	fmt.Println("URL:", sv.URL(paapi5.GetItems.Path()))
}
Output:
Marketplace: www.amazon.com
Region: us-east-1
AcceptLanguage: en_US
CredentialVersion: 3.1
URL: https://creatorsapi.amazon/catalog/v1/getItems

func New

func New(opts ...ServerOptFunc) *Server

New function returns a Server instance with options.

Example
package main

import (
	"fmt"

	paapi5 "github.com/goark/pa-api"
)

func main() {
	sv := paapi5.New(paapi5.WithMarketplace(paapi5.LocaleJapan)) //Create server in Japan region
	fmt.Println("Marketplace:", sv.Marketplace())
	fmt.Println("Region:", sv.Region())
	fmt.Println("AcceptLanguage:", sv.AcceptLanguage())
	fmt.Println("CredentialVersion:", sv.CredentialVersion())
	fmt.Println("URL:", sv.URL(paapi5.GetItems.Path()))
}
Output:
Marketplace: www.amazon.co.jp
Region: us-west-2
AcceptLanguage: ja_JP
CredentialVersion: 3.3
URL: https://creatorsapi.amazon/catalog/v1/getItems

func (*Server) AWS4Request deprecated

func (s *Server) AWS4Request() string

AWS4Request returns the AWS4 request token used by PA-API v5's SigV4 signing.

Deprecated: the Creators API does not use AWS SigV4 signing. This method returns the historical PA-API v5 value for back-compat callers only and will be removed in a future major version.

func (*Server) Accept

func (s *Server) Accept() string

Accept method returns the Accept header value used for API calls.

func (*Server) AcceptLanguage

func (s *Server) AcceptLanguage() string

AcceptLanguage method returns the Accept-Language parameter for API calls.

func (*Server) AuthEndpoint added in v0.16.0

func (s *Server) AuthEndpoint() string

AuthEndpoint returns the configured (or version-derived) OAuth2 token endpoint URL.

func (*Server) ContentEncoding deprecated

func (s *Server) ContentEncoding() string

ContentEncoding returns the Content-Encoding header value used by PA-API v5.

Deprecated: the Creators API does not use a Content-Encoding header. This method returns the historical PA-API v5 value for back-compat callers only and will be removed in a future major version.

func (*Server) ContentType

func (s *Server) ContentType() string

ContentType method returns the Content-Type header value for API calls.

func (*Server) CreateClient

func (s *Server) CreateClient(associateTag, credentialID, credentialSecret string, opts ...ClientOptFunc) Client

CreateClient method returns a Client instance with the supplied associate (partner) tag and Amazon Creators API credential pair.

credentialID and credentialSecret correspond to the Credential ID and Credential Secret issued in Associates Central > Tools > Creators API.

func (*Server) CredentialVersion added in v0.16.0

func (s *Server) CredentialVersion() string

CredentialVersion returns the Creators API credential version that matches the configured marketplace's region group. When the configured Marketplace implementation does not expose CredentialVersion(), the default North America version is returned.

func (*Server) HMACAlgorithm deprecated

func (s *Server) HMACAlgorithm() string

HMACAlgorithm returns the HMAC algorithm string used by PA-API v5's SigV4 signing.

Deprecated: the Creators API does not use AWS SigV4 signing. This method returns the historical PA-API v5 value for back-compat callers only and will be removed in a future major version.

func (*Server) HostName

func (s *Server) HostName() string

HostName method returns the API host.

func (*Server) Marketplace

func (s *Server) Marketplace() string

Marketplace method returns the marketplace name.

func (*Server) Region deprecated

func (s *Server) Region() string

Region method returns the historical AWS region associated with the configured marketplace.

Deprecated: the Creators API does not use AWS SigV4 signing; the value is retained for back-compat callers only.

func (*Server) ServiceName deprecated

func (s *Server) ServiceName() string

ServiceName returns the AWS service name used by PA-API v5's SigV4 signing.

Deprecated: the Creators API does not use AWS SigV4 signing. This method returns the historical PA-API v5 value for back-compat callers only and will be removed in a future major version.

func (*Server) URL

func (s *Server) URL(path string) *url.URL

URL method returns url of service server information for the Creators API.

type ServerOptFunc

type ServerOptFunc func(*Server)

ServerOptFunc type is self-referential function type for New functions. (functional options pattern)

func WithLanguage

func WithLanguage(language string) ServerOptFunc

WithLanguage function returns a ServerOptFunc that sets the desired response language. The Creators API does not honour an Accept-Language header; the value is forwarded for back-compat but callers should also use the LanguagesOfPreference body field for the same purpose.

func WithMarketplace

func WithMarketplace(marketplace Marketplace) ServerOptFunc

WithMarketplace function returns a ServerOptFunc that sets the Marketplace.

func WithServerAuthEndpoint added in v0.16.0

func WithServerAuthEndpoint(endpoint string) ServerOptFunc

WithServerAuthEndpoint overrides the OAuth2 token endpoint resolved from the credential version. Primarily useful for tests.

func WithServerHost added in v0.16.0

func WithServerHost(host string) ServerOptFunc

WithServerHost overrides the API service host. Useful for tests pointing at httptest.Server. Pass an empty string to fall back to the default.

func WithServerScheme added in v0.16.0

func WithServerScheme(scheme string) ServerOptFunc

WithServerScheme overrides the URL scheme used by the API host. Useful for tests that need plain HTTP.

type TimeStamp

type TimeStamp struct {
	time.Time
}

TimeStamp is wrapper class of time.Time

func NewTimeStamp

func NewTimeStamp(tm time.Time) TimeStamp

NewTimeStamp returns TimeStamp instance

func (TimeStamp) String

func (t TimeStamp) String() string

func (TimeStamp) StringDate

func (t TimeStamp) StringDate() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL