LinkedIn API: How to Post and Get Analytics With the LinkedIn API

Should you invest time crafting thought pieces and engaging with the entrepreneurs and professionals on LinkedIn? Will it help your company or your clients’ businesses? Or does it just increase vanity metrics? 

Such dilemmas are not uncommon but research points to the answer. Any lingering doubt can be further eased by optimizing content distribution using LinkedIn’s application programming interfaces (APIs). Learn how to use a LinkedIn API to post on your company’s page or those of your users.

Why LinkedIn Is Important for Your Business

LinkedIn is the preferred hub for B2B marketing and sales. Surveys of B2B marketing professionals show that LinkedIn leads all other social networks in effectiveness. Some 77% said it gave the best results among non-paid platforms and 79% agreed among paid platforms, well ahead of others.

LinkedIn users seem to concur. Though many associate LinkedIn with resumes and jobs, in reality, impressions for content are 15x those for job postings. Other surveys find 75% of would-be buyers evaluate vendors based on thought leadership, and 70% of users see LinkedIn as a trusted source.

Clearly, increasing content distribution on LinkedIn brings excellent returns for the time invested. Using APIs and automation, businesses can boost these returns by scaling up LinkedIn marketing while reducing the effort of doing it all manually.

Introduction to the LinkedIn API Landscape

LinkedIn APIs enable web and mobile applications to use LinkedIn’s data and features for their unique business needs. 

LinkedIn publishes the following APIs:

  • Consumer solutions platform: Covers most of the basic features we’re familiar with – profiles, networking, posts, and comments.
  • Marketing developer platform: A superset of the consumer platform with advanced features like organization management.
  • Compliance APIs: Same as the marketing platform but with data security features required by regulated industries.
  • Talent solutions: Functionality related to hiring that’s available only to select partners.
  • Learning solutions: Features for LinkedIn’s learning platform and available only to select partners.

Sales Navigator: Features related to sales use cases and available only to select partners.

Getting Ready to Use the LinkedIn API

The consumer API provides most features of LinkedIn without any app approval. But for features like posting on company pages, your app must undergo marketing platform approval. This section explains the common steps to access both platforms.

1. Register Your App

  • Sign in to the LinkedIn developer portal.
  • Create a new app with “Create app.”
  • Enter basic details like a name and logo.
  • You must associate your app with a company page. If you don’t have any pages, create one.

2. Request App Verification From the Company Page

A screen showing the verification of a LinkedIn account API
  • On the Settings tab, press “Verify” to obtain a verification link.
  • Send that link to the administrator of the company page you selected before.
  • When the administrator opens that link, they’re asked to confirm their responsibility for your app. If they confirm, you’re notified that your app is verified and you can proceed with other settings.

3. Request Access to Features

  • On the Products tab, request access to both “Share on LinkedIn” and “Sign In with LinkedIn.” They make up the consumer platform.
  • To post on company pages, request access to the “Marketing Developer Platform.” However, it has to be approved after you provide details about your application. 
  • Your application may take a while to review and expect a few rejections before being approved.

4. Review Your Application Authorization

LinkedIn API Permissions

On the Auth tab, register the OAuth redirect URL for your app. You’ll use it later when getting an access token.

Under the OAuth 2.0 scopes section, ensure that your app has these scopes:

  • w_member_social
  • r_liteprofile
  • w_organization_social (only if you requested marketing platform access)

Store the client ID and client secret securely in a database or vault.

Get Permission From Your Users

Your app must request your users to let it operate their LinkedIn accounts. This is done using the OAuth 2.0 authorization code flow. After user authentication with LinkedIn and authorization of the app, it produces an access token per user that lets your application make API calls to operate user accounts on their behalf.

Since the authorization API documentation is comprehensive and accurate, we won’t repeat the steps here. But some details to keep in mind:

  • For creating posts on LinkedIn profiles, you need scope=r_liteprofile w_member_social.
  • For posts on company pages, add w_organization_social to the scope.
  • Access tokens don’t expire for 60 days. Treat them like passwords and store them securely in your user database.

Unlike many other OAuth services, LinkedIn doesn’t issue refresh tokens to just anyone. Only some approved partners get them. If you get one, remember that refresh tokens don’t expire for a year.

Things You Should Know About the LinkedIn API

To avoid breaking client applications, LinkedIn maintains multiple versions of the APIs, each with different semantics. As of November 2022, three different posting APIs exist over different versions. Conflicting or stale information in the docs just adds to the confusion.

We have trawled through the docs and came up with these tips to help you avoid confusion:

  • Always use the Posts API. It replaces both the user-generated content API and the Shares API.
  • The preferred base URL for most REST APIs is now /rest/, not /v2/. For the Posts API, use /rest/posts, not /v2/posts. The latter still works but is deprecated.
  • An exception to the previous point is the profile API. Continue to use /v2/me, not /rest/me because the latter throws ACCESS_DENIED errors.
  • Since multiple versions of the API exist, you must specify the version you want in the Linkedin-Version: yyyymm header. The API will then behave as described by that version’s docs.
A screenshot of the linkedin marketing platform API versions

With that stuff cleared up, you’re ready for your first post.

Create Your First Post (Share) With the LinkedIn API

To share a post use the /post LinkedIn POST endpoint:

POST https://api.linkedin.com/rest/posts

The request body is a JSON object:

{
  "author": "urn:li:person:{ID}",
  "commentary": "Text of the post",
  "visibility": "PUBLIC",
  "lifecycleState": "PUBLISHED",
  "distribution": {
    "feedDistribution": "MAIN_FEED",
    "targetEntities": [],
    "thirdPartyDistributionChannels": []
  }
}
  • author={urn}: To post on a user’s page, use a uniform resource name (URN) like “urn:li:person:{ID}“. Get that ID from the /v2/me profile endpoint.
    To post on a client’s company page, use “urn:li:organization:{ID}” (Note: This requires marketing platform approval for your app and page administrator role for the user).
  • commentary={text}: The text of your post.

Always add these four request headers:

  • Authorization: Bearer {access_token}
  • LinkedIn-Version: {yyyymm}: The API version your application can handle.
  • X-Restli-Protocol-Version: 2.0.0
  • Content-Type: application/json

If the request succeeds, you get a 201 (created) status and the x-restli-id response header has the new post’s URN, urn:li:share:{ID}.

The code using server-side Node.js with JavaScript:

import fetch from 'node-fetch';
// Get the access token for the current user.
// from your database or vault.

const accessToken = getAccessTokenOfLoggedInUser();

const headers = {
  'Authorization': `Bearer ${accessToken}`,
  'LinkedIn-Version': '202211',
  'X-Restli-Protocol-Version': '2.0.0',
  'Content-Type': 'application/json'
};

// Get user ID and cache it.
const apiResp = await fetch('https://api.linkedin.com/v2/me',
    {headers: headers});
const profile = await apiResp.json();

const params = {
  "author": `urn:li:person:${profile.id}`,
  "commentary": "Text of the post",
  "visibility": "PUBLIC",
  "lifecycleState": "PUBLISHED",
  "distribution": {
    "feedDistribution": "MAIN_FEED",
    "targetEntities": [],
    "thirdPartyDistributionChannels": []
  }
};

const postResp = await fetch(
    'https://api.linkedin.com/rest/posts', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(params)
});

console.log(postResp.status);
if (postResp.ok) {
  const postId = postResp.headers.get('x-restli-id');
  console.log(postId);
}

Get Analytics for a Post With the LinkedIn API

LinkedIn reports detailed metrics for company pages and the posts on them from the page statistics and share statistics endpoints. Your app must have LinkedIn marketing platform approval to get analytics. Plus, metrics are not available for posts on a user’s personal page.

Send this API request to get metrics for a post:

GET https://api.linkedin.com/rest/organizationalEntityShareStatistics?
organizationalEntity=urn:li:organization:{org-id}
&shares[0]=urn:li:share:{post-id}
  • organizationalEntity=urn:li:organization:{org-id}: URN of your or a client’s company page
  • shares[0]=urn:li:share:{post-id}: URN of a post on that page that you want metrics for

The data in the response will look like this:

{
  "paging": {
    "count": 3,
    "start": 0
  },
  "elements": [
    {
      "totalShareStatistics": {
      "uniqueImpressionsCount": 927,
      "clickCount": 10976,
      "engagement": 0.0095647t9487,
      "likeCount": 31,
      "commentCount": 23,
      "shareCount": 2,
      "commentMentionsCount": 2,
      "impressionCount": 34416,
      "shareMentionsCount": 2
    },
    "organizationalEntity": "urn:li:organization:151279"
  }
  ]
}

If the API returns a large number of objects, the paging object is returned for pagination. For example:

GET https://api.linkedin.com/v2/{service}?start=10&count=10

An Alternative Social Media API for LinkedIn

The Ayrshare social media API is a simpler alternative to the LinkedIn API for posting content and getting analytics.

Get Ready to Use Ayrshare API

Get started with Ayrshare API in just three steps:

Linked what you want to set up company linked page or personal linked page in Ayrshare.

You’re all set to use our APIs as shown in the examples below.

Post Your Organization’s Videos on LinkedIn Using Python

Do you wish to automatically post on your or your company’s LinkedIn page? For example, whenever your marketing folks upload a useful product training video, you want it on your company’s LinkedIn page too.

To do so, just call the Ayrshare /post endpoint with your video in the mediaUrls parameter (Note: You need a Premium or Business plan to post videos, but text posts and single-image posts are available for all plans):

import os
import requests

# Add the API key to your application’s environment.
#     export AYRSHARE_API_KEY=YOUR-AYRSHARE-API-KEY

params = {
    'post': 'Product training video for our latest model WM300',
    'mediaUrls': ['https://TRAINING-VIDEO-LINK'],
    'platforms': ['linkedin']
}

headers = {
    'Authorization': f'Bearer {os.environ["AYRSHARE_API_KEY"]}',
    'Content-Type': 'application/json'
}

r = requests.post('https://app.ayrshare.com/api/post',
    json=params, headers=headers)
ret = r.json()

You’ll receive a JSON response like this:

{
  "status": "success",
  "errors": [],
  "postIds": [{
    "status": "success",
    "platform": "linkedin",
    "postUrl": "https://www.linkedin.com/feed/update/urn:li:share:699863680",
    "id": "urn:li:share:699863680"
   }],
 “id": "JsuoeTwnUSncf",
 "post": "Product training video for our latest model WM300"
}

You can also use the Social API SDK and Packages (including Python) to make the integration easier.

Post Your Users’ Content on Their LinkedIn Company Pages

For any content — e.g., jobs — published by a user on your platform, you may want to repost it on their LinkedIn page. To do so, call the same /post endpoint but pass in that user’s profile key in the profileKeys parameter.

This is shown by the Node.js snippet below (Note: Run this server-side, not in a browser; never store your API key in the browser):

import fetch from 'node-fetch'; // npm i node-fetch

// Add your API key to your application’s environment.
// export AYRSHARE_API_KEY=YOUR-AYRSHARE-API-KEY

const params = {
  'post': 'Job description posted by your user on your platform...',
  'platforms': ['linkedin'],
  'profileKeys': ['PROFILE-KEY-OF-USER-FROM-YOUR-DATABASE']
}

const apiResp = await fetch('https://app.ayrshare.com/api/post', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.AYRSHARE_API_KEY}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(params)
});

const post = await apiResp.json();

You can also use the Social API NPM package to make the calls simpler.

Get Insights on Posts

Using the /analytics endpoint, you can get insights on how a post is performing and present them to your users:

POST https://app.ayrshare.com/api/analytics/post

You’ll receive metrics like these:

...
"linkedin": {
    "analytics": {
      "uniqueImpressionsCount": 45, // Unique impressions for a post
      "shareCount": 2,    // Shares on a post
      "engagement": 34, // Clicks, likes, comments, shares
      "clickCount": 5,    // Clicks on a post
      "likeCount": 3,     // Likes on a count
      "impressionCount": 100, // Impressions on a post
      "commentCount": 2   // Comments count
    },
  },
...

See the analytics API for details.

Amplify Your Users’ B2B Marketing Using the LinkedIn API

This article introduced you to more effective B2B marketing using the posting capabilities of LinkedIn APIs. For more insights on LinkedIn, read our articles on the best social media platform for attracting B2B clients and the top 10 social media APIs for developers.