Creating Google Analytics 4 Source
  • 3 Minutes to read
  • Dark
    Light

Creating Google Analytics 4 Source

  • Dark
    Light

Article summary

Authorizing to Dataddo API

First step is to obtain access token for API calls authorization. Navigate to Authorization to see the complete tutorial how to obtain access_token for authorization of your API calls to Dataddo API. The access_token needs to be placed to HTTP Authorization header as in the examples below.

Creating Source

Listing All Available Authorizers

The following method retrieves a list of all available authorizers. The output is a list of Authorizer objects.

GET /connectors/google_analytics4/actions/authorization

Content-Type:application/json
Authorization: Bearer ACCESS_TOKEN
import requests

def get_dataddo_services(access_token):
    url = 'https://headless.dataddo.com/customer-api/v1/connectors/google_analytics4/actions/authorization'
    headers = {
        'accept': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }
    
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        response.raise_for_status()

def extract_ids(services):
    """Extracts the 'id' attribute from each service in the list."""
    ids = [service['id'] for service in services if 'id' in service]
    return ids

# Example usage
if __name__ == "__main__":
    # Replace 'YOUR_ACCESS_TOKEN' with your actual access token
    access_token = 'YOUR_ACCESS_TOKEN'
    
    try:
        services = get_dataddo_services(access_token)
        print("All Services:", services)
        
        # Extract and print the IDs from filtered services
        ids = extract_ids(services)
        print("Service IDs:", ids)
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

Listing All Available Google Analytics 4 Accounts

The following method retrieves a list of all available Google Analytics 4 accounts using the specified authorizer ID obtained in the previous step. The output is a list of Account objects. You can use this method to obtain the details of Google Analytics 4 accounts linked to the provided OAuth credentials.

POST /connectors/google_analytics4/actions/account
Accept: application/json
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN

{
    "oAuthId":"0"
}
import requests

def get_google_analytics4_accounts(access_token, oauth_id):
    url = 'https://headless.dataddo.com/customer-api/v1/connectors/google_analytics4/actions/account'
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {access_token}'
    }
    data = {
        "oAuthId": oauth_id
    }
    
    response = requests.post(url, headers=headers, json=data)
    
    if response.status_code == 200:
        return response.json()
    else:
        response.raise_for_status()

def extract_ids(accounts):
    """Extracts the 'id' attribute from each account in the list."""
    ids = [account['id'] for account in accounts if 'id' in account]
    return ids

# Example usage
if __name__ == "__main__":
    # Replace 'YOUR_ACCESS_TOKEN' and 'YOUR_OAUTH_ID' with your actual access token and OAuth ID
    access_token = 'YOUR_ACCESS_TOKEN'
    oauth_id = 0  # Example OAuth ID, replace with your actual OAuth ID
    
    try:
        accounts = get_google_analytics4_accounts(access_token, oauth_id)
        print("Google Analytics 4 Accounts:", accounts)
        
        # Extract and print the IDs
        ids = extract_ids(accounts)
        print("Account IDs:", ids)
    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")

Listing All Available Google Analytics 4 Properties

This facilitates the interaction with the Dataddo Headless API to retrieve properties from Google Analytics 4 . By executing a POST request to a specific endpoint, the script uses the oAuthId and accountId provided in the JSON payload to authenticate and authorize the request. The necessary headers, including the Authorization token, ensure secure communication with the API. Upon successful connection, the API returns a list of property objects from GA4 associated with the given account. Each object in the response array typically contains a value representing the property identifier and a label providing a human-readable name. The script is designed to extract and print these value attributes, thereby aiding users in efficiently managing and accessing GA4 properties related to their accounts. This process is crucial for applications that require dynamic data retrieval from GA4 based on user-specific or application-specific credentials.

POST /connectors/google_analytics4/actions/property
Accept: application/json
Content-Type: application/json
Authorization: Bearer ACCESS_TOKEN

{
    "oAuthId":"",
    "accountId":""
}
import requests

# Define the URL for the API endpoint
url = 'https://headless.dataddo.com/customer-api/v1/connectors/google_analytics4/actions/property'

# Define the headers including Authorization token
headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ACCESS_TOKEN'  # Replace ACCESS_TOKEN with your actual access token
}

# Define the JSON payload
payload = {
    "oAuthId": "",
    "accountId": ""
}

# Make the POST request
response = requests.post(url, json=payload, headers=headers)

# Check if the request was successful
if response.status_code == 200:
    # Parse the JSON response
    data = response.json()
    
    # Extract 'value' from each object in the response array
    values = [item['value'] for item in data if 'value' in item]
    print('Values:', values)
else:
    print('Failed to retrieve data:', response.status_code, response.text)

Create


{
   "connectorId": "google_analytics_4",
   "templateId": "index",
   "allow_empty": true,
   "oAuthId": OAUTH_ID, // Identifier of the authorizer
   "accountId": "ACCOUNT_ID", // Selected by user in your UI
   "propertyId": "PROPERTY_ID", // Selected by in your UI
   "usePropertyId": true,   
   "useInsertDate": false,
   "useDataddoHash": false,
   "label": "GA4 Source",
   "dimension": [
       "date",
       "sessionDefaultChannelGroup",
       "sessionSourceMedium",
       "city",
       "unifiedScreenName",
       "region",
       "eventName",
       "pagePath",
	"deviceCategory"
   ],
   "metric": [
       "totalAdRevenue",
       "activeUsers",
       "averageSessionDuration",
       "engagedSessions",
       "newUsers",
       "conversions",
       "sessions",
       "eventCount",
       "userEngagementDuration"
   ],
   "sync_frequency": "day",
   "day_of_week": "2",
   "day_of_month": "1",
   "hour": "2",
   "minute": "10",
   "timezone": "UTC",
   "dateRange": "{{1d1}}",
   "type": "googleAnalytics4",
   "storageStrategy": "clean" 
}


Was this article helpful?