• Aucun résultat trouvé

Facebook Query Language

3.2. Exploring the LinkedIn API

3.2.1. Making LinkedIn API Requests

As is the case with other social web properties, such as Twitter and Facebook (discussed in the preceding chapters), the first step involved in gaining API access to LinkedIn is to create an application. You’ll be able to create a sample application at https://www.link edin.com/secure/developer; you will want to take note of your application’s API Key, Secret Key, OAuth User Token, and OAuth User Secret credentials, which you’ll use to programmatically access the API. Figure 3-1 illustrates the form that you’ll see once you have created an application.

Figure 3-1. To access the LinkedIn API, create an application at https://www.linke din.com/secure/developer and take note of the four OAuth credentials (shown here as blurred values) that are available from the application details page

3.2. Exploring the LinkedIn API | 91

With the necessary OAuth credentials in hand, the process for obtaining API access to your own personal data is much like that of Twitter in that you’ll provide these creden‐

tials to a library that will take care of the details involved in making API requests. If you’re not taking advantage of the book’s virtual machine experience, you’ll need to install it by typing pip install python-linkedin in a terminal.

See Appendix B for details on implementing an OAuth 2.0 flow, which you will need to build an application that requires an arbitrary user to authorize it to access account data.

Example 3-1 illustrates a sample script that uses your LinkedIn credentials to ultimately create an instance of a LinkedInApplication class that can access your account data.

Notice that the final line of the script retrieves your basic profile information, which includes your name and headline. Before going too much further, you should take a moment to read about what LinkedIn API operations are available to you as a developer by browsing its REST documentation, which provides a broad overview of what you can do. Although we’ll be accessing the API through a Python package that abstracts the HTTP requests that are involved, the core API documentation is always your de‐

finitive reference, and most good libraries mimic its style.

Should you need to revoke account access from your application or any other OAuth application, you can do so in your account settings.

Example 3-1. Using LinkedIn OAuth credentials to receive an access token suitable for development and accessing your own data

from linkedin import linkedin # pip install python-linkedin

# Define CONSUMER_KEY, CONSUMER_SECRET,

# USER_TOKEN, and USER_SECRET from the credentials

# provided in your LinkedIn application CONSUMER_KEY = ''

CONSUMER_SECRET = '' USER_TOKEN = '' USER_SECRET = ''

RETURN_URL = '' # Not required for developer authentication

# Instantiate the developer authentication class

auth = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET, USER_TOKEN, USER_SECRET,

1. If any of your connections have opted out of LinkedIn API access, their first and last names will appear as

“private” and additional details will not be available.

RETURN_URL,

permissions=linkedin.PERMISSIONS.enums.values())

# Pass it in to the app...

app = linkedin.LinkedInApplication(auth)

# Use the app...

app.get_profile()

In short, the calls available to you through an instance of LinkedInApplication are the same as those available through the REST API, and the python-linkedin documenta‐

tion on GitHub provides a number of queries to get you started. A couple of APIs of particular interest are the Connections API and the Search API. You’ll recall from our introductory discussion that you cannot get “friends of friends” (“connections of con‐

nections,” in LinkedIn parlance), but the Connections API returns a list of your con‐

nections, which provides a jumping-off point for obtaining profile information. The Search API provides a means of querying for people, companies, or jobs that are avail‐

able on LinkedIn.

Additional APIs are available, and it’s worth your while to take a moment and familiarize yourself with them. The quality of the data available about your professional network is quite remarkable, as it can potentially contain full job histories, company details, geographic information about the location of positions, and more.

Example 3-2 shows you how to use app, an instance of your LinkedInApplication, to retrieve extended profile information for your connections1 and save this data to a file so as to avoid making any unnecessary API requests that will count against your rate-throttling limits, which are similar to those of Twitter’s API.

Be careful when tinkering around with LinkedIn’s API: the rate limits don’t reset until midnight UTC, and one buggy loop could potentially blow your plans for the next 24 hours if you aren’t careful.

Example 3-2. Retrieving your LinkedIn connections and storing them to disk

import json

connections = app.get_connections()

connections_data = 'resources/ch03-linkedin/linkedin_connections.json'

3.2. Exploring the LinkedIn API | 93

f = open(conections_data, 'w')

f.write(json.dumps(connections, indent=1)) f.close()

# You can reuse the data without using the API later like this...

# connections = json.loads(open(connections_data).read())

For an initial step in reviewing your connections’ data, let’s use the prettytable package as introduced in previous chapters to display a nicely formatted table of your connec‐

tions and where they are each located, as shown in Example 3-3. If you’re not taking advantage of this book’s preconfigured virtual machine, you’ll need to type pip install prettytable from a terminal for most of the examples in this chapter to work; it’s a package that produces nicely formatted, tabular output.

Example 3-3. Pretty-printing your LinkedIn connections’ data

from prettytable import PrettyTable # pip install prettytable pt = PrettyTable(field_names=['Name', 'Location'])

pt.align = 'l'

[ pt.add_row((c['firstName'] + ' ' + c['lastName'], c['location']['name'])) for c in connections['values']

if c.has_key('location')]

print pt

Sample (anonymized) results follow and display your connections and where they are currently located according to their profiles.

+---+---+

| Name | Location | +---+---+

| Laurel A. | Greater Boston Area |

| Eve A. | Greater Chicago Area |

| Jim A. | Washington D.C. Metro Area |

| Tom A. | San Francisco Bay Area |

| ... | ... | +---+---+

A full scan of the profile information returned from the Connections API reveals that it’s pretty spartan, but you can use field selectors as outlined in the Profile Fields online documentation to retrieve additional details, if available. For example, Example 3-4 shows how to fetch a connection’s job position history.

Example 3-4. Displaying job position history for your profile and a connection’s profile

import json

# See http://developer.linkedin.com/documents/profile-fields#fullprofile

# for details on additional field selectors that can be passed in for

# retrieving additional profile information.

# Display your own positions...

my_positions = app.get_profile(selectors=['positions']) print json.dumps(my_positions, indent=1)

# Display positions for someone in your network...

# Get an id for a connection. We'll just pick the first one.

connection_id = connections['values'][0]['id']

connection_positions = app.get_profile(member_id=connection_id, selectors=['positions']) print json.dumps(connection_positions, indent=1)

Sample output reveals a number of interesting details about each position, including the company name, industry, summary of efforts, and employment dates:

{

"title": "Chief Technology Officer", "company": {

"industry": "Computer Software", "name": "Digital Reasoning Systems"

},

"summary": "I lead strategic technology efforts...", "isCurrent": true,

3.2. Exploring the LinkedIn API | 95

As might be expected, some API responses may not necessarily contain all of the in‐

formation that you want to know, and some responses may contain more information than you need. Instead of making multiple API calls to piece together information or potentially stripping out information you don’t want to keep, you could take advantage of the field selector syntax to customize the response details. Example 3-5 shows how you can retrieve only the name, industry, and id fields for companies as part of a re‐

sponse for profile positions.

Example 3-5. Using field selector syntax to request additional details for APIs

# See http://developer.linkedin.com/documents/understanding-field-selectors

# for more information on the field selector syntax

my_positions = app.get_profile(selectors=['positions:(company:(name,industry,id))']) print json.dumps(my_positions, indent=1)

Once you’re familiar with the basic APIs that are available to you, have a few handy pieces of documentation bookmarked, and have made a few API calls to familiarize yourself with the basics, you’re up and running with LinkedIn.