Learn How to Fetch LinkedIn Ads Account Details and Profiles Using Python and LinkedIn Access Tokens
Welcome to this comprehensive guide! This guide will demonstrate how to leverage Python scripting and the LinkedIn API to extract crucial details from your LinkedIn Ads accounts. We’ll specifically focus on obtaining LinkedIn Ads Account IDs and Names, essential for retrieving in-depth campaign data. Whether you’re a seasoned marketer or just starting with LinkedIn Ads, this practical guide will empower you to efficiently gather the information you need.
Two primary methods exist for acquiring LinkedIn Ads Account IDs: manual retrieval from the dashboard or automated extraction using Python and the LinkedIn Advertising API. We’ll explore the advantages of each approach and guide you through the process. Let’s begin!
What is the LinkedIn API?
The LinkedIn Marketing API is used to programmatically query data, create and manage ads, create and manage campaigns, get account-related data, and perform a wide variety of other tasks. This guide helps you complete all the steps needed to use LinkedIn Marketing API successfully.
The LinkedIn API is the REST API and is the heart of all programmatic interactions with LinkedIn. LinkedIn API enables you to bring the power of the world’s largest professional network to your apps. By using the LinkedIn API (also known as LinkedIn Marketing API) you can use several LinkedIn services. Most importantly you can extract your campaign performance data using this API.
Quick Access:
- Guide to Set Up LinkedIn API
- Guide to building Python code to retrieve LinkedIn Campaign (Advertising) Insight using API
- Guide to get LinkedIn Ads Account ID (You are Here)
If you’re looking to maximize the potential of LinkedIn API integration, I’m here to help. Whether you have questions, need guidance, or automated token generation solutions, or require tailored consulting services, don’t hesitate to reach out. Let’s discuss how I can assist you in achieving your goals in just no time. Here are the ways you can connect with me, and let’s start a conversation about your unique requirements.
Method 1: Getting Ads Account ID from LinkedIn Campaign Manager
Manual Extraction:
- Log in: Access your LinkedIn Campaign Manager account.
- Locate Account List: You’ll typically find a list of the Ads Accounts you have permission to manage.
- Identify Account ID:
- Look for the label “Account ID” or a similar identifier next to each account name.
- Note down the numerical ID associated with each account (e.g., 605406338 for “Demo1”, 506806572 for “Demo2”).
Method 2: Python code to get LinkedIn Ad Account Details (Ad Account ID)
This method involves developing Python logic to retrieve LinkedIn Ads Account IDs and other relevant details (e.g., location, currency). To use this approach, you’ll need to complete the LinkedIn API setup process and have the necessary tokens to create the credential file.
2.1- Securely Store Tokens
Store your access token, refresh token, expiry time, and other credentials securely. Ideally, use cloud-based storage solutions like AWS Secrets Manager. Alternatively, store them in a .env file, which is designed to hold environment variables for a project. This method is recommended for this guide. While JSON files can be efficient for credential management, they are less secure and more vulnerable to unauthorized access.
Let’s create a .env file to manage your LinkedIn API credentials.
CLIENT_ID = "<Replace with your API app client ID >" CLIENT_SECRET = "<Replace with your API app client secret >" ACCESS_TOKEN = "<Replace with your API app access token >" ACCOUNT_ID = "<Replace this with LinkedIn ads account ID>"
You can also get the code to extract LinkedIn Marketing account details and campaign reports from my GitHub repo through GitHub Link.
2.2- Building Python Logic to get Account ID
This code snippet outlines the process of retrieving LinkedIn Ads Account details using Python and the LinkedIn API. Here’s a breakdown of the key steps:
- Read the credentials from the
.env
file (line 49). - Define a function (lines 15–39) to make a LinkedIn API call and retrieve Ads Account details from the response.
- Execute the function by calling it in the main script (line 52).
Take a moment to review the code and gain a basic understanding of its structure and functionality. Remember to save the file as linkedin_ads_accounts.py
to ensure proper execution.
#!/usr/bin/python3 # python3 ./linkedin_ads_account.py # The code gets the Auth User's LinkedIn Campaign Manager Account Details import requests import json import pandas as pd import sys from datetime import datetime import os from dotenv import load_dotenv load_dotenv() def get_linkedin_ads_account(access_token): try: url = "https://api.linkedin.com/v2/adAccountsV2?q=search&search.type.values[0]=BUSINESS&search.status.values[0]=ACTIVE" headers = {"Authorization": "Bearer "+access_token} #make the http call response = requests.get(url = url, headers = headers) #define a data frame to store the Linkedin account details account_df = pd.DataFrame() if response.status_code != 200: print("\n !! something went wrong !! Response: ",response) else: result = json.loads(response.text) if "elements" in result: accounts = result["elements"] account_list = accounts account_df = pd.DataFrame.from_records(account_list) return account_df except: print("\n !! function get_linkedin_ads_account Failed *** ",sys.exc_info()) raise if __name__ == '__main__': try: timestamp = datetime.strftime(datetime.now(),'%Y-%m-%d : %H:%M') print("DATE : ",timestamp,"\n") print("LinkedIn Ads Account data extraction process Starts") access_token = os.getenv("ACCESS_TOKEN") #call authentication function accounts_details_df = get_linkedin_ads_account(access_token) #print("\n Account Details :\n",accounts_details_df) print("\n Account Details :\n",accounts_details_df[["id","name","status","currency"]]) print("\n Linkedin Ads Account data extraction process Finished") except: print("\n !! Linkedin Ads Account data extraction process Failed !! ", sys.exc_info())
Run the above file with the command -> python3 ./linkedin_ads_accounts.py
You should see an output giving you Account Details along with your Account ID.
I’ve developed code (Python3 script) that can generate tokens, and extract data at the campaign group, campaign, ads, and creative levels. It efficiently handles pagination, date constraints, and API rate limits, and retrieves a wide range of metrics. If you’d like to get access to the code, feel free to get in touch with me directly on WhatsApp at +91 7892353323. You can also connect with me through LinkedIn or the provided Contact Form.
I’ll be happy to share the script and guide you through the integration process to ensure a smooth setup with your account. This can save you at least 5+ hours of effort, and I can also customize the code to meet your specific requirements.
Hope this guide was able to explain both the method of getting a LinkedIn Ads Account details and made it simple to understand, especially to get the Account ID by building a Python code using LinkedIn API.
Congratulations! You have successfully developed a Python3 script to use LinkedIn API to retrieve LinkedIn Marketing Ads Account Details. You can also look at Python code to extract LinkedIn campaign reporting and analytics data.
Hope I was able to solve the problem. If you like this article and think it was easy to understand do share it with your friends and connection. Thank you! See you soon.
If you have any questions or comments feel free to reach me at ->
Checkout out my other API Integration and Coding Solution Guide