Unlocking Social Media Insights with Cognitive Actions

1 Jul 2025
Unlocking Social Media Insights with Cognitive Actions

The Social Media Audience Insights API provides developers with powerful tools to analyze social media engagement and audience demographics. By leveraging cognitive actions, developers can gain deeper insights into their social media performance, enabling them to make data-driven decisions that enhance engagement and optimize content strategies. This service simplifies the process of gathering and interpreting audience data, making it an essential resource for businesses and social media managers looking to elevate their online presence.

Prerequisites

To get started with the Social Media Audience Insights API, you'll need an API key and a basic understanding of how to make API calls. This foundational knowledge will allow you to effectively integrate the cognitive actions into your applications.

Analyze Instagram Post Metrics

The Analyze Instagram Post Metrics action provides a detailed analysis of posts over a specified time period. This includes valuable insights on hashtags, post types, and the effectiveness of text length, helping users understand what resonates with their audience.

Purpose

This action addresses the need for businesses and marketers to evaluate the performance of their Instagram content. By analyzing metrics, users can identify trends and adapt their strategies accordingly.

Input Requirements

To utilize this action, you must provide the following parameters:

  • clientId: The unique identifier for your application.
  • from: The start date for the analysis period in 'DD.MM.YYYY' format.
  • to: The end date for the analysis period in 'DD.MM.YYYY' format.
  • sort: The order in which results are returned (default is 'date').
  • type: The type of content to analyze (options include 'posts', 'stories', or 'mentions').
  • advertisement: A boolean value to indicate whether to include advertisements in the results.

Expected Output

The output will be a comprehensive dataset detailing the performance of Instagram posts, including likes, comments, engagement rates, and insights on the use of hashtags.

Use Cases for this Action

  • Content Strategy Optimization: Marketers can refine their content strategies based on post performance data to enhance engagement.
  • Hashtag Effectiveness: By analyzing which hashtags drive the most interaction, users can optimize their hashtag strategies.
  • Performance Comparison: Users can compare the effectiveness of different post types (e.g., images vs. videos) to inform future content creation.

```python
import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "9edb048a-19d7-4a56-876e-49a9183f0aea" # Action ID for: Analyze Instagram Post Metrics

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "to": "30.11.2023",
  "from": "01.11.2023",
  "sort": "date",
  "type": "posts",
  "clientId": "INST:17841400005463628"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Retrieve Social Media Profile Statistics
The **Retrieve Social Media Profile Statistics** action allows users to obtain comprehensive statistics about social media profiles, including audience demographics and engagement metrics.

### Purpose
This action helps businesses and influencers understand their audience better, allowing for targeted marketing strategies and improved content creation based on demographic insights.

### Input Requirements
To use this action, you need to specify:
- **clientId**: The unique identifier for your application.

### Expected Output
The output will include detailed statistics such as gender distribution, age demographics, location data, and engagement rates across different platforms.

### Use Cases for this Action
- **Audience Segmentation**: Businesses can segment their audience based on demographics to tailor their marketing efforts.
- **Influencer Collaboration**: Brands can find potential influencers whose audience demographics align with their target market.
- **Performance Benchmarking**: Users can compare their profile statistics against industry standards to assess their social media performance.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "aa47ba27-cd94-435c-8e0c-062c9f37c89e" # Action ID for: Retrieve Social Media Profile Statistics

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "clientId": "INST:17841400005463628"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Retrieve Account Tags
The **Retrieve Account Tags** action provides users with all tags associated with social media accounts, allowing for filtering based on desired tags and nesting specifications.

### Purpose
This action is beneficial for users looking to categorize content or find relevant accounts based on specific tags, enhancing their social media strategy.

### Input Requirements
To utilize this action, you must provide:
- **limit**: The maximum number of results to return.
- **type**: The type of request, with a default value of 'location'.
- **query**: Optional search terms for filtering results.
- **parent**: References a parent entity or context for the request.

### Expected Output
The output will include a list of tags associated with accounts, along with their hierarchy and associated metadata.

### Use Cases for this Action
- **Content Discovery**: Users can discover content related to specific tags, helping them engage with relevant topics.
- **Targeted Marketing**: By filtering accounts based on tags, businesses can identify potential collaborators or influencers in their niche.
- **Trend Analysis**: Users can analyze which tags are trending within their audience, allowing for timely content creation.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "d12f2e13-efc2-4328-96d1-26d1132d40b9" # Action ID for: Retrieve Account Tags

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "type": "location",
  "limit": "100"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Generate Activity Time Graph Data
The **Generate Activity Time Graph Data** action provides data for plotting user activity time graphs on social media accounts. This helps in determining optimal publishing times and planning collaborations with influencers for maximum engagement.

### Purpose
This action addresses the need for businesses to identify the best times to post content, ensuring they reach their audience when engagement is highest.

### Input Requirements
To use this action, you must provide:
- **customerId**: A unique string that identifies the customer.

### Expected Output
The output will include data points for likes, comments, and interactions over specific time intervals, allowing users to visualize their engagement patterns.

### Use Cases for this Action
- **Optimal Posting Schedule**: Users can determine the best times to post their content based on historical engagement data.
- **Influencer Collaboration Timing**: Brands can plan collaborations with influencers during peak engagement times for maximum visibility.
- **Performance Tracking**: Users can track how engagement varies throughout different times of the day or week.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "dd2a9cfa-9a47-4dc1-b54f-4ba427460cba" # Action ID for: Generate Activity Time Graph Data

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "customerId": "INST:17841400005463628"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Retrieve Instagram Post Engagement Metrics
The **Retrieve Instagram Post Engagement Metrics** action fetches the number of likes, comments, and views for a specified Instagram post using its URL.

### Purpose
This action helps users analyze engagement metrics for individual Instagram posts, providing insights into what content performs best.

### Input Requirements
To utilize this action, you must provide:
- **postUrl**: The URL of the Instagram post to be processed.

### Expected Output
The output will include metrics such as likes, comments, views, and the post's associated image or video URL.

### Use Cases for this Action
- **Content Performance Analysis**: Users can evaluate which posts are driving the most engagement, informing future content strategies.
- **Campaign Effectiveness**: Businesses can measure the success of marketing campaigns by analyzing engagement on specific promotional posts.
- **Social Media Reporting**: Users can generate reports on post performance metrics for stakeholders or clients.

import requests
import json

# Replace with your actual Cognitive Actions API key and endpoint
# Ensure your environment securely handles the API key
COGNITIVE_ACTIONS_API_KEY = "YOUR_COGNITIVE_ACTIONS_API_KEY"
# This endpoint URL is hypothetical and should be documented for users
COGNITIVE_ACTIONS_EXECUTE_URL = "https://api.cognitiveactions.com/actions/execute"

action_id = "e6551716-a018-4716-9972-ecc87cba90e4" # Action ID for: Retrieve Instagram Post Engagement Metrics

# Construct the exact input payload based on the action's requirements
# This example uses the predefined example_input for this action:
payload = {
  "postUrl": "https://www.instagram.com/p/C1hfPhUiwo3/"
}

headers = {
    "Authorization": f"Bearer {COGNITIVE_ACTIONS_API_KEY}",
    "Content-Type": "application/json",
    # Add any other required headers for the Cognitive Actions API
}

# Prepare the request body for the hypothetical execution endpoint
request_body = {
    "action_id": action_id,
    "inputs": payload
}

print(f"--- Calling Cognitive Action: {action.name or action_id} ---")
print(f"Endpoint: {COGNITIVE_ACTIONS_EXECUTE_URL}")
print(f"Action ID: {action_id}")
print("Payload being sent:")
print(json.dumps(request_body, indent=2))
print("------------------------------------------------")

try:
    response = requests.post(
        COGNITIVE_ACTIONS_EXECUTE_URL,
        headers=headers,
        json=request_body
    )
    response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)

    result = response.json()
    print("Action executed successfully. Result:")
    print(json.dumps(result, indent=2))

except requests.exceptions.RequestException as e:
    print(f"Error executing action {action_id}: {e}")
    if e.response is not None:
        print(f"Response status: {e.response.status_code}")
        try:
            print(f"Response body: {e.response.json()}")
        except json.JSONDecodeError:
            print(f"Response body (non-JSON): {e.response.text}")
    print("------------------------------------------------")


## Conclusion
The Social Media Audience Insights API empowers developers to gather and analyze critical data from social media platforms, enhancing their content strategies and engagement efforts. By integrating these cognitive actions, businesses can unlock valuable insights into their audience, optimize their content, and ultimately drive better performance across their social media channels. As you explore these powerful tools, consider how they can fit into your existing workflows and help you achieve your social media goals.