How to Post a Message to LinkedIn Using Python

How to Post a Message to LinkedIn Using Python

In this blog post, we'll walk you through how to post a message to LinkedIn using Python. We'll use the LinkedIn API to post content programmatically, leveraging the requests library to interact with the API.


Why Post to LinkedIn Programmatically?

Posting to LinkedIn programmatically has several advantages, including:

  • Automation: Automate content sharing, such as blog updates, product releases, or company news, at specific intervals.
  • Consistency: Ensure that your posts are timely and consistent without manually logging into LinkedIn every time.
  • Efficiency: Streamline your content-sharing workflows, especially for marketing teams and content managers.

In this guide, we will focus on how to automate posting a simple update to LinkedIn using Python.


Prerequisites

Before you start, ensure that you have the following in place:

  1. LinkedIn Developer Account:


Article content
Created an app


  • Get your client_id, client_secret, and redirect_uri.


Article content
Get Client ID and Client secret token


2. OAuth 2.0 Authentication:

  • LinkedIn API requires authentication via OAuth 2.0. You’ll need to get an access token to interact with the LinkedIn API.
  • The OAuth flow involves:
  • Redirecting the user to the LinkedIn authorization URL.
  • After the user grants access, capturing the authorization code.
  • Exchanging the authorization code for an access token.


Article content
Get the authentication token


3. Python & Requests Library:

  • You need Python installed, along with the requests library to make HTTP requests.

You can install the requests library using:

pip install requests        

Step 1: Generate the Access Token

Before you can post on LinkedIn, you must authenticate and get an access token. This token allows your application to act on behalf of the user and access LinkedIn resources.

Here’s a simplified OAuth 2.0 flow for LinkedIn:

  1. Request Authorization Code: Redirect the user to LinkedIn’s authorization URL:

https://www.garudax.id/oauth/v2/authorization?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&scope=r_liteprofile%20w_member_social        

  1. Exchange Authorization Code for Access Token: Once the user grants permission, LinkedIn will redirect to the redirect_uri with a code. Use this code to get the access token:

import requests

url = 'https://www.garudax.id/oauth/v2/accessToken'
payload = {
    'grant_type': 'authorization_code',
    'code': 'AUTHORIZATION_CODE',
    'redirect_uri': 'YOUR_REDIRECT_URI',
    'client_id': 'YOUR_CLIENT_ID',
    'client_secret': 'YOUR_CLIENT_SECRET'
}

response = requests.post(url, data=payload)
access_token = response.json()['access_token']
print("Access Token:", access_token)        

Save this access_token as it will be used to authenticate API requests.


Step 2: Post Content to LinkedIn Using Python

Now that you have the access token, you can use Python to post a message to LinkedIn. Here’s the code to share a simple text update:

import requests

ACCESS_TOKEN = 'your_access_token'  # Obtain through OAuth 2.0
AUTHOR_URN = 'urn:li:person:your_person_id'  # Replace with your LinkedIn person URN

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

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

headers = {
    'Authorization': f'Bearer {ACCESS_TOKEN}',
    'Content-Type': 'application/json',
    'X-Restli-Protocol-Version': '2.0.0'
}

response = requests.post(url, headers=headers, json=post_data)

if response.status_code == 201:
    print("Post shared successfully on LinkedIn!")
else:
    print("Error:", response.status_code, response.text)        

Explanation of the Code:

1. API Endpoint:

The URL https://api.linkedin.com/v2/ugcPosts is used to create posts on LinkedIn’s user-generated content (UGC) platform.

2. Post Data:

The post_data dictionary contains the content you want to share. It includes:

  • author: This should be your LinkedIn person URN, which uniquely identifies you on LinkedIn.
  • specificContent: Contains the post content, such as the text of the update and the media category (in this case, NONE since we’re posting just text).
  • visibility: Sets the visibility of the post (e.g., PUBLIC for everyone to see).

3. Request:

  • The requests.post() function sends the POST request to LinkedIn's API, along with the necessary headers (including the access token).
  • The response is checked to confirm if the post was successful.


Conclusion

Automating LinkedIn posts using Python is a powerful way to streamline your content-sharing process. Whether you’re a developer, marketer, or professional, automating updates ensures that your content reaches your network at the right time, without manual intervention.

By following this guide, you can quickly set up a Python script that interacts with the LinkedIn API and post updates programmatically. If you’re looking to extend this functionality, you can integrate the script with a content management system or use it for scheduled posts.

Feel free to experiment with different post types (e.g., images, articles) and add more advanced features to your LinkedIn automation setup.


Final Thoughts

Using Python to automate LinkedIn posts is a great way to boost productivity and engagement. Whether you are managing personal updates, company announcements, or blog promotions, this automation approach can save you a lot of time while maintaining a consistent presence on LinkedIn.


Thank you for reading...

To view or add a comment, sign in

More articles by Himanshu Singh

Others also viewed

Explore content categories