How to Automate Your LinkedIn Posts Using Python and the LinkedIn API

Photo by dlxmedia.hu on Unsplash

How to Automate Your LinkedIn Posts Using Python and the LinkedIn API

LinkedIn is one of the most powerful social media platforms for professionals. It can be an excellent tool for organizations looking to expand their reach and connect with potential customers and clients. But did you know that LinkedIn also has an API that can programmatically post content to the platform? The LinkedIn API allows organizations to automate their social media strategy and maximize their reach on the platform.

In this blog, we'll guide you through accessing the LinkedIn API, choosing the right endpoint for your posts, preparing your content, and making the API call to post your content to LinkedIn. Whether you're looking to promote a new product or service, share industry news, or build your brand on LinkedIn, this guide will help you utilize the LinkedIn API to its fullest potential. So, let's dive in and learn how to maximize your organization's reach on LinkedIn!

Setting up your LinkedIn App:

To use the LinkedIn API, you'll need to create a LinkedIn App first. Here are the steps:

  1. Go to the LinkedIn Developer's website and sign in with your LinkedIn account.

  2. Click on "Create App" and fill in the required information, such as the app name, description, and website URL.

  3. To proceed, navigate to the "Products" section of the LinkedIn Developers Portal and activate both the "Share on LinkedIn" and "Advertising API" products.

    1. Enabling the "Share on LinkedIn" product permits you to manage your profile through LinkedIn API.

    2. Enabling the "Advertising API" product permits you to manage your page through LinkedIn API. The steps after requesting access to the LinkedIn Advertising API include waiting for review, completing the compliance review, and signing the API terms of use.

  4. Verify your LinkedIn page by clicking on “Verify”

  5. To create a URL on LinkedIn, you need to click on the "Generate URL" button and then complete the few steps required by LinkedIn.

Retrieving the Access Token:

Once your app is created, you can use OAuth 2.0 authorization process to retrieve an access token. This token is used to authenticate your API requests to LinkedIn. Here's how to do it:

  1. Obtain your app credentials: Sign in to your LinkedIn Developers Portal account, go to your app's dashboard, and obtain your "Client ID" and "Client Secret" credentials.

  2. Authenticate the user: Your app needs to authenticate the user by sending them to the LinkedIn login page. You can do this by directing the user to the LinkedIn OAuth 2.0 authorization endpoint (linkedin.com/oauth/v2/authorization) with the following parameters:

    • response_type: Set this to "code" to request an authorization code

    • client_id: Set this to your app's client ID

    • redirect_uri: Set this to the URI that LinkedIn will redirect the user to after they have authorized your app

    • state: Set this to a random value to prevent cross-site request forgery (CSRF) attacks

    • scope: Set this to the LinkedIn API permissions that your app requires. For example, to request access to a user's profile, you would set this to "r_liteprofile".

      Here's an example of a final URL for step 2, after filling in the necessary parameters:

        https://www.linkedin.com/oauth/v2/authorization?
          response_type=code&
          client_id=your_client_id&
          redirect_uri=https://yourwebsite.com/callback&
          state=12345&
          scope=r_liteprofile
      

      Note: Make sure to replace "your_client_id" with your actual LinkedIn app's client ID, and "yourwebsite.com/callback" with the URL where you want to receive the authorization code.

  3. Receive the authorization code: After the user has granted your app access to their LinkedIn account, they will be redirected to the redirect URI you specified in the previous step. The authorization code will be included in the query string of the URI. Store the access token securely, as it will be used for all future API requests.

  4. Request an access token: Use the authorization code to request an access token from the LinkedIn OAuth 2.0 token endpoint (linkedin.com/oauth/v2/accessToken) by sending a POST request with the following parameters:

    • grant_type: Set this to "authorization_code"

    • code: Set this to the authorization code that you received in step 3

    • redirect_uri: Set this to the same URI that you used in step 2

    • client_id: Set this to your app's client ID

    • client_secret: Set this to your app's client secret

      To send the POST request for step 4, you can use any HTTP client library or tool that supports sending POST requests with URL-encoded parameters in the request body. Here's an example of how to do this using the Python Requests library.

        import requests
      
        url = 'https://www.linkedin.com/oauth/v2/accessToken'
        params = {
            'grant_type': 'authorization_code',
            'code': 'your_authorization_code',
            'redirect_uri': 'https://yourwebsite.com/callback',
            'client_id': 'your_client_id',
            'client_secret': 'your_client_secret'
        }
        response = requests.post(url, data=params)
      
        if response.status_code == 200:
            access_token = response.json()['access_token']
            print('Access token:', access_token)
        else:
            print('Error:', response.status_code, response.text)
      

      Replace the "your_authorization_code", "yourwebsite.com/callback", "your_client_id", and "your_client_secret" parameters with the values you obtained in the previous steps.

  5. Receive the access token: If the access token request is successful, LinkedIn will respond with an access token that you can use to make authenticated requests to the LinkedIn API on behalf of the user.

Note: Access tokens are temporary and will expire after a certain amount of time. You will need to refresh the access token periodically to maintain access to the LinkedIn API.

Verifying the Access Token:

After retrieving the access token, it's important to verify that the token is valid and has not expired. To do this, you can make a test API call using the access token and check the response status code.

Here's a sample code in Python to verify the access token:

import requests

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

headers = {
    'Authorization': f'Bearer {access_token}',
    'Connection': 'Keep-Alive',
    'Content-Type': 'application/json',
}

response = requests.get(api_url, headers=headers)
if response.status_code == 200:
    print('Access token is valid!')
else:
    print('Access token is invalid or has expired.')

This code makes an API call to retrieve the authenticated user's profile using the access token. If the access token is valid, the API call will return a response with a status code of 200, indicating that the token is still valid. If the access token is invalid or has expired, the API call will return an error response with a status code other than 200.

Steps for making LinkedIn API requests:

After verifying the access token, you can proceed with making API requests to LinkedIn. Here are the steps to follow:

  1. Choose the appropriate endpoint for your API request. For example, to post a status update to LinkedIn, you would use the ugcPosts endpoint.

  2. Prepare your API request by constructing the request URL, specifying any necessary request headers, and providing the request body in the appropriate format. The request body will typically include the post's content, such as text, images, and links.

  3. Make the API request using the appropriate HTTP method (e.g. POST, GET, PUT), and include the access token in the request header.

  4. Handle the API response by checking the response status code and parsing the response body, if applicable.

Here's an example code snippet in Python for posting a status update to LinkedIn:

import requests

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

headers = {
    'Authorization': f'Bearer {access_token}',
    'Connection': 'Keep-Alive',
    'Content-Type': 'application/json',
}

post_body = {
    'author': 'urn:li:person:<your_linkedin_id>',
    'lifecycleState': 'PUBLISHED',
    'specificContent': {
        'com.linkedin.ugc.ShareContent': {
            'shareCommentary': {
                'text': 'Check out our latest blog post!',
            },
            'shareMediaCategory': 'ARTICLE',
            'media': [
                {
                    'status': 'READY',
                    'description': {
                        'text': 'Read our latest blog post about LinkedIn API!',
                    },
                    'originalUrl': '<your_blog_post_url>',
                },
            ],
        },
    },
    'visibility': {
        'com.linkedin.ugc.MemberNetworkVisibility': 'PUBLIC',
    },
}

response = requests.post(api_url, headers=headers, json=post_body)
if response.status_code == 201:
    print('Post successfully created!')
else:
    print(f'Post creation failed with status code {response.status_code}: {response.text}')

This code posts a status update to LinkedIn using the ugcPosts endpoint. The post includes a text commentary and a link to the blog post. The visibility is set to public, meaning that the post will be visible to all LinkedIn users. The API response is checked to ensure that the post was successfully created.

In conclusion, the LinkedIn API offers a powerful set of features that can help organizations to enhance their marketing, recruiting, and networking efforts. By following the steps outlined in this blog, you can set up your LinkedIn App, retrieve an access token, and make API requests to post updates and retrieve data. With a little creativity and experimentation, you can unlock the full potential of the LinkedIn API to achieve your business goals.

If you're interested in learning more about extracting LinkedIn profile data, we highly recommend checking out the following YouTube video: