LinkedInAPI Methods
A class to interact with LinkedIn's API for various data fetching and transformation tasks.
This class provides methods to authenticate a user, fetch organization IDs, fetch posts, fetch stats for posts, and convert time formats among other tasks. The class is designed to be a comprehensive utility for fetching and analyzing LinkedIn organizational data.
The main statistics (impressions, cicks, reach, likes, shares and comments) are fetched with the fetch_stats_for_a_post() method.
To get more detailed reactions such as Empathy, Praise, Interest, Appreciation or Funny, the fetch_reactions_for_a_post() has to be called.
To get video views call the method fetch_video_views_for_a_post().
Attributes:
| Name | Type | Description |
|---|---|---|
headers_v1 |
dict
|
Headers for API requests that use LinkedIn's API v1. |
headers_v2 |
dict
|
Headers for API requests that use LinkedIn's API v2. |
org_ids |
list
|
List of organization IDs associated with the authenticated user. |
posts_df |
DataFrame
|
DataFrame containing fetched posts data. |
post_stats_dict |
dict
|
Dictionary containing statistics for fetched posts. |
Examples:
api_client = LinkedIn(api_token="your-api-token") api_client.fetch_org_ids()
>>> api_client.fetch_posts()
Notes
- The class is designed to handle both individual and batch requests for efficiency.
- Ensure that you have the required libraries installed and valid API credentials.
Source code in veetility/linkedin_api.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | |
__init__(api_token=None, time_zone='Europe/London')
Initialize the LinkedIn API client with an API from the developer portal. Developer portal: https://developer.linkedin.com/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_token |
str
|
The API token for authentication. If not provided, a ValueError will be raised. |
None
|
time_zone |
str
|
The time zone for any date-time manipulations. Defaults to "Europe/London". |
'Europe/London'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the |
Attributes:
| Name | Type | Description |
|---|---|---|
api_token |
str
|
Stores the API token for use in other methods. |
headers_v1 |
dict
|
Stor=es headers for API X-Restli-Protocol-Version 1. |
headers_v2 |
dict
|
Stores headers for API VX-Restli-Protocol-Version 2. |
time_zone |
timezone
|
Stores the time zone information. |
Source code in veetility/linkedin_api.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
convert_pd_datetime_to_unix(pd_datetime)
Converts a pandas Timestamp to a Unix timestamp in milliseconds.
The method first converts the Timestamp to a Unix timestamp in seconds, then multiplies it by 1000 to get the timestamp in milliseconds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pd_datetime |
pandas.Timestamp
|
A pandas Timestamp object to convert. |
required |
Returns:
| Type | Description |
|---|---|
int or None: An integer representing the Unix timestamp in milliseconds if the conversion is successful. Returns None if an error occurs. |
Source code in veetility/linkedin_api.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | |
convert_unix_datetime(unix_format)
Converts a Unix timestamp to a pandas NaT (Not-a-Time) or datetime64 object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unix_format |
int, str, or None
|
The Unix timestamp to convert. Can be None, np.nan, an integer, or a string that can be converted to an integer. |
required |
Returns:
| Type | Description |
|---|---|
pandas.Timestamp or pandas.NaT: A pandas datetime64 object representing the converted Unix timestamp. Returns pandas.NaT if the conversion fails or input is invalid. |
|
Notes
- Unix timestamps are expected to be in milliseconds.
- If the provided timestamp is a string and not a digit, pandas.NaT is returned.
- If an exception occurs during conversion, pandas.NaT is returned.
Source code in veetility/linkedin_api.py
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 | |
exponential_backoff_delay(retry_count)
Implements an exponential backoff delay with jitter for server response problems.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
retry_count |
int
|
The number of times the request has been retried. |
required |
Side Effects
Introduces a time delay into the program execution.
Notes
The delay is calculated as follows: delay = (4 ** retry_count + 1) * 5 A jitter (random noise) is also added to the delay.
Source code in veetility/linkedin_api.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | |
fetch_follower_count(dict_of_urls)
Fetches the follower count of companies from their LinkedIn URLs.
This function sends a GET request to each URL present in the given dictionary, scrapes the page's HTML to find the follower count, and then stores this information in a pandas DataFrame.
Source code in veetility/linkedin_api.py
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | |
fetch_org_ids()
Fetches the organization IDs associated with the authenticated LinkedIn user who has the role of ADMINISTRATOR. This is useful if you want a list of organisation ids to iterate through to fetch information for each client.
Side Effects
Populates the org_ids attribute of the class instance with a list of organization IDs, if any are found.
Prints a message to the console if no data is found in the API response.
Source code in veetility/linkedin_api.py
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | |
fetch_org_info()
Fetches the organization information for the authenticated LinkedIn user based on organization IDs.
Returns:
| Type | Description |
|---|---|
pandas.DataFrame: A DataFrame containing the organization information. Each row corresponds to an organization. |
|
Side Effects
- Calls
fetch_org_idsmethod iforg_idsattribute is not already set. - Prints the API response to the console.
Source code in veetility/linkedin_api.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | |
fetch_posts(org_ids=None)
Fetches LinkedIn posts associated with the specified organization IDs or those found by the fetch_org_ids method.
The method utilizes convert_unix_datetime to convert Unix timestamps in the columns 'createdAt', 'lastModifiedAt' and
'publishedAt'] to datetime objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
org_ids |
list
|
List of organization IDs for which to fetch posts. Defaults to None, if None it will fetch the list of org_ids associated with the linkedIn account using the fetch_org_ids() function |
None
|
Returns:
| Type | Description |
|---|---|
pandas.DataFrame: A DataFrame containing fetched posts. Each row corresponds to a post. |
Source code in veetility/linkedin_api.py
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | |
fetch_reactions_for_a_post(urn_id, community_api_token, count=100)
Fetches the count of different types of reactions for a LinkedIn post specified by its URN (Uniform Resource Name) ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
urn_id |
str
|
The URN ID of the LinkedIn post for which reactions are to be fetched. Can be either 'ugcPost' or 'share'. |
required |
count |
int
|
The number of reactions to fetch per API call. Defaults to 100. |
100
|
Returns:
| Type | Description |
|---|---|
collections.Counter: A Counter object with keys as reaction types and values as their respective counts. |
Notes
- This method internally uses pagination to fetch all reactions in batches of size
count. - The function includes an exponential backoff delay mechanism to handle failed requests and retries up to 5 times.
- The URN ID is URL-encoded internally to handle special characters.
Source code in veetility/linkedin_api.py
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 | |
fetch_reactions_for_multiple_posts(list_of_posts, community_api_token, id_col_name='id')
Fetches the count of different types of reactions for a list of LinkedIn posts and aggregates them into a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
list_of_posts |
list
|
A list of URN IDs for the LinkedIn posts for which reactions are to be fetched. |
required |
id_col_name |
str
|
The name of the column in the output DataFrame that will store the URN IDs. Defaults to 'id'. |
'id'
|
Returns:
| Type | Description |
|---|---|
pandas.DataFrame: A DataFrame where each row represents the reaction count for a specific post. Columns represent different types of reactions, and the index is reset with a column containing URN IDs. |
Notes
- Calls the
fetch_reactions_for_a_postmethod internally for each post inlist_of_posts. - The DataFrame's NaN values are replaced with 0.
- The DataFrame's index is reset, and the column for URN IDs is renamed according to
id_col_name.
Source code in veetility/linkedin_api.py
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 | |
fetch_stats_for_a_post(post_id, org_id)
Fetches impressions, cicks, reach, likes, shares and comments for a specific LinkedIn post associated with a given organization. The org_id is requried for this endpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
post_id |
str or int
|
The identifier for the post for which to fetch statistics. |
required |
org_id |
str or int
|
The identifier for the organization under which the post was created. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict | A dictionary containing the fetched post statistics. |
Notes
- This method uses LinkedIn v1 API and requires appropriate headers for authentication.
- The method relies on
run_request_with_error_handlingfor API requests and error handling..
Source code in veetility/linkedin_api.py
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
fetch_stats_for_posts(posts_df=None, post_id_col='id', org_id_col='author')
Fetches statistics for a list of LinkedIn posts based on their IDs and associated organization IDs. The function adds a new column 'date_fetched_from_api' to the DataFrame with the current date which can be used to track how a posts metrics change over time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posts_df |
pd.DataFrame
|
DataFrame containing information about the posts for which to fetch statistics. If None, the method will use self.posts_df that would be created by previously running fetch_posts(). |
None
|
post_id_col |
str
|
The column name in |
'id'
|
org_id_col |
str
|
The column name in |
'author'
|
Returns:
| Type | Description |
|---|---|
pd.DataFrame: A DataFrame containing both the original post information and the fetched statistics. |
|
Notes
- The function fetches statistics using
fetch_stats_for_a_postmethod. - If fetching fails, an Excel sheet "Failed_fetch_posts_stats.xlsx" will be generated, so that data can be used to backfill if a large amount of post data was fetched before it broke. You could then only fetch the stats for the remaining posts to save time.
Source code in veetility/linkedin_api.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 | |
fetch_video_views_for_a_post(post_id)
Fetches video view statistics for a specific LinkedIn post based on its ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
post_id |
str or int
|
The unique identifier for the LinkedIn post for which to fetch video view statistics. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict | A dictionary containing the JSON response from the LinkedIn API, which includes video view statistics. |
Notes
- The function uses the
run_request_with_error_handlingmethod for making the API call. - The 'VIDEO_VIEW' type is hardcoded as it's specific to fetching video views.
Source code in veetility/linkedin_api.py
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 | |
fetch_video_views_for_multiple_posts(posts_df, media_type_col, post_id_col='id', output_col='videoViews')
Fetches video view statistics for multiple LinkedIn posts and adds them to a DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posts_df |
pd.DataFrame
|
A DataFrame containing information about multiple LinkedIn posts. It must include the columns specified by |
required |
media_type_col |
str
|
The column name in |
required |
post_id_col |
str
|
The column name in |
'id'
|
output_col |
str
|
The column name in which to store the fetched video views. Defaults to 'videoViews'. |
'videoViews'
|
Returns:
| Type | Description |
|---|---|
pd.DataFrame: A DataFrame with an additional column containing video view statistics, specified by |
Notes
- The function identifies posts with videos by checking if the string 'video' appears in the
media_type_colvalue for each row. - If the API call fails or if the post does not contain a video, np.nan will be inserted for that post.
Source code in veetility/linkedin_api.py
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 | |
run_request_with_error_handling(url, headers, params=None, max_retries=5, expected_json_response=True)
Wrapper function to execute an HTTP GET request with error handling and mutliple time delayed retries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url |
str
|
The URL endpoint to call. |
required |
headers |
dict
|
The headers to include in the request. |
required |
params |
dict
|
The parameters to include in the request. Defaults to None. |
None
|
max_retries |
int
|
The maximum number of times to retry the request. Defaults to 5. |
5
|
Returns:
| Type | Description |
|---|---|
requests.Response: The response object if the request is successful. |
Raises:
| Type | Description |
|---|---|
HTTPError
|
If a permanent HTTP error occurs (status code 400, 401, 403). |
Exception
|
If an unexpected error occurs or if the request fails multiple times. |
Source code in veetility/linkedin_api.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |