### Deploy SQS Queue for Amazon Marketing Stream Data Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Deploy a CloudFormation stack to provision an SQS queue and SNS-to-SQS policy for receiving Amazon Marketing Stream data. This example deploys for the NA realm and the sp-traffic dataset. ```bash # Deploy via AWS CLI — NA realm, sp-traffic dataset aws cloudformation deploy \ --template-file amazon_marketing_stream/Stream_SQS\ _CF_Template.yaml \ --stack-name stream-sqs-sp-traffic-na \ --region us-east-1 \ --parameter-overrides \ StreamDestinationQueueName=MyStreamQueue \ StreamDatasetId=sp-traffic \ StreamRealm=NA \ --capabilities CAPABILITY_IAM # Available StreamDatasetId values: # sp-traffic, sp-conversion, budget-usage, # sd-traffic, sd-conversion, sb-traffic, sb-conversion, # sb-clickstream, sb-rich-media, # sponsored-ads-campaign-diagnostics-recommendations, # campaigns, adgroups, ads, targets, # adsp-campaigns, adsp-campaign-flights, adsp-adgroups, # adsp-adgroup-targets, sp-budget-recommendations # # StreamRealm → required AWS region: # NA → us-east-1 # EU → eu-west-1 # FE → us-west-2 # # After deployment, provide the SQS queue ARN to Amazon Ads to # register it as a Stream subscription destination. ``` -------------------------------- ### Get Download URLs for Workflow Results Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Retrieves pre-signed URLs for downloading the results of a workflow execution. ```APIDOC ## Get Download URLs for Workflow Results ### Description Retrieves pre-signed URLs to download the results of a workflow execution from S3. ### Method GET ### Endpoint `/amc/reporting/{instanceid}/workflowExecutions/{workflowExecutionId}/downloadUrls` ### Parameters #### Path Parameters - **workflowExecutionId** (string) - Required - The ID of the workflow execution for which to get download URLs. ``` -------------------------------- ### AMC SQL Query Example Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This is an example of an AMC SQL query. AMC SQL queries used in API requests must be single-line, stripped of tabs and newlines. ```SQL SELECT campaign, SUM(total_purchases) AS total_orders_9d FROM amazon_attributed_events_by_traffic_time WHERE SECONDS_BETWEEN(traffic_event_dt_utc, conversion_event_dt_utc) <= 60 * 60 * 24 * 9 GROUP BY campaign ``` -------------------------------- ### Set Up Event Deduplication Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Configure GTM to prevent duplicate conversions by mapping an `eventId` across different sources. This ensures only the first-received event is retained, prioritizing the Events API over the Amazon Ad Tag. ```GTM Setup # Web Container setup: # 1. Create a DataLayer Variable: # Name: dlv_order_id # Key Path: order_id ← must be pushed to dataLayer on conversion # # 2. In your web container tag (e.g., GA4 event tag), add a configuration parameter: # Parameter Name: order_id # Value: {{dlv_order_id}} # (this forwards the value in the Events Stream to the server container) # Server Container setup: # 1. Create an Event Data Variable: # Name: edv_order_id # Key Path: order_id ← matches the parameter name used above # # 2. In the Amazon Events API tag, set: # Event ID: {{edv_order_id}} # Deduplication behavior: # Timestamp-based: Duplicate events from the same source within 200ms → first retained # eventId-based: Same eventId from multiple sources → first by timestamp retained # Priority: Events API (CAPI v2) > Amazon Ad Tag ``` -------------------------------- ### Manage Credentials with AWS Secrets Manager Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Set up API authentication variables by retrieving credentials from AWS Secrets Manager. This snippet is executed at the start of each session to ensure up-to-date authentication parameters. ```python ## Modify the values of the variables in this code block that the collection will refer to. Execute it at the start of each session. ## In our example, we store the Clientid, Clientsecret, returnurl, and refresh_token in the secrets manager. ## These variables help with authenticating your calls. ## While Clientid, Clientsecret, returnurl are constant variables, ## you will will need to update the your secrets manager with the value of refresh_token at the start of each session. ## Set Variables secret_name = "secrets-name-here" region_name = "us-east-1" secretDict = get_secret(secret_name = secret_name, region_name=region_name) Clientid = secretDict['Clientid'] Clientsecret = secretDict['Clientsecret'] returnurl = secretDict['returnurl'] ## Update the value of refresh token after you generate the access token and refresh tokens the first time. ## After refresh tokens are generated initialize here. This value must be updated at the start of each session. #refresh_token = secretDict['refreshToken'] ## Store the instance ID of your instance here. You will not need the instanceid for onboarding. ## After onboarding, uncomment the line below and update the value to store your instance id. In this example, the instanceid is 'amc-instance01'. instanceid = 'amc-instance01' ## Your AMC Account Id, also referred to as entityId here ## In this example, the entityId is 'ENTITY1AA1AA11AAA1' ## if you don't know this this value use the GET operation of the `/amc/accounts` endpoint that returns a list of all the accounts your client Id has access to #entityId = 'ENTITY1AA1AA11AAA1' ``` -------------------------------- ### Import Libraries for AMC API Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Execute this code block before each session to import necessary libraries for interacting with the AMC API. Ensure Python version >=3.8 and urllib3<2.0.0,>=1.25.8 are installed. ```python ## Import Libraries ## Execute this code block before each session to import libraries import requests import json import pandas as pd import boto3 from botocore.exceptions import ClientError from pprint import pprint import sys ``` -------------------------------- ### Get AMC Workflow Execution Download URLs Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Request pre-signed URLs for downloading the results of an AMC workflow execution from S3. These URLs are temporary and provide access to the generated reports. ```python ## Retrieve pre-signed url for downloading workflow execution results from S3 r = requests.get(url + f'/amc/reporting/{instanceid}/workflowExecutions/{workflowExecutionId}/downloadUrls', headers = headers) print(r) print(r.text) ``` -------------------------------- ### Setup Amazon Ads API Postman Collection Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Follow these steps to import and configure the Postman collection for interacting with the Amazon Ads API. Ensure your LWA credentials are set up correctly in the environment variables. ```bash # Setup steps: # 1. Download files from postman/ directory: # - Amazon_Ads_API.postman_collection.json # - Amazon_Ads_API_Environment.postman_environment.json # # 2. Import both files into Postman (File > Import) # # 3. In the imported Environment, set these variables: # client_id → Your LWA Client ID # client_secret → Your LWA Client Secret # refresh_token → Your LWA Refresh Token # # 4. Select the imported environment as active # # 5. Run the "Authentication" request first to generate an access token. # The post-request script stores the access_token automatically. # # Supported endpoint groups in the collection: # - Authentication # - GET profiles # - GET manager accounts # - Sponsored Products (v3) # - Sponsored Brands (v4) # - Sponsored ads reporting (v2, v3) # - DSP reporting # - Sponsored ads snapshots # - Amazon Marketing Stream # - Amazon Marketing Cloud # - Product metadata # - Sponsored ads budget usage & rules # - Creative asset library # - Stores / Locations # - Sponsored Display / Sponsored TV # - Exports / Partner opportunities # # Video walkthrough: https://www.youtube.com/watch?v=SWqOPN33phw # Full API docs: https://advertising.amazon.com/API/docs/en-us/ ``` -------------------------------- ### Initialize AMC API Functions Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This code block initializes functions used throughout the collection. It must be executed during onboarding and at the start of each session. It includes functions for retrieving secrets from AWS Secrets Manager and refreshing access tokens. ```python ## Functions ## Execute this code block before each session to initialize the functions to use ## Function to retrieve credentials from secrets manager def get_secret(secret_name, region_name): ## Create a Secrets Manager client session = boto3.session.Session() client = session.client( service_name='secretsmanager', region_name=region_name ) try: get_secret_value_response = client.get_secret_value( SecretId=secret_name ) except ClientError as e: ## For a list of exceptions thrown, see ## https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html raise e print("Secrets retrieved") return json.loads(get_secret_value_response['SecretString']) ## Function to refresh access token def refresh_access_token(url, Clientid, Clientsecret, refresh_token): refresh_body = {"grant_type": "refresh_token", "client_id": Clientid, "client_secret": Clientsecret, "refresh_token": refresh_token} r = requests.post(url, data = refresh_body) if r.ok: access_token = r.json()['access_token'] print("Token refreshed successfully") return access_token else: print('Response Code is: ', r) print('Error message is: ', r.text) raise Exception("Access token failed to refresh") ``` -------------------------------- ### Retrieve AMC Workflow Execution Status Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Get the current status of a specific AMC workflow execution using its execution ID. This allows you to monitor the progress and completion of a workflow run. ```python ## Retrieve status information about the requested workflow execution. r = requests.get(url + f'/amc/reporting/{instanceid}/workflowExecutions/{workflowExecutionId}', headers = headers) print(r) print(r.text) if r.ok: print(f"\n Status of workflow execution is: {r.json()['status']}") ``` -------------------------------- ### Create Workflow Schedule Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This snippet demonstrates how to create a schedule for a specific workflow. ```APIDOC ## Create Workflow Schedule ### Description Creates a schedule for a given workflow. ### Method POST ### Endpoint `/amc/reporting/{instanceid}/schedules` ### Request Body - **scheduleId** (string) - Required - The ID for the schedule. - **workflowId** (string) - Required - The ID of the workflow to schedule. - **aggregationHourUtc** (integer) - Required - The hour of the day (UTC) for aggregation. - **aggregationPeriod** (string) - Required - The period for aggregation (e.g., 'Daily'). - **aggregationStartDay** (string) - Required - The starting day for aggregation (e.g., 'Tuesday'). - **scheduleEnabled** (string) - Required - Whether the schedule is enabled ('True' or 'False'). ### Request Example ```json { "scheduleId": "schedule-id", "workflowId": "workflow-name", "aggregationHourUtc": 8, "aggregationPeriod": "Daily", "aggregationStartDay": "Tuesday", "scheduleEnabled" : "True" } ``` ``` -------------------------------- ### List Existing Workflows Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This code demonstrates how to list existing workflows for a given AMC instance. It requires an instance ID and uses the previously defined headers for authentication. ```python ## List Existing Workflow print(instanceid) url = 'https://advertising-api.amazon.com' r = requests.get(url + f'/amc/reporting/{instanceid}/workflows', headers = headers) print(r) if r.ok: print(r.text[:50]) #pprint(r.json()) else: print(f"Error: {r.text}") ``` -------------------------------- ### Deploy Firehose to S3 via AWS CLI Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Use this command to deploy a CloudFormation stack for a Kinesis Firehose delivery stream to an S3 bucket in the EU realm. Ensure the template file and parameters are correctly specified. ```bash aws cloudformation deploy \ --template-file amazon_marketing_stream/Stream_Firehose_CF_Template.yaml \ --stack-name stream-firehose-sd-conversion-eu \ --region eu-west-1 \ --parameter-overrides \ StreamDestinationFirehose=MyFirehoseStream \ StreamDatasetId=sd-conversion \ StreamRealm=EU \ S3Storage=my-unique-stream-bucket-eu \ --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM ``` -------------------------------- ### Deploy CloudWatch Monitoring Stack via AWS CLI Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Deploy a CloudFormation stack to create CloudWatch alarms and a dashboard for an SQS-based stream queue. This requires specifying the SQS queue name and an email address for notifications. ```bash aws cloudformation deploy \ --template-file amazon_marketing_stream/Stream_CloudWatch_CF_Template.yaml \ --stack-name stream-cloudwatch-monitoring \ --region us-east-1 \ --parameter-overrides \ SQSQueueName=MyStreamQueue \ EmailAddress=ops-team@example.com \ --capabilities CAPABILITY_IAM ``` -------------------------------- ### Create Workflow Template Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This snippet demonstrates how to create a workflow template by defining an AMC SQL query and submitting it via the API. ```APIDOC ## Create Workflow Template ### Description Creates a workflow template with a specified SQL query. ### Method POST ### Endpoint `/amc/reporting/{instanceid}/workflows` ### Request Body - **workflowId** (string) - Required - The ID for the workflow. - **distinctUserCountColumn** (string) - Required - The column name for distinct user counts. - **filteredMetricsDiscriminatorColumn** (string) - Required - The column name for filtered metrics discriminator. - **filteredReasonColumn** (string) - Required - The column name for the filtered reason. - **sqlQuery** (string) - Required - The AMC SQL query to be executed. ### Request Example ```json { "workflowId": "workflow-name", "distinctUserCountColumn": "du_count", "filteredMetricsDiscriminatorColumn": "filtered", "filteredReasonColumn": "true", "sqlQuery": "SELECT campaign, SUM(total_purchases) AS total_orders_9d FROM amazon_attributed_events_by_traffic_time WHERE SECONDS_BETWEEN(traffic_event_dt_utc, conversion_event_dt_utc) <= 60 * 60 * 24 * 9 GROUP BY campaign" } ``` ``` -------------------------------- ### Deploy Kinesis Firehose to S3 for Amazon Marketing Stream Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt This template provisions AWS resources for Amazon Marketing Stream, including a Kinesis Data Firehose delivery stream and an S3 bucket for data storage. Data is partitioned by date and hour. ```bash ``` -------------------------------- ### Execute Workflow Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Initiates the execution of a workflow with specified time window and other parameters. ```APIDOC ## Execute Workflow ### Description Executes a workflow using its ID and specifies the time window for the execution. ### Method POST ### Endpoint `/amc/reporting/{instanceid}/workflowExecutions` ### Request Body - **timeWindowStart** (string) - Required - The start of the time window for execution (ISO 8601 format). - **timeWindowEnd** (string) - Required - The end of the time window for execution (ISO 8601 format). - **timeWindowType** (string) - Required - The type of time window ('EXPLICIT' or 'AUTO'). - **workflowId** (string) - Required - The ID of the workflow to execute. - **ignoreDataGaps** (string) - Optional - Whether to ignore data gaps ('True' or 'False'). - **workflowExecutionTimeoutSeconds** (string) - Optional - The timeout for the workflow execution in seconds. - **requireSyntheticData** (string) - Optional - Whether to require synthetic data (for sandbox instances). ### Request Example ```json { "timeWindowStart": "2024-02-01T00:00:00Z", "timeWindowEnd": "2024-03-31T00:00:00Z", "timeWindowType": "EXPLICIT", "workflowId": "workflow-name", "ignoreDataGaps": "True", "workflowExecutionTimeoutSeconds": "86400" } ``` ``` -------------------------------- ### Refresh Access Token and Set Up Headers Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This snippet shows how to refresh an access token using a refresh token and construct the necessary headers for AMC API requests. Ensure you have your Client ID, Client Secret, and a valid refresh token. ```python ## Refresh access token for each session ## Refresh tokens are valid for one hour access_token = refresh_access_token(url = 'https://api.amazon.com/auth/o2/token', Clientid=Clientid,Clientsecret=Clientsecret, refresh_token=refresh_token) url = 'https://advertising-api.amazon.com' ## For this collection, we'll use the marketplaceId for North America headers = { 'Authorization': 'Bearer ' + access_token, 'Amazon-Advertising-API-ClientId': Clientid, 'Amazon-Advertising-API-MarketplaceId': 'ATVPDKIKX0DER' ## Your Amazon Ads account executive would have provided you this an entity identifier (entityId) when you onboarded AMC. ## This entity id is referred to as Amazon-Advertising-API-AdvertiserId in the headers. ## Access the AMC console with your user identifier and password, and grab the entity identifier value that is displayed in the URL. ## The alphanumeric code that is prefixed with ENTITY is your account identifier. An example of an entityId is: ENTITY1AA1AA11AAA1. ## Update this value with the entityId #'Amazon-Advertising-API-AdvertiserId': ENTITY1AA1AA11AAA1 } ``` -------------------------------- ### View AMC Instances Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This snippet fetches and displays the AMC instances associated with your account. This information is useful for understanding the available AMC environments. ```python ## View the AMC instances associated with your account instances = requests.get(url + '/amc/instances', headers = headers) print(instances) print(instances.json()['instances']) ``` -------------------------------- ### Create AMC Workflow Template Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Construct the request body to create a workflow template using the defined SQL query. This involves specifying workflow details and the SQL query. ```python ## Create workflow template to call the SQL code defined above body = { "workflowId": "workflow-name", "distinctUserCountColumn": "du_count", "filteredMetricsDiscriminatorColumn": "filtered", "filteredReasonColumn": "true", "sqlQuery": sql, } r = requests.post(url + f'/amc/reporting/{instanceid}/workflows', headers = headers, data = json.dumps(body)) print(r) print(r.text) ``` -------------------------------- ### Retrieve a Schedule Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Fetches the details of a specific workflow schedule. ```APIDOC ## Retrieve a Schedule ### Description Retrieves the details of a specific workflow schedule. ### Method GET ### Endpoint `/amc/reporting/{instanceid}/schedules/{scheduleId}` ### Parameters #### Path Parameters - **scheduleId** (string) - Required - The ID of the schedule to retrieve. ``` -------------------------------- ### Refresh Access Token Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This snippet demonstrates how to refresh an access token using a refresh token, which is necessary for authenticating API requests. It also shows how to construct the necessary headers for API calls. ```APIDOC ## Refresh access token for each session ## Refresh tokens are valid for one hour access_token = refresh_access_token(url = 'https://api.amazon.com/auth/o2/token', Clientid=Clientid,Clientsecret=Clientsecret, refresh_token=refresh_token) url = 'https://advertising-api.amazon.com' ## For this collection, we'll use the marketplaceId for North America headers = { 'Authorization': 'Bearer ' + access_token, 'Amazon-Advertising-API-ClientId': Clientid, 'Amazon-Advertising-API-MarketplaceId': 'ATVPDKIKX0DER' ## Your Amazon Ads account executive would have provided you this an entity identifier (entityId) when you onboarded AMC. ## This entity id is referred to as Amazon-Advertising-API-AdvertiserId in the headers. ## Access the AMC console with your user identifier and password, and grab the entity identifier value that is displayed in the URL. ## The alphanumeric code that is prefixed with ENTITY is your account identifier. An example of an entityId is: ENTITY1AA1AA11AAA1. ## Update this value with the entityId #'Amazon-Advertising-API-AdvertiserId': ENTITY1AA1AA11AAA1 } ``` -------------------------------- ### Deploy Firehose to Snowflake via AWS CLI Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Deploy a CloudFormation stack for a Kinesis Firehose delivery stream to Snowflake. This command requires detailed Snowflake connection and loading parameters. Ensure your private key is securely handled. ```bash aws cloudformation deploy \ --template-file amazon_marketing_stream/Stream_firehose_snowflake.yml \ --stack-name stream-snowflake-campaigns-fe \ --region us-west-2 \ --parameter-overrides \ StreamDestinationFirehose=MySnowflakeFirehose \ StreamDatasetId=campaigns \ StreamRealm=FE \ S3Storage=my-stream-snowflake-backup-bucket \ SnowflakeAccountUrl=https://myaccount.snowflakecomputing.com \ SnowflakeUser=firehose_user \ SnowflakeDatabase=ADS_DATA \ SnowflakeSchema=STREAM \ SnowflakeTable=CAMPAIGNS \ SnowflakeRole=FIREHOSE_ROLE \ SnowflakeDataLoadingOption=JSON_MAPPING \ SnowflakePrivateKey= \ --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM ``` -------------------------------- ### Read Workflow Results into Pandas DataFrame Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Load the downloaded workflow execution results into a pandas DataFrame for analysis. This assumes the results are in a CSV format. ```python ## Read "Download URL" into pandas dataframe #df = pd.read_csv(r.json()['downloadUrls'][0]) #df ``` -------------------------------- ### Execute AMC Workflow Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Initiate the execution of an AMC workflow. This requires specifying the time window, workflow ID, and other execution parameters. ```python ## Execute workflow using workflow ID ## For detailed descriptions of each parameter, see https://advertising.amazon.com/API/docs/en-us/amc-reporting#tag/Workflows body = { "timeWindowStart": "2024-02-01T00:00:00Z", "timeWindowEnd": "2024-03-31T00:00:00Z", "timeWindowType": "EXPLICIT", "workflowId": "workflow-name", "ignoreDataGaps": "True", "workflowExecutionTimeoutSeconds": "86400" ##If using a Sandbox instance, uncomment the following: #"requireSyntheticData": "True" } r = requests.post(url + f'/amc/reporting/{instanceid}/workflowExecutions', headers = headers, data = json.dumps(body)) print(r) print(r.text) if r.ok: workflowExecutionId = r.json()['workflowExecutionId'] print("workflowExecutionId updated") ``` -------------------------------- ### List Workflow Schedules Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Retrieves a list of all schedules associated with workflows. ```APIDOC ## List Workflow Schedules ### Description Retrieves a list of all workflow schedules. ### Method GET ### Endpoint `/amc/reporting/{instanceid}/schedules` ``` -------------------------------- ### Generate Access and Refresh Tokens Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Exchanges an authorization code for an access token and a refresh token. This is a one-time step after which the refresh token should be stored securely and used for subsequent token refreshes. ```python ## Generate access token and refresh tokens - one time step ## After your refresh token is generated through this code, you do not need once to run this code again, ## instead use the (next) code block that uses the refresh token to generate access tokens. tokenurl = 'https://api.amazon.com/auth/o2/token' auth_code = 'Insert authorization code generated in your redirect url' token_body = {"grant_type": 'authorization_code', "client_id": 'Clientid', "client_secret": 'Clientsecret', "redirect_uri": 'returnurl', "code": 'auth_code'} r = requests.post(tokenurl, data = token_body) print(r.text) if r.ok: access_token = r.json()['access_token'] refresh_token = r.json()['refresh_token'] ## Save the refresh_token in your secrets manager ``` -------------------------------- ### List Workflow Executions Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Retrieves a list of all executions for a given workflow ID. ```APIDOC ## List Workflow Executions ### Description Lists all past executions of a specific workflow. ### Method GET ### Endpoint `/amc/reporting/{instanceid}/workflowExecutions?workflowId={workflowId}` ### Parameters #### Query Parameters - **workflowId** (string) - Required - The ID of the workflow to list executions for. ``` -------------------------------- ### Configure Amazon Events API Tag Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Set up the main GTM tag for sending conversion events to Amazon's Events Manager. This tag handles PII hashing, consent processing, custom attributes, and event deduplication. ```GTM Tag Configuration # GTM Tag configuration (Amazon Events API template): # # --- Event Configuration --- # Amazon CAPI Auth Variable: {{Amazon_CAPI_Auth}} ← variable from above # Account ID: 123456789 ← DSP Advertiser ID # (DSP → Campaign Manager → Advertisers → ID column) # # --- Event Description --- # Event Name: Purchase_Complete # Conversion Type: Off-Amazon purchase ← monetary event # Event Source: Website # Dataset Name: website_events ← groups events in reporting # # --- Match Keys (at least one required) --- # Type Value (GTM variable or raw string) # EMAIL {{dlv_email}} ← raw or pre-hashed SHA-256 # PHONE {{dlv_phone}} ← tag normalizes & hashes if raw # # --- Event Data --- # Country Code: {{dlv_country}} ← e.g. "US" # Event Time: {{Amazon_CAPI_Timestamp}} # Event Value: {{dlv_order_value}} ← e.g. 99.99 # Currency Code: USD ← ISO-4217, required for Off-Amazon purchase # Units Sold: {{dlv_units}} ← defaults to 1 if blank # Event ID: {{dlv_order_id}} ← deduplication key (see below) # # --- Custom Attributes --- # Brand: {{dlv_brand}} # Product ID: {{dlv_product_id}} # Category: {{dlv_category}} # Custom Data: # Name Type Value # campaign STRING {{dlv_campaign_name}} # discount INTEGER {{dlv_discount_pct}} # # --- Consent (choose one framework) --- # Amazon Consent: # User Data Consent: {{dlv_consent_user_data}} ← GRANTED / TRUE / yes / 1 # Ad Storage Consent: {{dlv_consent_ad_storage}} # # --- Trigger --- # Custom trigger: Event Name equals "purchase" ``` -------------------------------- ### List AMC Workflow Schedules Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Retrieve a list of all schedules associated with AMC workflows. This is useful for monitoring or managing existing schedules. ```python ## List workflow schedules r = requests.get(url + f'/amc/reporting/{instanceid}/schedules', headers = headers) print(r) print(r.text) ``` -------------------------------- ### Create AMC Workflow Schedule Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Create a new schedule for an AMC workflow. This involves defining the schedule ID, workflow ID, aggregation details, and enabling the schedule. ```python ## Create a schedule for a workflow body = { 'scheduleId': scheduleId, 'workflowId': workflowId, 'aggregationHourUtc': 8, 'aggregationPeriod': 'Daily', 'aggregationStartDay': 'Tuesday', 'scheduleEnabled' : 'True' } r = requests.post(url + f'/amc/reporting/{instanceid}/schedules', headers = headers, data = json.dumps(body)) print(r) print(r.text) ``` -------------------------------- ### Configure Amazon CAPI Auth Variable Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Set up the GTM variable for Amazon CAPI Authentication. This variable handles the OAuth lifecycle, generates and caches access tokens, and refreshes them automatically. It outputs a bearer token string for the Events API tag. ```GTM Variable Configuration # GTM Variable configuration (Amazon CAPI Auth template): # # Variable Name: Amazon_CAPI_Auth # Template: Amazon CAPI Auth # # Fields: # Client ID → {{YOUR_LWA_CLIENT_ID}} # Client Secret → {{YOUR_LWA_CLIENT_SECRET}} # Refresh Token → {{YOUR_LWA_REFRESH_TOKEN}} # # To generate a refresh token, use the Amazon Ads API Postman collection # or follow: https://advertising.amazon.com/API/docs/en-us/guides/get-started/retrieve-access-token # # The variable output is a bearer token string used by the Events API tag. # Token is cached server-side — no per-request OAuth round-trips. ``` -------------------------------- ### Configure Amazon CAPI Timestamp Variable Source: https://context7.com/amzn/ads-advanced-tools-docs/llms.txt Configure the GTM variable to generate ISO-8601 formatted timestamps. This is crucial for the 'Event Time' field in the Events API tag to avoid silent failures with invalid timestamp formats. ```GTM Variable Configuration # GTM Variable configuration (Amazon CAPI Timestamp template): # # Variable Name: Amazon_CAPI_Timestamp # Template: Amazon CAPI Timestamp # # No configuration fields required. # Output example: 2025-11-07T15:30:00Z # # IMPORTANT: Always use this variable for the "Event Time" field in the # Events API tag. The API accepts invalid timestamps with HTTP 207 but # marks them as BAD_REQUEST in the response body — use this variable to # avoid silent failures. ``` -------------------------------- ### Retrieve Workflow Execution Status Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Fetches the status information for a specific workflow execution. ```APIDOC ## Retrieve Workflow Execution Status ### Description Retrieves the status of a specific workflow execution. ### Method GET ### Endpoint `/amc/reporting/{instanceid}/workflowExecutions/{workflowExecutionId}` ### Parameters #### Path Parameters - **workflowExecutionId** (string) - Required - The ID of the workflow execution to retrieve status for. ``` -------------------------------- ### Retrieve AMC Workflow Schedule Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Fetch details for a specific AMC workflow schedule using its schedule ID. This allows you to view the configuration of a particular schedule. ```python ## Retrieve a schedule r = requests.get(url + f'/amc/reporting/{instanceid}/schedules/{scheduleId}', headers = headers) print(r) print(r.text) ``` -------------------------------- ### Define AMC SQL Query in Python Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Define your AMC SQL query as a single-line string in Python. This string will be used in the workflow template. ```python ## Define SQL body that your workflow will use sql = """ SELECT campaign, SUM(total_purchases) AS total_orders_9d FROM amazon_attributed_events_by_traffic_time WHERE SECONDS_BETWEEN(traffic_event_dt_utc, conversion_event_dt_utc) <= 60 * 60 * 24 * 9 GROUP BY campaign """ ``` -------------------------------- ### List AMC Workflow Executions Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Retrieve a list of all past executions for a specific AMC workflow ID. This helps in tracking workflow history and finding specific execution details. ```python ## List all executions of a certain workflowId. ## Example: list past executions or find a workflowId that was not stored r = requests.get(url + f'/amc/reporting/{instanceid}/workflowExecutions?workflowId={workflowExecutionId}', headers = headers) print(r) print(r.json()) ``` -------------------------------- ### Delete AMC Workflow Template Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Send a DELETE request to remove a previously created workflow template. Ensure the workflow name is correctly specified. ```python ## Delete Workflow Template r = requests.delete(url + f'/amc/reporting/{instanceid}/workflows/workflow-name', headers = headers) print(r) print(r.text) ``` -------------------------------- ### Delete Workflow Template Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This snippet shows how to delete an existing workflow template using its ID. ```APIDOC ## Delete Workflow Template ### Description Deletes a specified workflow template. ### Method DELETE ### Endpoint `/amc/reporting/{instanceid}/workflows/{workflowId}` ### Parameters #### Path Parameters - **workflowId** (string) - Required - The ID of the workflow to delete. ``` -------------------------------- ### Generate Authorization Grant URL Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Constructs the URL required to initiate the OAuth 2.0 Authorization Code Grant process. This URL is used to request user permission for your client application to access Amazon Ads API data. ```python ## Generate an authorization grant - execute this code block only once. #urlgrant = f'https://www.amazon.com/ap/oa?client_id={Clientid}&scope=advertising::campaign_management&advertising::audiences&response_type=code&redirect_uri={returnurl}' print(urlgrant) ``` -------------------------------- ### AMC Workflow and Schedule IDs Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Define variables for workflowId and scheduleId. These are used in subsequent API calls for managing schedules and executions. ```python workflowId = 'workflow-name' scheduleId = 'schedule-id' ``` -------------------------------- ### List AMC Accounts Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This code snippet retrieves a list of AMC accounts associated with your client ID. The response includes account IDs and marketplace IDs, which are essential for subsequent API calls. ```python ## List AMC account r = requests.get(url + "/amc/accounts", headers = headers) print(r) print(r.text) if r.ok: ## Select which element of the list is the correct choice for your use case. # Replace 'X' with the chosen integer to get a single value accountId = r.json()['amcAccounts'][X]['accountId'] marketplaceId = r.json()['amcAccounts'][X]['marketplaceId'] print(accountId, marketplaceId) ``` -------------------------------- ### List AMC Accounts Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb This API call retrieves a list of AMC accounts associated with your client ID. The response includes account IDs and marketplace IDs, which are essential for subsequent API requests. ```APIDOC ## List AMC account r = requests.get(url + "/amc/accounts", headers = headers) print(r) print(r.text) if r.ok: ## Select which element of the list is the correct choice for your use case. # Replace 'X' with the chosen integer to get a single value accountId = r.json()['amcAccounts'][X]['accountId'] marketplaceId = r.json()['amcAccounts'][X]['marketplaceId'] print(accountId, marketplaceId) ``` -------------------------------- ### Delete a Schedule Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Removes a specific workflow schedule. ```APIDOC ## Delete a Schedule ### Description Deletes a specified workflow schedule. ### Method DELETE ### Endpoint `/amc/reporting/{instanceid}/schedules/{scheduleId}` ### Parameters #### Path Parameters - **scheduleId** (string) - Required - The ID of the schedule to delete. ``` -------------------------------- ### Set Workflow Execution ID Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Manually set or overwrite the workflowExecutionId variable. This is useful if the ID was not captured automatically from a previous request. ```python ## Pull the workflowExecutionId from original workflow execute request ## Overwrite value set in previous cell if needed # workflowExecutionId = "11111111" ``` -------------------------------- ### Delete AMC Workflow Schedule Source: https://github.com/amzn/ads-advanced-tools-docs/blob/main/amazon_marketing_cloud/AMC_API_sample_python_collection.ipynb Remove an existing AMC workflow schedule by providing its schedule ID. This action permanently deletes the schedule. ```python ## Delete a schedule r = requests.delete(url + f'/amc/reporting/{instanceid}/schedules/{scheduleId}', headers = headers) print(r) print(r.text) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.