Writing a script for LinkedIn can be a great way to automate various tasks and processes on the platform. LinkedIn provides an API that allows developers to programmatically access many aspects of LinkedIn including profiles, connections, groups, posts, jobs and more. With some knowledge of scripting and the LinkedIn API, it is possible to create scripts that can save you time and effort. Some common uses of LinkedIn scripts include:
- Automating connection requests
- Messaging new connections
- Posting status updates
- Searching profiles and extracting data
- Applying to jobs
When writing a LinkedIn script there are a few key things you need:
- A LinkedIn developer account and API keys
- An understanding of LinkedIn’s API documentation
- Experience with a scripting language like Python, Javascript, Ruby etc
- A code editor or IDE for writing your script
- Libraries and packages for accessing LinkedIn’s API
In this comprehensive guide, we will cover everything you need to know to get started with writing scripts for LinkedIn including:
Getting Set Up with LinkedIn’s API
The first step to automating LinkedIn through scripts is to set up developer access to LinkedIn’s API. Here is what you need to do:
- Go to https://www.linkedin.com/developers/ and click “Sign in”
- Sign in with your regular LinkedIn account credentials
- Agree to LinkedIn’s API terms of use
- Register your application by clicking “Create Application”. Provide an application name, description, logo and select “Non-commercial use”
- After creating your app, you will get an API Key and Secret. Save these somewhere safe as they allow your scripts to make API calls.
- Turn on permissions for your app for the parts of the API you want to use. For example, r_liteprofile, r_emailaddress, w_member_social.
Once you have created your LinkedIn developer account and registered an application, you can use the API Key and Secret to authenticate your scripts. The permissions will determine what your scripts can access.
Choosing a Scripting Language
The LinkedIn API provides a REST API with JSON endpoints. This means you can use any programming language capable of making HTTP requests and parsing JSON to access it. Here are some of the most popular choices:
Python
Python is one of the most widely used languages for scripting and automation. It has simple syntax, vast libraries and integrates well with REST APIs. For accessing LinkedIn’s API, the requests library makes it easy to send HTTP requests while json handles parsing.
JavaScript
JavaScript is another excellent choice for LinkedIn automation. It is commonly used for web scraping and automation. The Fetch API and JSON global object can be used to call REST endpoints. Scripts can be run directly in Node.js or through libraries like Puppeteer.
Ruby
Ruby is another programming language well suited for writing scripts and bots. It has robust HTTP client libraries like RestClient and JSON handling built-in. LinkedInBot is one popular Ruby framework specifically for accessing LinkedIn’s API.
PHP
PHP is a common server-side scripting language used by developers to integrate websites with backends and APIs. For LinkedIn, the cURL library provides HTTP request functionality. JSON parsing can be handled with json_decode.
C#
For .NET developers, C# provides a way to interact with LinkedIn through scripts. The HttpClient class enables REST API calls while APIs like Json.NET are available for JSON handling. This can be executed via .NET Core CLI.
Authentication Options
LinkedIn provides several ways for your scripts to authenticate with its API:
API Key & Secret
This is the simplest method – your registered app includes an API key and secret that can be passed with all API calls for authentication. This is suitable for scripts handling non-sensitive tasks.
OAuth 2.0
For accessing private resources and performing actions as a specific LinkedIn member, OAuth 2.0 is recommended. Your script programmatically guides the user through approving permissions. You then use the access token to authenticate.
Service Accounts
Service accounts are for establishing trust between your app and LinkedIn through a server-to-server exchange. They are useful for cases where manual user approval is not feasible.
Choosing the right authentication depends on your use case. For public data, API keys may suffice. For member-specific actions, OAuth 2.0 is better. Service accounts are meant for server-based scripts.
Important LinkedIn API Concepts
Before diving into code, it helps to understand some key LinkedIn API concepts:
Resources
Resources represent the different objects you can access via the API – profiles, posts, companies etc. Each has its own endpoints.
URIs
The API endpoints follow a standard URI structure of:
https://api.linkedin.com/{version}/{resource}?{parameters}
For example: https://api.linkedin.com/v2/jobs
HTTP Methods
REST APIs use HTTP verbs to operate on resources:
GET – Read resources
POST – Create resources
PUT – Update resources
DELETE – Delete resources
Parameters
Parameters can be added to endpoints as query strings to filter data or specify options. For example, ?state=published.
Fields
You can control what fields are returned for resources by specifying fields parameters like ?fields=id,title,description
Understanding how LinkedIn structures its API helps in knowing how to compose requests and what options are available.
Accessing Public LinkedIn Data
Much of the data on LinkedIn can be accessed without any authentication using the public API endpoints. Here are some examples of accessing public resources:
Searching Profiles
“`js
const profilesUrl = ‘https://api.linkedin.com/v2/search/blended?keywords=software&resultType=PEOPLE’
fetch(profilesUrl)
.then(response => response.json())
.then(data => {
// process profile data
})
“`
This searches profiles containing “software” using the blended search and returns profile results.
Getting Company Details
“`python
import requests
company_id = ‘1586’ # Microsoft
url = f’https://api.linkedin.com/v2/organizations/{company_id}’
response = requests.get(url)
data = response.json()
print(data[‘name’]) # Microsoft
“`
Uses the Organizations API to fetch info on a specific company by ID.
Searching Jobs
“`php
$apiKey = ‘xxxxxxxxxxxx’;
$url = ‘https://api.linkedin.com/v2/jobs/search?keywords=python&location=London&apikey=’ . $apiKey;
$response = file_get_contents($url);
$data = json_decode($response, true);
print_r($data[‘elements’][0][‘title’]); // Junior Python Developer
“`
Searches for “python” jobs in London using the Jobs API. The apikey parameter is required.
These examples demonstrate accessing public LinkedIn data by calling API endpoints directly without needing authorization.
Authenticating via OAuth 2.0
To access private LinkedIn resources and perform actions as a LinkedIn member, you need to authenticate with OAuth 2.0. Here is an example workflow:
- Redirect the user to LinkedIn’s OAuth 2.0 authorization URL with your client ID to request access:
- User signs in to LinkedIn and approves permissions.
- User is redirected back to your redirect URI with a authorization code.
- Your script exchanges the code for an access token:
- Use the access token in the Authorization header to make API calls as that user.
“`
https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id={ID}&scope={SCOPE}&state={STATE}&redirect_uri={URI}
“`
“`
POST https://www.linkedin.com/oauth/v2/accessToken
“`
This allows your script to access member data like connections, posts, messages and more on their behalf. The access token expires after a set period and needs to be refreshed.
Example Scripts
Let’s look at some real world examples of scripts that automate various LinkedIn tasks.
Auto-Connecting Chrome Extension
This browser extension clicks the “Connect” button on targeted profiles to send connection requests:
“`js
// content script injected on LinkedIn profile pages
const connectButtons = document.getElementsByClassName(‘bt-request-buffed’)
for(const button of connectButtons) {
button.click()
}
“`
It uses Puppeteer to extract profile links from search pages and iterate over each one:
“`js
const puppeteer = require(‘puppeteer’)
puppeteer.launch().then(async browser => {
const page = await browser.newPage()
await page.goto(‘https://www.linkedin.com/search/results/people/?keywords=software%20engineer’)
const links = await page.evaluate(() => {
const anchors = document.querySelectorAll(‘a.app-aware-link’)
return Array.from(anchors).map(anchor => anchor.href)
})
for(const link of links) {
await page.goto(link)
// run content script on each page
}
})
“`
Job Application Bot
This bot automatically applies to relevant job postings:
“`python
import os
import requests
from linkedin_api import Linkedin
# authenticate
api = Linkedin(access_token=os.environ.get(‘ACCESS_TOKEN’))
jobs = api.search_jobs(keywords=[“python”, “remote”])
for job in jobs:
if job.isSponsored:
continue
job.apply([resume]) # apply with resume
print(f”Applied to {job.title} at {job.company.name}”)
“`
It uses the access token to search jobs and apply to any relevant ones. Useful for automated job hunting.
Profile Scraper
This script extracts data from LinkedIn profiles into a CSV file:
“`ruby
require ‘linkedin-scraper’
require ‘csv’
scraper = Linkedin::ProfileScraper.new
CSV.open(‘contacts.csv’, ‘w’) do |csv|
csv << ['Name', 'Headline', 'Location']
scraper.search('marketing', 300).each do |profile|
row = [profile.name, profile.headline, profile.location]
csv << row
end
end
```
The Linkedin-Scraper gem handles searching and parsing profile data which is output to the CSV format.
Libraries for LinkedIn’s API
While you can call LinkedIn’s API directly using URL requests and JSON parsing, libraries and clients make development easier. Here are some options for different languages:
Python
– linkedin-api
– linkedin-python
JavaScript
– node-linkedin
– linkedin-private-api
Ruby
– linkedin-scraper
– linkedin_api
PHP
– phpleague/linkedin-api
– lullabot/linkedin-api-client
C#
– tmolty/LinkedInNetSDK
These provide wrappers around LinkedIn’s API to abstract away low level details like authentication, HTTP requests, pagination etc. Check documentation for usage examples.
Common Use Cases
Here are some common things developers build using LinkedIn’s API:
– Job posting and application bots – search jobs and auto-apply
– Recruitment tools – find and source candidate profiles
– Social media managers – post status updates and articles
– Browser extensions – customize LinkedIn UI and automation
– Contact scrapers – extract profile data into spreadsheets
– Marketing analytics – analyze company pages and follower demographics
– LinkedIn bots – automated engagement like connecting, messaging etc
The API access allows automating and enhancing many LinkedIn activities. Just be sure to comply with LinkedIn’s terms of service.
Limitations and Things to Keep in Mind
When working with LinkedIn’s API, there are some limitations and considerations:
– Rate limits – LinkedIn enforces hourly and daily request limits
– Data restrictions – personal member data requires proper API scopes
– Bot detection – excessive automated actions may lead to blocking
– Terms of service – no scraping, spam, privacy breaches, etc
– Deprecated API versions – migrate to latest supported version
– User access tokens expire – plan for refreshing expired tokens
– Poor documentation – prepare to do your own exploration
Keep these in mind when designing your program to avoid disruptions. Ensure your use case aligns with LinkedIn’s policies.
Conclusion
LinkedIn provides a REST API to tap into its platform’s rich data and automation potential. With an appropriate scripting language and authentication, you can leverage LinkedIn’s API for scraping, marketing, recruitment, automation and more.
The key is understanding the capabilities of the API, setting up proper developer access, choosing the right scripting approach and libraries, and handling authentication plus rate limiting. Put together correctly, scripts allow you to work smarter by outsourcing repetitive LinkedIn tasks to code.
So explore LinkedIn’s developer documentation, think creatively about use cases, and start scripting to supercharge your LinkedIn productivity.