linkedin api python tutorial create a post

How To Create a Post With Linkedin API Using Python

In this post, we’re going to make a simple Python algorithm for creating a post on Linkedin with their API. Furthermore, we’ll do it without any existing Linkedin packages for accessing the API. We’ll do it with good ol’ requests only.

This may seem a little daunting, but don’t worry, it’s quite simple. Additionally, we’ll demonstrate how to make a GET and POST request, since we need to retrieve some private information.

Setup

Before we can start coding, we’ll need to get the Linkedin access token. To do that, you’ll need a Linkedin account and create an application in the developers portal. Once you have your application you’ll need to verify it, and add the necessary permissions to it.

You can find available these options under Products tab and what you need to add for this project are Share on LinkedIn and Sign In with LinkedIn using OpenID Connect products. These will give you permissions to access user info and enable you to post.

LinkedIn API permissions

Alright now you’re ready to get the access token. You can find the token generator tool under Docs and tools in the main menu and OAuth Token Tools in the dropdown options.

NOTE: You might encounter a problem while creating the access token, where the new window that offers you to confirm this action doesn’t work properly. It happened to me on Chrome, so I tried it again on Edge and it worked fine.

Once you get the access token, save it into a json file, which we will later use to retrieve it in code.

Using LinkedIn API with Python

Before we begin, like with any other Python project, we need to import all the necessary libraries. In our case here, we’ll need only 1 library that is not a part of Python installation – requests.

Here is the pip command to install it, if you haven’t yet.

pip install requests

And here are the imports for this project.

import os
import json
import requests

Next, we’ll need to define a function that will fetch our access token from that json file we saved it in earlier.

ROOT = os.path.dirname(__file__)

def get_token(token_name):
    with open(os.path.join(ROOT, 'auth.json'), 'r') as auth_file:
        auth_data = json.load(auth_file)
        token = auth_data[token_name]
        return token

ACCESS_TOKEN = get_token('linkedin-token')

So far so good. Now we’ll need to set a couple variables, which we’ll later use to make GET and POST request.

api_url_base = 'https://api.linkedin.com/v2/'

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

Alright, now we’re ready to make our first request. Here we’ll get the user information, because we’ll need the user ID later when we’ll make a POST request.

response = requests.get(api_url_base + 'userinfo', headers=headers)
URN = response.json()['sub']

Before, we make the POST request, we first need to define the post information including content, author, status, and more. Following is a demonstration of a simple text post with a link.

post_data = {
    "author": f"urn:li:person:{URN}",
    "lifecycleState": "PUBLISHED",
    "specificContent": {
        "com.linkedin.ugc.ShareContent": {
            "shareCommentary": {
                "text": "AK Codes is a programming oriented blog featuring posts about machine learning, DevOps, various API usage, and more."
            },
            "shareMediaCategory": "ARTICLE",
            "media": [
                {
                    "status": "READY",
                    "description": {
                        "text": "AK Codes - Making the learning process of programming and software development fun."
                    },
                    "originalUrl": "https://ak-codes.com/",
                    "title": {
                        "text": "AK Codes Blog"
                    }
                }
            ]
        }
    },
    "visibility": {
        "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
    }
}

Great, now we’re finally ready to create the post.

response = requests.post(api_url_base + 'ugcPosts', headers=headers, json=post_data)

if response.status_code == 201:
    print("Success")
    print(response.content)
else:
    print(response.content)

And once you run this script, a shiny new post should appear on your profile page.

LinkedIn post created through API with Python

Here is also the entire code of the project.

import os
import json
import requests

ROOT = os.path.dirname(__file__)

def get_token(token_name):
    with open(os.path.join(ROOT, 'auth.json'), 'r') as auth_file:
        auth_data = json.load(auth_file)
        token = auth_data[token_name]
        return token

ACCESS_TOKEN = get_token('linkedin-token')

api_url_base = 'https://api.linkedin.com/v2/'

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

response = requests.get(api_url_base + 'userinfo', headers=headers)
URN = response.json()['sub']

post_data = {
    "author": f"urn:li:person:{URN}",
    "lifecycleState": "PUBLISHED",
    "specificContent": {
        "com.linkedin.ugc.ShareContent": {
            "shareCommentary": {
                "text": "AK Codes is a programming oriented blog featuring posts about machine learning, DevOps, various API usage, and more."
            },
            "shareMediaCategory": "ARTICLE",
            "media": [
                {
                    "status": "READY",
                    "description": {
                        "text": "AK Codes - Making the learning process of programming and software development fun."
                    },
                    "originalUrl": "https://ak-codes.com/",
                    "title": {
                        "text": "AK Codes Blog"
                    }
                }
            ]
        }
    },
    "visibility": {
        "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
    }
}

response = requests.post(api_url_base + 'ugcPosts', headers=headers, json=post_data)

if response.status_code == 201:
    print("Success")
    print(response.content)
else:
    print(response.content)

Conclusion

To conclude, we made a simple Python algorithm for creating posts in Linkedin using their API. I learned a lot while working on this project and I hope you will find it helpful as well.

Share this article:

Related posts

Discussion(0)