LinkedIn is one of the most popular professional social networks with over 600 million users worldwide. As a developer, you can leverage LinkedIn’s APIs to create powerful applications that can extract data, post updates, and more. In this comprehensive guide, we will walk through how to use LinkedIn’s APIs with Python.
Overview of LinkedIn’s API
LinkedIn provides several APIs to access their platform. The main ones are:
- REST API – For reading data from LinkedIn including profiles, companies, jobs, groups, posts, etc.
- Share API – For sharing content on LinkedIn including links, images, videos, etc.
- Sign In with LinkedIn – For enabling LinkedIn authentication in your apps.
- Ads API – For managing LinkedIn ads and campaigns programmatically.
In this post, we will focus on using the REST API from Python. The REST API uses OAuth 2.0 for authentication and provides responses in JSON format.
Registering a LinkedIn App
To get started, you need to register an app in LinkedIn’s developer portal to get API keys:
- Go to https://www.linkedin.com/developers/ and log in with your LinkedIn account.
- Click on My Apps in the top menu bar and then Create App.
- Fill in details like app name, description, logo, etc.
- Specify “r_liteprofile” and any other needed permissions.
- Agree to LinkedIn’s terms and hit submit.
This will provide you a Client ID and Client Secret which we will use later to authenticate.
Setting up the Python Environment
We will use the following libraries for accessing LinkedIn APIs in Python:
- requests – For making HTTP requests to API endpoints.
- json – For parsing JSON responses returned by the API.
- oauth2 – For handling OAuth2 authentication flow.
Let’s install these libraries:
pip install requests json oauth2
We also need an HTTP request library like requests_oauthlib which combines requests and oauth2 to manage the access token flow:
pip install requests_oauthlib
Authentication Process
To call LinkedIn APIs, we need an access token which identifies our application. Here are the steps to get one:
- Obtain authorization code:
from requests_oauthlib import OAuth2Session client_id = YOUR_CLIENT_ID client_secret = YOUR_CLIENT_SECRET redirect_uri = 'https://www.example.com/callback' auth_url = 'https://www.linkedin.com/oauth/v2/authorization' scope = ['r_liteprofile'] oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope) auth_url, state = oauth.authorization_url(auth_url) print(auth_url)
This will print out an authorization URL which when visited will provide a verification code.
- Exchange code for access token:
redirect_response = 'http://localhost:8000/callback?state=...&code=...' token = oauth.fetch_token(token_url='https://www.linkedin.com/oauth/v2/accessToken', client_secret=client_secret, authorization_response=redirect_response) print(token)
Pass the full redirect URL with code to fetch an access token.
This access token can then be used to call APIs by passing it in the request headers.
Fetching Profile Data
Let’s make an API call to fetch the profile data of the authenticated user:
import requests headers = {'Authorization': f'Bearer {token["access_token"]}'} api_url = f'https://api.linkedin.com/v2/me' response = requests.get(api_url, headers=headers) print(response.json())
This will print out the profile data in JSON format containing information like:
{ "id": "gFMaJnLKS...", "firstName": { "preferredLocale": { "country": "US", "language": "en" }, "localized": { "en_US": "John" } }, "lastName": { "preferredLocale": { "country": "US", "language": "en" }, "localized": { "en_US": "Doe" } }, ... }
We can see the user’s first and last name along with other details.
Searching Profiles
We can use the search API to find LinkedIn members matching certain keywords:
params = {'q': 'Software Engineer', 'count': 3} api_url = f'https://api.linkedin.com/v2/search/cluster?{urlencode(params)}' response = requests.get(api_url, headers=headers) print(response.json())
This searches for “Software Engineer” and returns 3 matches like:
{ "elements": [ { "member": true, "memberDistance": { "value": 2 }, "image": "https://media.licdn.com/dms/image/ABC.../profile-displayphoto-shrink_100_100/0/1234?e=1671312000&v=beta&t=nC8MDTzmEKOfJNpeOdcmVaPrdbGDc8uaqoP3RWEaqLw", "targetUrn": "urn:li:fs_memberProfile:ACoAACpniNQBd101NRQD1O_VdffgRdJXxXXQ920" }, { "member": true, "memberDistance": { "value": 2 }, "image": "https://media.licdn.com/dms/image/ABC.../profile-displayphoto-shrink_100_100/0/5678?e=1671312000&v=beta&t=6O0Sc11K8Hxj84OhJViaTMk80YBPXx_ee2Guo8TZzLc", "targetUrn": "urn:li:fs_memberProfile:ACoAAA_TZMBd101NRQD1O_VdffgRdJXxXXQ920" } ] }
We get back profile images and URNs for the matched members.
Posting Updates
The Share API can be used to post updates to LinkedIn:
import requests api_url = 'https://api.linkedin.com/v2/shares' headers = { 'X-Restli-Protocol-Version': '2.0.0', 'Authorization': f'Bearer {token["access_token"]}' } data = { "distribution": { "linkedInDistributionTarget": {} }, "owner": "urn:li:person:abc123", "subject": "Hello LinkedIn!", "text": { "text": "Posting from Python using LinkedIn's API" } } response = requests.post(api_url, headers=headers, json=data) print(response.status_code)
If successful, this will return 201 status code and post the “Hello LinkedIn!” update.
Conclusion
That covers the basics of accessing LinkedIn’s API with Python! The key steps are:
- Register an app to get API credentials
- Implement OAuth 2.0 flow to get access tokens
- Pass tokens in request headers to call APIs
- Use endpoints like /me, /search, /shares to get data, search, and post updates
LinkedIn’s API provides many more capabilities like retrieving company pages, job listings, groups, and user connections. The documentation provides additional details on all available endpoints.
Some other ideas for building applications using LinkedIn’s APIs:
- Job search engine
- Business lead generator
- Auto-messaging tool
- Social analytics
- Recruiting platform
Hopefully this gives you a good overview of how to access LinkedIn data and features with Python code! Let me know if you have any other questions.