How to Automate Creating Posts on LinkedIn

Created on Mar 8, 2022
Updated on Apr 14, 2022

LinkedIn API is not an easy API to use. I spent almost a whole day trying to figure out how to set up the access token to create articles on LinkedIn.

But…

I ended up to the conclusion that the LinkedIn API can’t write articles. It rather shares an article. It can post a text on the profile of the authenticated user.

It was frustrating spending all that time on this in vain. But it wasn’t that useless because of this blog post.

In this article, I’ll show you how to spend less time than I did. You’ll be able to set up the access token so that you can use it for your next project using LinkedIn API.

This tutorial focuses on the settings you need to post a text, media, and/or a URL link to your LinkedIn profile.

Let’s do it so that you’ll be able to do it.

Prerequisites

Create a new LinkedIn application or select an existing app from the LinkedIn Developer Portal.

Note that you need to create a new LinkedIn page for your application (if you don’t have it yet).

By default, the application will be authorized with 3-legged OAuth permission.

Configure Your Application

Select your application from the portal. Then, click on the “Auth” tab to view your application credentials.

You’ll see the client id and the client secret. You’ll need them as environment variables so copy and paste them in your shell file as follows:

export LINKEDIN_CLIENT_ID=<your client id>
export LINKEDIN_CLIENT_SECRET=<your client secret>

If you’re using a Linux, open this ~/.bashrc file and add the above lines. Similarly for Mac, if the default shell is bash, add the two lines to ~/.bash_profile . If zsh, add them to ~/.zshrc .

Make sure to run source ~/.bashrc , source ~/.bash_profile , or source ~/.zshrc (depending on your shell and machine) to make the environment variables available to your shell.

Finally, add the redirect link. Example: https://dev.example.com/auth/linkedin/callback

I put it as the Brainwave medium URL. So do whatever page you want to redirect to. Make sure to make it an absolute URL (with the protocol) like the example.

Request an Authorization Code

In the LinkedIn Developer Portal after you select your application, go to the “Products” tab.

Select two products that we need to access in this tutorial:

  1. Share on LinkedIn product
  2. Sign In with LinkedIn product

Let’s have a look at the following code snippet to get the authorization code:

import requests
import os
import webbrowser



def authorize():
    """Authorizes the user and opens a browser window to get the code."""

    url = "https://www.linkedin.com/oauth/v2/authorization"
    payload = {
        "response_type": "code",
        "client_id": os.getenv("LINKEDIN_CLIENT_ID"),
        "redirect_uri": "<your redirect link>",
        "state": "SADvGFt74M36bgwLoe753",
        'scope': 'r_liteprofile r_emailaddress w_member_social',
    }
    response = requests.Request("GET", url, params=payload)
    url = response.prepare().url
    webbrowser.open(url)


if __name__ == "__main__":
    authorize()

As you can see, the url here is the endpoint to get authorized and the payload is the parameters to be sent to the server.

And then, you’ll get a URL that will be opened in your browser via webbrowser.open() function and you’ll allow the application to be authorized.

Finally, look at the URL. You’ll find the redirected URL with the authorization code concatenated to it.

Let’s understand what the payload consists of:

  1. The response_type is the type of response that we want to get from the server. In this case, we want to get an authorization code. So, we’ll set it to code .
  2. The client_id is the client id that you generated when you created your application. Though you already pasted it in the environment variables.
  3. The redirect_uri is the URL that you set in the previous section.
  4. The state parameter is used to prevent CSRF attacks and it’s optional but recommended.
  5. The scope is the permissions that you need to access.

So for example, if redirect uri is https://medium.com/the-brainwave and state is SADvGFt74M36bgwLoe753 , then the URL on the browser will look like this: https://medium.com/the-brainwave?code=<YOUR_AUTHORIZATION_CODE>&state=SADvGFt74M36bgwLoe753

where <YOUR_AUTHORIZATION_CODE> is a very long string that you’ll need to copy and paste in the code parameter of the next step to get the access token.

Get the Access Token

In the following function, you’ll get the access token by sending a post request to the accessToken endpoint:

def get_access_token(code):
    """Returns an access token."""

    url = "https://www.linkedin.com/oauth/v2/accessToken"
    payload = {
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "<your redirect link>",
        "client_id": os.getenv("LINKEDIN_CLIENT_ID"),
        "client_secret": os.getenv("LINKEDIN_CLIENT_SECRET"),
    }
    response = requests.post(url, params=payload)
 return response.json()["access_token"]

if __name__ == "__main__":
    # authorize()
    code = "<YOUR_AUTHORIZATION_CODE>"
    print(get_access_token(code))

Where grant_type has the value of authorization_code and code is the authorization code that you got from the previous step. We discussed the rest of the parameters except the client_secret which is the credential that you pasted to the environment variables.

Now, you can use the access token to make requests to the LinkedIn API.

Use Postman to Test Your Application

It’s now to test your application using the access token. Postman is a great tool to do that.

Open Postman and go to the Authorization tab and select the authorization type to be OAuth2.0 . Then, select the Access Token option and paste the access token that you got from the previous step.

To create a post on LinkedIn, you’ll need to have an ID of your authorized user. You can get the ID by sending a request to the me endpoint:

GET https://api.linkedin.com/v2/me

as simple as a GET request to this https://api.linkedin.com/v2/me endpoint.

At the end of the response, you’ll see the ID of the user. Copy and paste it because you’ll need it in the next step.

Create a Post

Now, you can create a post by sending a POST request to the User Generated Content (UGC) API endpoint. So:

POST https://api.linkedin.com/v2/ugcPosts

Finally, go the body tab on Postman to fill the body of the request with the following parameters:

{
    "author": "urn:li:person:<YOUR ID FROM THE PREVIOUS STEP>",
    "lifecycleState": "PUBLISHED",
    "specificContent": {
        "com.linkedin.ugc.ShareContent": {
            "shareCommentary": {
                "text": "A text from LinkedIn API."
            },
            "shareMediaCategory": "ARTICLE",
            "media": [
                {
                    "status": "READY",
                    "description": {
                        "text": "The description field coming from LinkedIn API."
                    },
                    "originalUrl": "https://blog.linkedin.com/",
                    "title": {
                        "text": "Testing LinkedIn API"
                    }
                }
            ]
        }
    },
    "visibility": {
        "com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
    }
}

and replace <YOUR ID FROM THE PREVIOUS STEP> with the ID from the previous step.

This should create a post with this text: “A text from LinkedIn API.” sharing this article link: https://blog.linkedin.com/

Final Thoughts

We’ve discussed how to authenticate and authorize your LinkedIn account. This allows you to access some features of the API like creating posts and sharing media content.

You’ll only need to be authorized once unless you want to change the permissions. So don’t worry! you’ll be able to use the API without any further authorization to create and automate your LinkedIn posts.

Credit