how to post on linkedin API

In this tutorial, we will learn how to use the LinkedIn API and Python to make a text post, a link post, and a link post with a mention to a company page.


This post is part of the complete guide on how to use the LinkedIn API with Python

  1. Get Your OAuth Credentials
  2. Authenticate Using OAuth 2.0
  3. Get Your Own User Information
  4. Simple Steps to Find Any Company ID on LinkedIn
  5. How to Post On LinkedIn API With Python
  6. How to Scrape LinkedIn Jobs with Python

1. Prepare the Request

Let’s set up a few things to prepare the API call regardless of what you want to post.


Subscribe to my Newsletter


  • Importing packages
  • Authenticate and Prepare the Header
  • Get your User ID
  • Define your URN
  • Define the API URL

Import Packages

Let’s install requests and import it.

$ pip install requests
import requests

Then, we will need to import local module.

from ln_oauth import auth, headers

Authenticate and Prepare the Header

Before making the request, you need to authorize your credentials and attach the access token to the header of the GET Request.

credentials = 'credentials.json'
access_token = auth(credentials) # Authenticate the API
headers = headers(access_token) # Make the headers to attach to the API call.

If you don’t know how to get the credentials, just read the post on how to get your LinkedIn OAuth credentials.

Get Your User ID

It is time to get your user ID that we will need to make a post to your wall.

We saw how to create the user_info() from the get_user_info.py module we created for the post Get user information with the LinkedIn API.

def user_info(headers):
    '''
    Get user information from Linkedin
    '''
    response = requests.get('https://api.linkedin.com/v2/me', headers = headers)
    user_info = response.json()
    return user_info

# Get user id to make a UGC post
user_info = user_info(headers)
urn = user_info['id']

Define Your Personal URN

In your request, you need to define who you are, by providing your URN.

urn:li:person:<your-user-id>

We have extracted the user ID from the user_info() function.

author = f'urn:li:person:{urn}'

Define the API URL

The API URL defines which API you want to use. In this case, we are using the UGC API, which replaces the Shares API. We are going to use only the ugcPosts URL in this tutorial.

api_url = 'https://api.linkedin.com/v2/ugcPosts'

2. Make a Simple Text Post

To prepare the body of your request to make a text post, you will need the author, your URN from the previous step, and the message that you want to share.

The Message of your Post

The message is the text associated with your post. The maximum length of your message for a UGC post is 1300 characters.

message = 'Preparing a LinkedIn Bot'

The body of the request

To share an organic post, you will be using com.linkedin.ugc.ShareContent

post_data = {
    "author": author,
    "lifecycleState": "PUBLISHED",
    "specificContent": {
        "com.linkedin.ugc.ShareContent": {
            "shareCommentary": {
                "text": message
            },
            "shareMediaCategory": "NONE"
        }
    },
    "visibility": {
        "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
    }
}

Make The Post to LinkedIn

This set-up is public, which means that anyone on the LinkedIn Platform will be able to view this share.

The request needs the api_url, the authenticated headers and the post_data to run.

if __name__ == '__main__':
    r = requests.post(api_url, headers=headers, json=post_data)
    r.json()

If your request is successful, it will return a 201 Created response, and the post will be identified by the X-RestLi-Id response header.

The if name equals main line checks whether you are running the module or importing it. If you are importing it, requests.post() will not run.

3. Make a Link Post

Keeping all the code from Step 1, we will modify the post_data body to add media to the ShareContent.

message = '''
Interested to automate LinkedIn using #Python and the LinkedIn API? 
Read this in-depth Python for #SEO post I wrote.
''' 
link = 'https://www.jcchouinard.com/how-to-use-the-linkedin-api-python/'
link_text = 'Complete tutorial using the LinkedIn API'

post_data = {
    "author": author,
        "lifecycleState": "PUBLISHED",
        "specificContent": {
            "com.linkedin.ugc.ShareContent": {
                "shareCommentary": {
                    "text": message
                },
                "shareMediaCategory": "ARTICLE",
                "media": [
                    {
                        "status": "READY",
                        "description": {
                            "text": message
                        },
                        "originalUrl": link,
                        "title": {
                            "text": link_text
                        }
                    }
                ]
            }
        },
        "visibility": {
            "com.linkedin.ugc.MemberNetworkVisibility": "CONNECTIONS"
        }
    }

Execute the Request.

if __name__ == '__main__':
    r = requests.post(api_url, headers=headers, json=post_data)
    r.json()

4. Share a Link Post and Mention a Company

Here, it start to become a little bit tricky.

First, I have not found how to mention another user, because I don’t have access to the people API to find what URN is associated with the user.

If you know how to get any user URN, please let me know!

Second, we need to manually find the company URN.

Third, we need to define where the mention starts and ends in the string so that LinkedIn know where to start the mention.

Find the Company URN

Finding any LinkedIn company ID is easy. Go to the company page on LinkedIn and click on “See all X employees on LinkedIn“. The company ID is in the URL after the “?facetCurrentCompany=%5B” parameter.

Add the company ID to the mention_id variable.

mention_name = 'iPullRank'
message = f'Watch Michael King from {mention_name} with Hamlet Batista at Ranksense talk about Automated #SEO Testing' 
mention_id = '9280143'
mention_urn = f'urn:li:organization:{mention_id}'
link = 'https://www.crowdcast.io/e/webinar-automated-testing'

Find Where the Mention is

We will create a function called find_pos() to find where the mention_name starts in the message.

def find_pos(mention_name, message):
    '''
    Find position of mention_name in the message
    '''
    index = 0
    if mention_name in message:
        c = mention_name[0]
        for ch in message:
            if ch == c:
                if message[index:index+len(mention_name)] == mention_name:
                    return index
            index += 1
    return -1

Then, we will check the length of the mention_name, that we will also need to mention the company.

len_uname = len(mention_name)
start = find_pos(mention_name, message)

Create the Body of the Request

Now, we will create the body of the request adding attributes to the shareCommentary object. Then length, start, value and com.linkedin.common.CompanyAttributedEntity are required to mention a company.

post_data = {
    "author": author,
        "lifecycleState": "PUBLISHED",
        "specificContent": {
            "com.linkedin.ugc.ShareContent": {
                "shareCommentary": {
                    "attributes": [
                        {
                            "length": len_uname,
                            "start": start,
                            "value": {
                                "com.linkedin.common.CompanyAttributedEntity": {
                                    "company": mention_urn
                                }
                            }
                        }
                    ],
                    "text": message
                },
                "shareMediaCategory": "ARTICLE",
                "media": [
                    {
                        "status": "READY",
                        "description": {
                            "text": message
                        },
                        "originalUrl": link,
                        "title": {
                            "text": message
                        }
                    }
                ]
            }
        },
        "visibility": {
            "com.linkedin.ugc.MemberNetworkVisibility": "CONNECTIONS"
        }
    }

if __name__ == '__main__':
    r = requests.post(api_url, headers=headers, json=post_data)
    r.json()

If you find how to get any user ID, first LET ME KNOW, next, you can replace the com.linkedin.common.CompanyAttributedEntity to the com.linkedin.common.MemberAttributedEntity and it will also work.

{
"com.linkedin.common.MemberAttributedEntity": {
    "member": "urn:li:person:<user-id>"
}

Run the Code

Now the time to run the code.

if __name__ == '__main__':
    r = requests.post(api_url, headers=headers, json=post_data)
    r.json()

Success!

Full Code

Sorry, I haven’t made the repository public to Github yet. Here is the full code for the link post

import requests

from ln_oauth import auth, headers

credentials = 'credentials.json'
access_token = auth(credentials) # Authenticate the API
headers = headers(access_token) # Make the headers to attach to the API call.

def user_info(headers):
    '''
    Get user information from Linkedin
    '''
    response = requests.get('https://api.linkedin.com/v2/me', headers = headers)
    user_info = response.json()
    return user_info

# Get user id to make a UGC post
user_info = user_info(headers)
urn = user_info['id']

# UGC will replace shares over time.
api_url = 'https://api.linkedin.com/v2/ugcPosts'
author = f'urn:li:person:{urn}'

message = '''
Interested to automate LinkedIn using #Python and the LinkedIn API? 
Read this in-depth Python for #SEO post by Jean-Christophe Chouinard.
Proof being, I just made this post using the LinkedIn API
''' 
link = 'https://www.jcchouinard.com/how-to-use-the-linkedin-api-python/'
link_text = 'Complete tutorial using the LinkedIn API'

post_data = {
    "author": author,
        "lifecycleState": "PUBLISHED",
        "specificContent": {
            "com.linkedin.ugc.ShareContent": {
                "shareCommentary": {
                    "text": message
                },
                "shareMediaCategory": "ARTICLE",
                "media": [
                    {
                        "status": "READY",
                        "description": {
                            "text": message
                        },
                        "originalUrl": link,
                        "title": {
                            "text": link_text
                        }
                    }
                ]
            }
        },
        "visibility": {
            "com.linkedin.ugc.MemberNetworkVisibility": "CONNECTIONS"
        }
    }

if __name__ == '__main__':
    r = requests.post(api_url, headers=headers, json=post_data)
    r.json()

Congratulations, you now have made your first text post using the LinkedIn API.

5/5 - (3 votes)