How to send and receive statistics with the LinkedIn API

[ad_1]
Should you be spending time composing think pieces and interacting with entrepreneurs and professionals on LinkedIn? Will it help your company or your clients’ businesses? Or does it increase vanity metrics?
Such problems are rare but research points to the answer. Any lingering doubts can be further alleviated by optimizing content distribution using LinkedIn’s application programming interfaces (APIs). Learn how to use the LinkedIn API to post to your company page or your users.
Why LinkedIn Is Important for Your Business
LinkedIn is a popular hub for B2B marketing and sales. A survey of B2B marketing professionals shows that LinkedIn leads all other social networks effectively. Some 77 percent said they provided the best results among non-paid platforms and 79% agreed among paid platforms, ahead of others.
LinkedIn users seem to agree. Although many associate LinkedIn with resumes and jobs, in reality, content impressions are 15 times that of job postings. Some surveys find 75% of prospective buyers evaluate sellers based on thought leadership, and 70% of users see LinkedIn as a trusted source.
Clearly, the increased distribution of content on LinkedIn brings great returns on time invested. By using APIs and automation, businesses can increase these returns by increasing LinkedIn marketing while reducing the manual effort.
Introduction to the LinkedIn API Landscape
LinkedIn APIs enable web and mobile applications to use LinkedIn data and features for their unique business needs.
LinkedIn publishes the following APIs:
- A platform for consumer solutions: It includes many of the basic features we are used to – profiles, network, posts, and comments.
- A platform for marketing engineers: An advanced set of consumer platforms with advanced features such as organization management.
- Compliance APIs: Similar to a marketing platform but with data security features required by regulated industries.
- Talent solutions: Recruitment-related functionality available only to select partners.
- Learning solutions: LinkedIn learning platform features and is only available 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 many of LinkedIn’s features without app permission. But for features like posting to company pages, your app must get permission from the marketing platform. This section describes the general 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 information such as name and logo.
- You must associate your app with a company page. If you don’t have pages, create one.
2. Request Application Verification on Company Page
- On the Settings tab, tap “Verify” to get the verification link.
- Send that link to the company page manager you selected earlier.
- When an administrator opens that link, they are asked to confirm their responsibility for your application. If they confirm, you are notified that your app is verified and you can continue 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 create a consumer platform.
- To post on company pages, request access to the “Sales Developer Forum.” However, it must be approved after you provide information about your application.
- Your application may take a while to review and expect a few rejections before it is approved.
4. Review your Application Approval

On the Auth tab, register the OAuth redirect URL for your application. You will use it later when you get the access token.
Under the OAuth 2.0 scopes section, verify that your application has these scopes:
w_member_social
r_liteprofile
w_organization_social
(only if you have requested access to the marketing platform)
Store the client ID and client secret securely in a database or vault.
Get Consent From Your Users
Your app should ask your users to allow it to use their LinkedIn accounts. This is done using the OAuth 2.0 authorization code flow. After user authentication with LinkedIn and app authorization, it generates an access token for each user that allows your app to make API calls to use 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:
- To create posts on LinkedIn profiles, you need
scope=r_liteprofile w_member_social
. - For posts on company pages, add
w_organization_social
in the range. - Access tokens do not expire for 60 days. Treat them like passwords and store them securely in your user database.
Unlike many other OAuth services, LinkedIn does not issue refresh tokens to anyone. Only other authorized partners receive them. If you get one, remember those refresh tokens you can expire 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 shipping APIs exist in different versions. Conflicting or outdated information in documents only adds to the confusion.
We’ve reviewed the documentation and come up with these tips to help you avoid confusion:
- Always use the Post API. It replaces the User Generated Content API and the Shares API.
- The preferred base URL for most REST APIs now
/rest/
not/v2/
. For the Post API, use/rest/posts
not/v2/posts
. The latter is still active but has been withdrawn. - The exception to the previous location is the profile API. Keep using
/v2/me
not/rest/me
because the last one missesACCESS_DENIED
errors. - Since multiple versions of the API exist, you must specify the version you want in it
Linkedin-Version: yyyymm
the head. The API will then behave as described in the documentation for that version.

With those items cleared, 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
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 to a user page, use a uniform resource name (URN) like “urn:li:person:{ID}
“. Find that ID at/v2/me
profile endpoint.
To post to a customer’s company page, use the “urn:li:organization:{ID}
” (Note: This requires marketing platform authorization in your application and the page administrator role for the user).commentary={text}
: The text of your post.
Always add these four application topics:
Authorization: Bearer {access_token}
LinkedIn-Version: {yyyymm}
: The API version that your application can handle.X-Restli-Protocol-Version: 2.0.0
Content-Type: application/json
If the request is successful, you receive a status of 201 (created) and x-restli-id
the reply header contains the URN of the new post, urn:li:share:{ID}
.
Code that uses 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('
{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(
'', {
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 Post Statistics with the LinkedIn API
LinkedIn reports detailed metrics of company pages and posts to them from page statistics and shares statistical results. Your app must be approved for the LinkedIn marketing platform to receive analytics. Also, metrics are not available for posts on a user’s personal page.
Send this API request to get post metrics:
GET
organizationalEntity=urn:li:organization:{org-id}
&shares[0]=urn:li:share:{post-id}
organizationalEntity=urn:li:organization:{org-id}
: URN of your company or client pageshares[0]=urn:li:share:{post-id}
: The URN of the post on that page that you want your metrics for
The data in 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 writing. For example:
GET
Alternative Social Media API for LinkedIn
Ayrshare’s social media API is a simple LinkedIn API for posting content and getting analytics.
Get ready to use the Ayrshare API
Get started with the Ayrshare API in just three steps:

You are ready to use our APIs as shown in the examples below.
Post your organization’s videos on LinkedIn Using Python
Do you wish to post automatically to your or your company’s LinkedIn page? For example, whenever your sales people upload a helpful product training video, you want it on your LinkedIn company page.
To do so, simply call Ayrshare /post
conclusion with your video on mediaUrls
parameter (Note: You need a Premium or Business plan to post videos, but text posts and single image posts are available in 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': ['
'platforms': ['linkedin']
}
headers = {
'Authorization': f'Bearer {os.environ["AYRSHARE_API_KEY"]}',
'Content-Type': 'application/json'
}
r = requests.post('
json=params, headers=headers)
ret = r.json()
You will get a JSON response like this:
{
"status": "success",
"errors": [],
"postIds": [{
"status": "success",
"platform": "linkedin",
"postUrl": "
"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 integration easier.
Post Your Users’ Content to Their LinkedIn Company Pages
For any content – eg, jobs – published by a user on your site, you may want to repost it theirs LinkedIn page. To do so, call the same /post
finally but pass that user’s profile key to profileKeys
parameter.
This is shown in the Node.js snippet below (Note: Run this server side, not in the 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(' {
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 calls easier.
Get details in the post
Using the /analytics
Finally, you can get information about how the post works and present it to your users:
POST
You will get 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.
Increase B2B Marketing for Your Users Using the LinkedIn API
This article introduced you to effective B2B marketing using the power of LinkedIn APIs. For more insights on LinkedIn, read our articles on the best social media for B2B customer acquisition and the top 10 social media APIs for developers.