python-amazon-paapi

repository·master·Indexed 43 days ago

https://github.com/sergioteula/python-amazon-paapi

A Python wrapper for the Amazon Creators API (version 7.1.0) providing an object-oriented and async-capable interface. It allows developers to access product details, search for items, manage variations, and handle feeds and reports. The library supports both synchronous and asynchronous operations via AsyncAmazonCreatorsApi and includes built-in support for ASIN extraction from URLs and marketplace configuration across multiple countries.

Tokens
10.3K
Snippets
38
Records
49
Agent score
54%

What's inside python-amazon-paapi

  1. Handle errors in version 7

    master

    In version 7, errors are mapped directly from the Creators API response. While except RequestError still catches 401 (AuthenticationError) and 403 (AccessDeniedError), a 400 error that previously raised RequestError now raises InvalidArgumentError.

    To catch all library-specific errors, catch AmazonCreatorsApiError. Note that error messages now include specific details from Amazon, such as the rejected fields and request identifier, so any logic relying on exact error message text should be reviewed.

    from amazon_creatorsapi.errors import AmazonCreatorsApiError
    
    try:
        items = api.get_items(["B01N5IB20Q"])
    except AmazonCreatorsApiError as error:  # Catches every error of the library
        print(error)
  2. Configure custom host and auth_endpoint

    master

    In version 7, every client instance maintains its own configuration. Global configuration via Configuration.set_default() is no longer supported.

    To point the client to a different server (e.g., for testing against a mock server), use the host argument. To use a specific authentication endpoint (useful for using unsupported API versions), use the auth_endpoint argument.

    # Use a custom host for testing
    api = AmazonCreatorsApi(..., host="http://localhost:8080")
    
    # Use a specific auth endpoint for a specific version
    api = AmazonCreatorsApi(
        ...,
        version="2.4",
        auth_endpoint="https://creatorsapi.auth.eu-west-1.amazoncognito.com/oauth2/token",
    )
  3. Search items with required criteria

    master

    The search_items method now requires at least one search criterion. A request containing only filters will raise an InvalidArgumentError. You must include at least one of the following: keywords, actor, artist, author, brand, title, browse_node_id, or search_index.

    # This will raise InvalidArgumentError
    api.search_items(min_price=1000) 
    
    # This is correct
    api.search_items(keywords="laptop", min_price=1000) 
  4. Quick start with AmazonCreatorsApi

    master

    To use the library, initialize the AmazonCreatorsApi client with your Amazon Associates Creators API credentials. You can then use the client to fetch product information using ASINs.

    Required parameters for AmazonCreatorsApi:

    • credential_id: Your Creators API credential ID.
    • credential_secret: Your Creators API credential secret.
    • version: The API version (e.g., "2.2").
    • tag: Your affiliate tag.
    • country: The Country enum value representing the target market (e.g., Country.US).
    from amazon_creatorsapi import AmazonCreatorsApi, Country
    
    api = AmazonCreatorsApi(
        credential_id="your_credential_id",
        credential_secret="your_credential_secret",
        version="2.2",
        tag="your-affiliate-tag",
        country=Country.US,
    )
    
    # Get product information by ASIN
    items = api.get_items(["B01N5IB20Q"])
    print(items[0].item_info.title.display_value)
  5. Configure timeouts and retries in AmazonCreatorsApi

    master

    Timeouts

    The synchronous client now has default timeouts: 5 seconds to connect and 25 seconds to read. You can customize this using the timeout parameter. Setting timeout=None allows the client to wait indefinitely.

    Retries

    The client automatically retries requests that fail with 429, 500, 502, 503, or 504. It uses an exponential backoff strategy, honoring the Retry-After header up to 30 seconds. To disable automatic retries (e.g., if you have your own backoff logic), set retries=0.

    # Custom timeout
    api = AmazonCreatorsApi(..., timeout=60)    # Wait up to a minute
    api = AmazonCreatorsApi(..., timeout=None)  # Wait indefinitely
    
    # Disable retries
    api = AmazonCreatorsApi(..., retries=0)
  6. Quick start: Initialize and get product info

    master

    Use the following pattern to initialize the client and retrieve product information using either an ASIN or an Amazon URL.

    from amazon_creatorsapi import AmazonCreatorsApi, Country
    
    # Initialize with your Creators API credentials
    api = AmazonCreatorsApi(
        credential_id="your_credential_id",
        credential_secret="your_credential_secret",
        version="2.2",
        tag="your-affiliate-tag",
        country=Country.US,
    )
    
    # Get product information by ASIN
    items = api.get_items(["B01N5IB20Q"])
    print(items[0].item_info.title.display_value)
    
    # Or use Amazon URLs directly
    items = api.get_items(["https://www.amazon.com/dp/B01N5IB20Q"])
  7. Use the AsyncAmazonCreatorsApi with async/await

    master

    The async API provides the same methods, parameters, and errors as the synchronous version, but must be called with await.

    It is highly recommended to use AsyncAmazonCreatorsApi as an async context manager. This enables connection pooling, allowing multiple requests to reuse the same connection. If you instantiate it without a context manager, every request will open and close its own connection, which is less efficient.

    from amazon_creatorsapi import Country
    from amazon_creatorsapi.aio import AsyncAmazonCreatorsApi
    
    # Use as async context manager (recommended for connection pooling)
    async with AsyncAmazonCreatorsApi(
        credential_id="your_credential_id",
        credential_secret="your_credential_secret",
        version="2.2",
        tag="your-affiliate-tag",
        country=Country.US,
    ) as api:
        items = await api.get_items(["B01N5IB20Q"])
        results = await api.search_items(keywords="laptop")
        variations = await api.get_variations("B01N5IB20Q")
        nodes = await api.get_browse_nodes(["667049031"])
        feeds = await api.list_feeds()
        reports = await api.list_reports()
  8. Work with SDK models and enums

    master

    All SDK models and enums are available via amazon_creatorsapi.models. You can use these to provide type-safe arguments for filtering, sorting, and resource selection.

    Resource Selection

    By default, every method requests all available resources for that operation. You can pass a list of GetItemsResource members to the resources parameter to narrow the response. This makes the response smaller and faster, but any fields not requested will return as None.

    Note that resource names follow the API schema where dots become _DOT_ and colons become _COLON_ (e.g., itemInfo.title becomes ITEM_INFO_DOT_TITLE).

    from amazon_creatorsapi.models import (
        Condition,
        GetItemsResource,
        Item,
        SearchItemsResource,
        SortBy,
    )
    
    # Use Condition enum for filtering
    items = api.get_items(["B01N5IB20Q"], condition=Condition.NEW)
    
    # Use SortBy enum for search ordering
    results = api.search_items(
        keywords="laptop",
        sort_by=SortBy.PRICE_COLON_LOW_TO_HIGH,
    )
    
    # Specify which resources to retrieve
    resources = [
        GetItemsResource.ITEM_INFO_DOT_TITLE,
        GetItemsResource.OFFERS_V2_DOT_LISTINGS_DOT_PRICE,
    ]
    items = api.get_items(["B01N5IB20Q"], resources=resources)
  9. Migrate from amazon_paapi to amazon_creatorsapi

    master

    Starting from version 7.0.0, the amazon_paapi module has been removed. Users must migrate to the amazon_creatorsapi module which utilizes Amazon's Creators API. This migration involves updating imports, changing initialization parameters, and adjusting method signatures to include a resources parameter.

    Upgrade Command

    To upgrade to the latest version containing the Creators API support, run:

    pip install python-amazon-paapi --upgrade
  10. Handle missing items in get_items

    master

    In version 7, get_items raises ItemsNotFoundError if none of the requested items are found.

    To avoid exceptions and receive a list containing all requested identifiers (where missing items are returned as Item objects containing only their asin), use the include_unavailable=True parameter. You can inspect the errors attribute of the returned list to find the reason for any missing items.

    from amazon_creatorsapi.errors import ItemsNotFoundError
    
    # Option 1: Catch the error
    try:
        items = api.get_items(["B01N5IB20Q", "0000000000"])
    except ItemsNotFoundError as error:
        items = []
    
    # Option 2: Use include_unavailable to get partial results
    items = api.get_items(["B01N5IB20Q", "0000000000"], include_unavailable=True)
    
    # Inspect errors for specific items
    for error in items.errors:
        print(error.code, error.message)