### Example Usage of Python Amazon Advertising API Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/index.rst This is a general example demonstrating how to use the Python Amazon Advertising API. Ensure you have the necessary credentials and have installed the library. ```python from advertising_api import advertising_api # Initialize the API client api = advertising_api.API() # Example: Get account information accounts = api.get_accounts() print(accounts) # Example: Get campaigns for a specific profile ID profile_id = "1234567890" campaigns = api.get_campaigns(profile_id=profile_id) print(campaigns) ``` -------------------------------- ### Get Currency Information Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst This example shows how to retrieve basic currency information using a JSON file as the request body. The version is optional and defaults to 1. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) # The function definition for get_currency would typically be here, similar to get_currency_extended # For brevity, only the usage in __main__ is shown as per the source structure. if __name__ == '__main__': file_name = "../../test/localizations/request_currency.json" # Assuming a get_currency function exists in Localization class # result = Localization(debug=True).get_currency(body=file_name) # logging.info(result) pass # Placeholder as the actual function call is commented out in the source ``` -------------------------------- ### Get Product Localization with Marketplace ID (Python) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Example of retrieving product localization using marketplace IDs for source and target. Defaults to version 1. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_products(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_products( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) if __name__ == '__main__': product_request = \ { "localizeProductRequests": [ { "product": { "asin": "B000000000", "sku": "SKU-OF-B000000000" } } ], "adType": "SPONSORED_PRODUCTS", "entityType": "SELLER", "sourceMarketplaceId": "A1RKKUPIHCS9HS", "sourceAdvertiserId": "AD9EUOBWMS33M", "targetDetails": [ { "marketplaceId": "A1F83G8C2ARO7P", "advertiserId": "AD9EUOBWMS33M" } ] } get_products(product_request) ``` -------------------------------- ### Install python-amazon-ad-api using pip Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/installation.rst Use this command to install the library. Ensure pip is up to date. ```bash pip install python-amazon-ad-api ``` -------------------------------- ### Example Query JSON Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/history.rst This is an example JSON file that can be used as a query for the history API. Download the file to use it. ```json { "fromDate": 1643683200000, "toDate": 1678271999999, "eventTypes": { "CAMPAIGN": { "filters": [ "BUDGET_AMOUNT", "STATUS" ], "eventTypeIds": [ "45662011530311" ] } } } ``` -------------------------------- ### Another Invoice Summary Output Example Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/invoices.rst An alternative example of an invoice summary object, demonstrating variations in data. ```json { 'id': 'DR0012TTY-76', 'status': 'PAID_IN_FULL', 'fromDate': '20210624', 'toDate': '20210703', 'invoiceDate': '20210702', 'amountDue': {'amount': 332.2, 'currencyCode': 'EUR'}, 'taxAmountDue': {'amount': 0.0, 'currencyCode': 'EUR'}, 'remainingAmountDue': {'amount': 0.0, 'currencyCode': 'EUR'}, 'remainingTaxAmountDue': {'amount': 0.0, 'currencyCode': 'EUR'} } ``` -------------------------------- ### Get Product Localization with Country Code (Python) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Example of retrieving product localization using country codes for source and target, specifically for version 2. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_products(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_products( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) if __name__ == '__main__': product_request = \ { "localizeProductRequests": [ { "product": { "asin": "B000000000", "sku": "SKU-OF-B000000000" } } ], "adType": "SPONSORED_PRODUCTS", "entityType": "SELLER", "sourceCountryCode": "ES", "sourceAdvertiserId": "AD9EUOBWMS33M", "targetDetails": [ { "countryCode": "FR", "advertiserId": "AD9EUOBWMS33M" } ] } get_products(product_request, version=2) ``` -------------------------------- ### Get Keywords by Locale Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst This example demonstrates how to retrieve localized keywords using a source locale and a list of target country codes. It shows the dynamic creation of a request body. ```APIDOC ## Get Keywords by Locale ### Description This operation retrieves localized keywords based on a source locale and a list of target country codes. It allows for dynamic construction of the request payload. ### Method `POST` ### Endpoint `/localization/keywords` ### Parameters #### Request Body - **localizeKeywordRequests** (array) - Required - A list of localization keyword requests. - **localizationKeyword** (object) - Required - Contains the keyword to localize. - **keyword** (string) - Required - The keyword string. - **sourceDetails** (object) - Required - Details about the source localization. - **locale** (string) - Required - The locale string of the source (e.g., "en_US"). - **targetDetails** (object) - Required - Details about the target localizations. - **countryCodes** (array) - Required - A list of country codes for the targets. ### Request Example ```json { "localizeKeywordRequests": [ { "localizationKeyword": { "keyword": "example keyword" } } ], "sourceDetails": { "locale": "en_US" }, "targetDetails": { "countryCodes": [ "GB", "FR", "DE" ] } } ``` ### Response #### Success Response (200) - **localizedKeywords** (array) - A list of localized keywords. - **keyword** (string) - The original keyword. - **localizedKeyword** (string) - The localized keyword. - **countryCode** (string) - The country code of the localization. - **locale** (string) - The locale of the localization. #### Response Example ```json { "localizedKeywords": [ { "keyword": "example keyword", "localizedKeyword": "mot-clé exemple", "countryCode": "FR", "locale": "fr_FR" } ] } ``` ``` -------------------------------- ### Get All Invoices with Pagination Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/invoices.rst This example utilizes the `Utils.load_all_pages` decorator to automatically handle pagination when retrieving all invoices matching certain criteria. It's useful for fetching large datasets without manual cursor management. ```python import logging from ad_api.api import Invoices from ad_api.base import Utils @Utils.load_all_pages(throttle_by_seconds=1, next_token_param="cursor") def get_all_invoices(**kwargs): return Invoices(account=store, debug=True).list_invoices(**kwargs) bill_status = 'PAID_IN_FULL' for page in get_all_invoices(invoiceStatuses=bill_status): res = page.payload payload = res.get("payload") invoice_summaries = payload.get("invoiceSummaries") for invoice in invoice_summaries: logging.info(invoice) ``` -------------------------------- ### Get Keywords by Country Code Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst This example demonstrates how to retrieve localized keywords using a source country code and a list of target country codes. It shows the dynamic creation of a request body. ```APIDOC ## Get Keywords by Country Code ### Description This operation retrieves localized keywords based on a source country code and a list of target country codes. It allows for dynamic construction of the request payload. ### Method `POST` ### Endpoint `/localization/keywords` ### Parameters #### Request Body - **localizeKeywordRequests** (array) - Required - A list of localization keyword requests. - **localizationKeyword** (object) - Required - Contains the keyword to localize. - **keyword** (string) - Required - The keyword string. - **sourceDetails** (object) - Required - Details about the source localization. - **countryCode** (string) - Required - The country code of the source. - **targetDetails** (object) - Required - Details about the target localizations. - **locales** (array) - Required - A list of locale strings for the targets. ### Request Example ```json { "localizeKeywordRequests": [ { "localizationKeyword": { "keyword": "example keyword" } } ], "sourceDetails": { "countryCode": "ES" }, "targetDetails": { "locales": [ "en_GB", "fr_FR", "it_IT" ] } } ``` ### Response #### Success Response (200) - **localizedKeywords** (array) - A list of localized keywords. - **keyword** (string) - The original keyword. - **localizedKeyword** (string) - The localized keyword. - **countryCode** (string) - The country code of the localization. - **locale** (string) - The locale of the localization. #### Response Example ```json { "localizedKeywords": [ { "keyword": "example keyword", "localizedKeyword": "mot-clé exemple", "countryCode": "FR", "locale": "fr_FR" } ] } ``` ``` -------------------------------- ### Load and Get Extended Currency Information from File Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst This example demonstrates how to use a JSON file as the request body for the get_currency_extended function. MarketplacesIds are not needed when using a file. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_currency_extended(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_currency_extended( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) if __name__ == '__main__': file_name = "../test/localizations/request_currency.json" get_currency_extended(file_name) # No version include will get version 1 # get_currency_extended(file_name, version=2) ``` -------------------------------- ### Upload File using Requests Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/creative_assets.rst This example demonstrates how to upload a file to a given URL using the requests library in Python. It's a supplementary example for the asset upload process. ```python from requests import request def upload_file(_method, _url, _img): response = request( _method, _url, data=open(_img, 'rb') ) logging.info(response.status_code) logging.info(response.headers) logging.info(response.content) logging.info(response.raw) if __name__ == '__main__': file_name = "Sample-1200x1200.jpeg" ``` -------------------------------- ### Query Taxonomy JSON Example Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/audiences.rst This is an example of a JSON file used to query audience taxonomy data. ```json { "adType": "SD", "categoryPath": [ "Lifestyle" ] } ``` -------------------------------- ### Get Currency Localization (Python) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Demonstrates how to get currency localization data. Requires the `ad_api` library and handles potential `AdvertisingApiException`. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException def get_currency(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_currency( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) if __name__ == '__main__': file_name = "../test/localizations/request_currency.json" try: with open(file_name, mode="r", encoding="utf-8") as file: get_currency(file_name, version=1) file.close() except FileNotFoundError as e: logging.info(e) ``` -------------------------------- ### Get Targeting Expression (Python) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Shows how to generate a targeting expression using MarketplacesIds for both source and target, with a specific predicate like 'asinSameAs'. This example uses version 1 of the API. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException, MarketplacesIds logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_targeting_expression(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_targeting_expression( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) if __name__ == '__main__': source_country_code = "GB" source_marketplace_id = MarketplacesIds[source_country_code].value target_country_code = "ES" target_marketplace_id = MarketplacesIds[target_country_code].value expression_request = \ { "targetDetailsList": [ { "marketplaceId": target_marketplace_id, } ], "requests": [ { "targetingExpression": { "isForNegativeTargeting": True, "expression": [ { "type": "asinSameAs", "value": "B08SWH2KP4" } ] } } ], "sourceDetails": { "marketplaceId": source_marketplace_id, } } get_targeting_expression(expression_request, version=1) ``` -------------------------------- ### Invoice Summary Output Example Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/invoices.rst This is an example of the JSON structure for a single invoice summary object returned by the `list_invoices` method. ```json { 'id': 'DR0012TTY-75', 'status': 'PAID_IN_FULL', 'fromDate': '20210613', 'toDate': '20210625', 'invoiceDate': '20210624', 'amountDue': {'amount': 500.04, 'currencyCode': 'EUR'}, 'taxAmountDue': {'amount': 0.0, 'currencyCode': 'EUR'}, 'remainingAmountDue': {'amount': 0.0, 'currencyCode': 'EUR'}, 'remainingTaxAmountDue': {'amount': 0.0, 'currencyCode': 'EUR'} } ``` -------------------------------- ### Get Campaign Optimization Rule Recommendation Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/campaign_optimization_rules.rst Gets a campaign optimization rule recommendation for Sponsored Products campaigns. ```APIDOC ## POST /sp/rules/campaignOptimization/eligibility ### Description Gets a campaign optimization rule recommendation for SP campaigns. ### Method POST ### Endpoint /sp/rules/campaignOptimization/eligibility ### Request Body - **campaignIds** (list of strings) - Required - A list of campaign IDs for which to get optimization recommendations. ### Request Example { "campaignIds": [ "string" ] } ### Response #### Success Response (200) - **campaignIds** (list of strings) - A list of campaign IDs that are eligible for optimization rules. ``` -------------------------------- ### Query General Audience JSON Example Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/audiences.rst This is an example of a JSON file used to query general audience data, including filters for audience name. ```json { "adType": "SD", "filters": [ { "field": "audienceName", "values": [ "Automotive Ownership" ] } ] } ``` -------------------------------- ### Report Details JSON Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/reports.rst This is an example of the JSON response when retrieving report details. It includes configuration, status, and download URL. ```json { 'configuration': { 'adProduct': 'SPONSORED_PRODUCTS', 'columns': ['impressions', 'clicks', 'cost', 'campaignStatus', 'advertisedAsin', 'date'], 'filters': None, 'format': 'GZIP_JSON', 'groupBy': ['advertiser'], 'reportTypeId': 'spAdvertisedProduct', 'timeUnit': 'DAILY' }, 'createdAt': '2022-11-21T12:00:52.528Z', 'endDate': '2022-11-01', 'failureReason': None, 'fileSize': 51199, 'generatedAt': '2022-11-21T12:01:53.255Z', 'name': None, 'reportId': '8877234e-bdaa-165d-21ee-45e2e4d8b746', 'startDate': '2022-11-01', 'status': 'COMPLETED', 'updatedAt': '2022-11-21T12:01:53.255Z', 'url': 'https://offline-report-storage-eu-west-1-prod.s3.eu-west-1.amazonaws.com/8877234e-bdaa-165d-21ee-45e2e4d8b746/report-8877234e-bdaa-165d-21ee-45e2e4d8b746.json.gz?X-Amz-Security-Token=****************&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20221121T120227Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Credential=*********************&X-Amz-Signature=*************************************************', 'urlExpiresAt': '2022-11-21T13:02:27.915577Z' } ``` -------------------------------- ### List SB Themes Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sb/themes.rst Retrieves a list of all available themes. No specific setup is required beyond importing the Themes class. ```python from ad_api.api.sb.themes import Themes result = Themes().list_themes() print(result) ``` -------------------------------- ### Example Brands Payload Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sb/brands.rst This is an example of the JSON payload structure returned when listing brands. It includes identifiers and registry names for each brand. ```json [{'brandEntityId': 'ENTITY5ON7M22396H', 'brandId': 'A387T2Q1UNXHJK', 'brandRegistryName': 'Apple'}, {'brandEntityId': 'ENTITY218756GCCQ6CF', 'brandId': 'A36UAF6UNGFFAR', 'brandRegistryName': 'Huawei'}, {'brandEntityId': 'ENTITY1PRG7GD8FVXA3', 'brandId': 'A87RK5OLHEBUU5', 'brandRegistryName': 'Xiaomi'}] ``` -------------------------------- ### Example Response Payload for Edit Product Ads Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sd/product_ads.rst This is an example of the expected response payload when editing product ads, indicating the success status and the ad ID. ```python [{'code': 'SUCCESS', 'adId': 182575048323550}] ``` -------------------------------- ### Get Product Recommendations Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/budget_recommendations.rst Retrieves suggested target ASINs for your advertised product. ```APIDOC ## POST /sp/targets/products/recommendations ### Description Suggested target ASINs for your advertised product. ### Method POST ### Endpoint /sp/targets/products/recommendations ### Parameters #### Query Parameters - **kwargs** (dict) - Optional - Additional keyword arguments for the API call. ### Request Example ```python # Example usage (assuming you have an authenticated client) from ad_api.api.sp import ProductRecommendations client = ProductRecommendations() response = client.list_products_recommendations(product_id='YOUR_PRODUCT_ID', asin_type='YOUR_ASIN_TYPE') print(response.json()) ``` ### Response #### Success Response (200) - **response** (ApiResponse) - The API response object containing the recommendations. ``` -------------------------------- ### Get Budget Recommendations Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/product_recommendations.rst Retrieves recommended daily budgets and estimated missed opportunities for Sponsored Products campaigns. ```APIDOC ## POST /sp/campaigns/budgetRecommendations ### Description Get recommended daily budget and estimated missed opportunities for campaigns. ### Method POST ### Endpoint /sp/campaigns/budgetRecommendations ### Parameters #### Query Parameters - **kwargs** (dict) - Optional - Additional keyword arguments for the request. ### Request Example ```python # Example usage (assuming you have an authenticated client) response = client.sp.budget_recommendations.list_campaigns_budget_recommendations() ``` ### Response #### Success Response (200) - **ApiResponse** (object) - The API response object containing budget recommendations and missed opportunity data. ``` -------------------------------- ### Sample Payload Response Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sb/landing_page_asins.rst This is an example of the JSON payload returned by the `get_page_asins` method, containing a list of ASINs and a status code. ```json { "asinList": [ "B08N5WRTN2", "B081G9YQ73", "B008ATNJNS", "B08N5VXMK6", "B016UPAVDE", "B08N5S5HH5", "B016MUBL4U", "B08N5WM84C", "B08N5TLVQ2", "B0863B2L69", "B08N5TLB5J", "B081GBLPTB", "B081G4SK26", "B08N5VT5SV", "B0863G2M7F", "B07BRLMY93", "B08N5V4CKB", "B086395QZM", "B081GC15CY", "B086395QZP" ], "code": "SUCCESS" } ``` -------------------------------- ### List Product Ads with Default Configuration Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sd/product_ads.rst This example shows how to list product ads using default configurations for account and marketplace if not explicitly provided. Debugging information is omitted by default. ```python import os from ad_api.base import AdvertisingApiException from ad_api.api.sd.product_ads import ProductAds try: status = 'enabled' index = 5 # Sets a cursor into the requested set of product ads number = 2 # Sets the number of ProductAd objects in the returned array result = ProductAds().list_product_ads( stateFilter=status ) products_ads = result.payload # except AdvertisingApiException as error: logging.error(error) ``` -------------------------------- ### List Sponsored Products Campaigns (Python) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/code.rst Example of initializing the client with credentials and making a call to list sponsored products campaigns. Handles potential API exceptions. ```python import logging from ad_api.base import AdvertisingApiException from ad_api.api import sponsored_products credentials = dict( refresh_token='your-refresh_token', client_id='your-client_id', client_secret='your-client_secret', profile_id='your-profile_id', ) try: status = 'enabled' result=sponsored_products.Campaigns(credentials=credentials, debug=True).list_campaigns( stateFilter=status ) payload = result.payload logging.info(payload) except AdvertisingApiException as error: logging.info(error) ``` -------------------------------- ### List Campaigns with Default Account Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/config.rst Demonstrates how to list campaigns using the default account configured in `credentials.yml`. Ensure the `Campaigns` class is imported. ```python Campaigns().list_campaigns() ``` -------------------------------- ### Get Landing Page ASINs Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sb/landing_page_asins.rst Use this snippet to retrieve a list of ASINs from a specified Amazon landing page URL. Ensure the `ad_api` library is installed and imported. ```python from ad_api.api.sb.landing_page_asins import PageAsins page_url = 'https://www.amazon.es/stores/page/49D4CB50-9C2F-46D5-8E50-5505529C790D' result = PageAsins().get_page_asins( pageUrl=page_url ) logging.info(result) ``` -------------------------------- ### Get Keywords Localization (Python) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Demonstrates how to localize a list of keywords from a source marketplace to multiple target marketplaces. Ensure the Localization class and MarketplacesIds are imported. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException, MarketplacesIds logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_keywords(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_keywords( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) except KeyboardInterrupt as error: logging.info(error) if __name__ == '__main__': keywords = ['máquina', 'diagnosis', 'diagnosis multimarca', 'coche', 'automóvil', 'frenos', 'presión', 'neumáticos'] source_country_code = "ES" source_marketplace_id = MarketplacesIds[source_country_code].value target_country_codes = ["GB", "FR", "IT", "DE", "NL", "SE"] keywords_request = \ { "localizeKeywordRequests": [{"localizationKeyword": {"keyword": keyword}} for keyword in keywords], "sourceDetails": { "marketplaceId": source_marketplace_id }, "targetDetails": { "marketplaceIds": [MarketplacesIds[target_country_code].value for target_country_code in target_country_codes], } } get_keywords(keywords_request) # get_keywords(keywords_request, version=2) ``` -------------------------------- ### Get Keywords using Locale for Source Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Use this snippet to create a dynamic dictionary of keywords based on a source locale and target country codes. Ensure the 'ad_api' library is installed and imported. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException, Locales logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_keywords(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_keywords( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) except KeyboardInterrupt as error: logging.info(error) if __name__ == '__main__': keywords = ['máquina', 'diagnosis', 'diagnosis multimarca', 'coche', 'automóvil', 'frenos', 'presión', 'neumáticos'] source_country_code = "ES" source_locale = Locales[source_country_code].value target_country_codes = ["GB", "FR", "IT", "DE", "CN", "NL", "SE"] keywords_request = \ { "localizeKeywordRequests": [{"localizationKeyword": {"keyword": keyword}} for keyword in keywords], "sourceDetails": { "locale": source_locale }, "targetDetails": { "countryCodes": target_country_codes, } } get_keywords(keywords_request) # get_keywords(keywords_request, version=2) ``` -------------------------------- ### Get Keywords using Country Code for Source Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Use this snippet to create a dynamic dictionary of keywords based on a source country code and target country codes. Ensure the 'ad_api' library is installed and imported. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException, Locales logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_keywords(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_keywords( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) except KeyboardInterrupt as error: logging.info(error) if __name__ == '__main__': keywords = ['máquina', 'diagnosis', 'diagnosis multimarca', 'coche', 'automóvil', 'frenos', 'presión', 'neumáticos'] source_country_code = "ES" target_country_codes = ["GB", "FR", "IT", "DE", "CN", "NL", "SE"] keywords_request = \ { "localizeKeywordRequests": [{"localizationKeyword": {"keyword": keyword}} for keyword in keywords], "sourceDetails": { "countryCode": source_country_code, }, "targetDetails": { "locales": [Locales[target_country_code].value for target_country_code in target_country_codes] } } get_keywords(keywords_request) # get_keywords(keywords_request, version=2) ``` -------------------------------- ### List Sponsored Products Campaigns (v3) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/README.md Demonstrates how to list Sponsored Products campaigns using v3 of the API. Requires valid credentials and optionally accepts a body for filtering. ```python import logging from ad_api.base import AdvertisingApiException from ad_api.api import sponsored_products logging.basicConfig( level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(message)s" ) def sp_list_campaigns_v3(info: dict = None): credentials = dict( refresh_token='your-refresh_token', client_id='your-client_id', client_secret='your-client_secret', profile_id='your-profile_id', ) try: result = sponsored_products.CampaignsV3(credentials=credentials, debug=True).list_campaigns( body=info ) payload = result.payload return payload except AdvertisingApiException as error: logging.error(error) logging.error(error.code) state_filter = { "stateFilter": { "include": [ "ENABLED" ] } } enabled_campaigns = sp_list_campaigns_v3(state_filter).get("campaigns") for campaign in enabled_campaigns: logging.info(campaign) logging.info(len(campaigns)) ``` -------------------------------- ### Get Products Targets Count Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/product_targeting_v3.rst Get the number of targetable ASINs based on refinements provided by the user. ```APIDOC ## POST /sp/targets/products/count ### Description Get number of targetable asins based on refinements provided by the user. ### Method POST ### Endpoint /sp/targets/products/count ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Fetch All Audiences with Utils Decorator (Python) Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/insights.rst This example demonstrates how to retrieve all available audiences using the `Utils.load_all_categories` decorator. It handles pagination and rate limiting, fetching data in sets of 10 with a 5-second delay between requests. This is useful for comprehensive data collection. ```python import logging from ad_api.api import Insights from ad_api.base import AdvertisingApiException, Utils @Utils.load_all_categories(throttle_by_seconds=5, next_token_param="nextToken") def get_all_categories(**kwargs): return Insights(debug=True).get_insights(**kwargs) if __name__ == '__main__': id_audience = "427339506193361161" ad_type = "SD" for page in get_all_categories(audienceId=id_audience, adType=ad_type, version=2, maxResults=10): result = page.payload overlapping_audiences = result.get("overlappingAudiences") for audience in overlapping_audiences: logging.info(audience.get("affinity")) logging.info(audience.get("audienceMetadata")) ``` -------------------------------- ### List Campaigns with Specific Account Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/config.rst Shows how to list campaigns using a specific account named 'another_account' from the `credentials.yml` file. Requires specifying the account name and marketplace. ```python Campaigns(account="another_account", marketplace=Marketplaces.ES).list_campaigns() ``` -------------------------------- ### List Product Ads with Filters Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sd/product_ads.rst Use this to list product ads with specific filters like status. Ensure you have the necessary imports and account credentials configured. ```python from ad_api.base import AdvertisingApiException, Marketplaces from ad_api.api import sponsored_display try: status = 'enabled' store = 'my_store' result = sponsored_display.ProductAds(account=store, marketplace=Marketplaces.ES, debug=True).list_product_ads( stateFilter=status ) products_ads = result.payload # except AdvertisingApiException as error: logging.error(error) ``` -------------------------------- ### Initialize Client with Dictionary Credentials Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/README.md Use your Amazon Ads API credentials by passing them as a dictionary to the client. Ensure all required fields like refresh_token, client_id, client_secret, and profile_id are provided. ```javascript from ad_api.api import sponsored_products my_credentials = dict( refresh_token='your-refresh_token', client_id='your-client_id', client_secret='your-client_secret', profile_id='your-profile_id', ) info = { "stateFilter": { "include": [ "ENABLED" ] } } result = sponsored_products.CampaignsV3(credentials=my_credentials).list_campaigns( body=info ) ``` -------------------------------- ### Create a New Report Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/reports.rst Use this method to initiate a new report. Provide the report configuration in the body. The response contains a report ID that can be used to track the report's status. ```python from ad_api.api.reports import Reports with open("advertised_product.json", "r", encoding="utf-8") as f: data = f.read() result = Reports().post_report(body=data) payload = result.payload report_id = payload.get('reportId') ``` -------------------------------- ### Retrieve All Audiences with Pagination Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/audiences.rst This example demonstrates how to retrieve all audiences using the `Utils.load_all_categories` decorator for pagination. It handles fetching data in batches with a specified delay between requests. ```python import logging from ad_api.api import Audiences from ad_api.base import AdvertisingApiException, Utils @Utils.load_all_categories(throttle_by_seconds=5, next_token_param="nextToken") def get_all_categories(**kwargs): return Audiences(debug=True).list_audiences(**kwargs) if __name__ == '__main__': request = { "adType": "SD", } for page in get_all_categories(maxResults=20,body=request): result = page.payload audiences = result.get("audiences") for audience in audiences: logging.info(audience) ``` -------------------------------- ### Get Ranked Keywords Recommendations for ASINs Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/ranked_keywords_recommendations.rst Use this function to get keyword recommendations based on a list of ASINs. Ensure the recommendationType is set to 'KEYWORDS_FOR_ASINS'. ```python import logging import json from ad_api.api import sponsored_products from ad_api.base import AdvertisingApiException def sp_get_ranked_keywords_recommendations_asin(version:int): dictionary = \ { "asins": [ "B08C1KN5J2" ], "recommendationType": "KEYWORDS_FOR_ASINS" } data = json.dumps(dictionary) try: result = sponsored_products.RankedKeywordsRecommendations(debug=True).list_ranked_keywords_recommendations( version=version, body=data ) except AdvertisingApiException as error: logging.error(error) logging.info("version {}".format(str(version))) logging.info(result.payload) if __name__ == '__main__': # sp_get_ranked_keywords_recommendations_asin(version=3) # default api endpoint version=3 sp_get_ranked_keywords_recommendations_asin(version=4) sp_get_ranked_keywords_recommendations_asin(version=5) ``` -------------------------------- ### Create DSP Report Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/dsp/reports.rst Use this method to initiate the creation of a DSP report. Provide the DSP account ID and the report configuration body. The response contains a report ID that can be used to track the report's status. ```python from ad_api.api.dsp.reports import Reports with open("campaign.json", "r", encoding="utf-8") as f: data = f.read() dsp_account_id = '1111111111111' result = Reports().post_report( dspAccountId=dsp_account_id, body=data ) payload = result.payload report_id = payload.get('reportId') ``` -------------------------------- ### Create Portfolios Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/portfoliosV3.rst Creates new portfolios. ```APIDOC ## create_portfolios ### Description Creates new portfolios. ### Method POST ### Endpoint /portfolios ### Parameters #### Request Body - **name** (string) - Required - The name of the portfolio. - **budget** (object) - Required - The budget information for the portfolio. - **amount** (float) - Required - The budget amount. - **currencyCode** (string) - Required - The currency code. - **period** (string) - Required - The budget period. - **campaigns** (list) - Optional - A list of campaign IDs to associate with the portfolio. ### Request Example { "name": "New Portfolio", "budget": { "amount": 500.00, "currencyCode": "USD", "period": "DAILY" }, "campaigns": [ "1234567890abcdef1234567890abcdef", "abcdef1234567890abcdef1234567890" ] } ### Response #### Success Response (200) - **portfolioId** (string) - The ID of the newly created portfolio. #### Response Example { "portfolioId": "0123456789abcdef0123456789abcdef" } ``` -------------------------------- ### Get Extended Currency Information Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/api/localization.rst Use this helper function to get country codes and currency details for better contextualization of results. It accepts a dictionary for the request body and an optional version number. ```python import logging from ad_api.api import Localization from ad_api.base import AdvertisingApiException, MarketplacesIds logging.basicConfig( level=logging.INFO, format="%(asctime)s:%(levelname)s:%(message)s" ) def get_currency_extended(data: (str, dict), version: int = 1): try: result = Localization(debug=True).get_currency_extended( version=version, body=data ) logging.info(result) except AdvertisingApiException as error: logging.info(error) if __name__ == '__main__': source_country_code = "DE" source_marketplace_id = MarketplacesIds[source_country_code].value target_country_codes = ["GB", "US", "JP"] amount_1 = 10 amount_2 = 15 request = { 'localizeCurrencyRequests': [ { 'currency': { 'amount': amount_1 } }, { 'currency': { 'amount': amount_2 } } ], 'targetCountryCodes': target_country_codes, 'sourceCountryCode': source_country_code, 'sourceMarketplaceId': source_marketplace_id, 'targetMarketplaces': [MarketplacesIds[target_country_code].value for target_country_code in target_country_codes] } get_currency_extended(request, version=1) # You could submit version=2 ``` -------------------------------- ### Get Budget History Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sd/budget_rules.rst Retrieves the budget history for a specific campaign. ```APIDOC ## GET /sd/campaigns/{campaignId}/budgetRules/budgetHistory ### Description Gets the budget history for a campaign specified by identifier. ### Method GET ### Endpoint /sd/campaigns/{campaignId}/budgetRules/budgetHistory ### Parameters #### Path Parameters - **campaignId** (string) - Required - The identifier of the campaign. ### Response #### Success Response (200) - **budgetHistory** (list) - A list of budget history entries. ``` -------------------------------- ### ProductAdsV3.create_product_ads Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/product_ads_v3.rst Creates new product ads. ```APIDOC ## create_product_ads ### Description Creates new product ads. ### Method APICall ### Endpoint /sp/productAds/v3/create ### Parameters #### Request Body - **productAds** (list) - Required - A list of product ad objects to create. - **adGroupId** (str) - Required - The ID of the ad group to which the product ad belongs. - **sku** (str) - Required - The SKU of the product for which to create an ad. - **state** (str) - Optional - The state of the product ad (e.g., ENABLED, PAUSED). ### Request Example ```python api.ProductAdsV3.create_product_ads([ { "adGroupId": "1234567890", "sku": "ABC-12345" } ]) ``` ### Response #### Success Response (200) - **productAds** (list) - A list of created product ad objects, including their IDs and status. #### Response Example ```json { "productAds": [ { "adGroupId": "1234567890", "adId": "1122334455", "sku": "ABC-12345", "state": "ENABLED", "status": "SUCCESS" } ] } ``` ``` -------------------------------- ### Get Product Ad Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sd/product_ads.rst Retrieves details for a specific product ad by its ID. ```APIDOC ## get_product_ad ### Description Retrieves the details of a specific product ad using its unique identifier. ### Method GET ### Endpoint /sd/productAds/{adId} ### Parameters #### Path Parameters - **adId** (integer) - Required - The unique identifier of the product ad to retrieve. ### Response #### Success Response (200) - **payload** (object) - An object containing the details of the specified product ad. ### Response Example ```json { "adId": 123456789012345, "name": "Example Product Ad", "state": "enabled", "creationDate": "2023-01-01T10:00:00Z", "lastUpdatedDate": "2023-01-01T10:00:00Z" } ``` ``` -------------------------------- ### Create SB Themes Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sb/themes.rst Creates new themes for a given ad group and campaign. Themes can be related to keywords or landing pages. Ensure 'YOUR_ADGROUP_ID' and 'YOUR_CAMPAIGN_ID' are replaced with actual IDs. Up to 100 themes can be created in a single request. ```python from ad_api.api.sb.themes import Themes import json # Example data for themes themes_to_create = [ { "adGroupId": "YOUR_ADGROUP_ID", "campaignId": "YOUR_CAMPAIGN_ID", "themeType": "KEYWORDS_RELATED_TO_YOUR_BRAND", "bid": 0.75 } # Add more theme objects as needed, up to 100 ] # For a real scenario, you might read this from a file like in your Keywords example # file = open("create_themes.json") # data = file.read() # file.close() # result = Themes().create_themes(body=data) result = Themes().create_themes(themes=themes_to_create) print(result) ``` ```json { "themes": [ { "adGroupId": "string", "campaignId": "string", "themeType": "KEYWORDS_RELATED_TO_YOUR_BRAND|KEYWORDS_RELATED_TO_YOUR_LANDING_PAGES", "bid": 0.75 } ] } ``` -------------------------------- ### Get Budget Rule by ID Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/budget_rules.rst Retrieves a specific budget rule by its identifier. ```APIDOC ## GET /sp/budgetRules/{budgetRuleId} ### Description Gets a budget rule specified by identifier. ### Method GET ### Endpoint /sp/budgetRules/{budgetRuleId} ### Parameters #### Path Parameters - **budgetRuleId** (string) - Required - The identifier of the budget rule. ### Response #### Success Response (200) - **budgetRule** (object) - The details of the budget rule. ``` -------------------------------- ### Get Targeting Clause by ID Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sd/product_targeting.rst Retrieves a specific targeting clause by its identifier. ```APIDOC ## GET /sd/targets/{targetId} ### Description Gets a targeting clause specified by identifier. ### Method GET ### Endpoint /sd/targets/{targetId} ### Parameters #### Path Parameters - **targetId** (str) - Required - The unique identifier of the targeting clause. #### Query Parameters - **kwargs** (dict) - Optional - Additional parameters for the request. ### Response #### Success Response (200) - **body** (ApiResponse) - The response containing the targeting clause details. ``` -------------------------------- ### Get Budget History for a Campaign Source: https://github.com/denisneuf/python-amazon-ad-api/blob/main/docs/sp/budget_rules.rst Retrieves the budget history for a specific campaign. ```APIDOC ## GET /sp/campaigns/{campaignId}/budgetRules/budgetHistory ### Description Gets the budget history for a campaign specified by identifier. ### Method GET ### Endpoint /sp/campaigns/{campaignId}/budgetRules/budgetHistory ### Parameters #### Path Parameters - **campaignId** (string) - Required - The identifier of the campaign. ### Response #### Success Response (200) - **budgetHistory** (array) - A list of budget history entries. ```