bannerColor WARNING_YELLOW templateName stackForums

Sample Code: People Search


People Search Example Application

Many developers prefer to learn from sample code. Here is a small but self-contained application that authenticates the viewer and lets them use the PeopleSearch API to find the top 10 members that match a keyword closest to them in the LinkedIn network.

The application:

  • Displays a login button using an IN/Login tag which the viewer can use to authenticate and authorize the app
  • Uses the IN.API.PeopleSearch() API with a number of different chained methods to search for professionals
  • Parses the result and displays people in a list

Here's code for the entire app. It'll then be broken down bit-by-bit. If you have questions about any pieces, read the JavaScript API Tutorial and JavaScript API Reference. If using this code for yourself, be sure to use your own API key that's been properly configured to work for your domain.

The Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>LinkedIn JavaScript API Sample Application</title>
<!-- Load in the JavaScript framework and register a callback function when it's loaded -->
<script type="text/javascript" src="http://platform.linkedin.com/in.js">/*
api_key: s6nVKvpJ35zFoeAVntLuSYPyVxKU1N7PuJNii4bkKhAOF7_RdIZHlun0gTRIbgai
onLoad: onLinkedInLoad
authorize: true
*/</script>
 
<script type="text/javascript">
function onLinkedInLoad() {
     // Listen for an auth event to occur
     IN.Event.on(IN, "auth", onLinkedInAuth);
}
 
function onLinkedInAuth() {
     // After they've signed-in, print a form to enable keyword searching
     var div = document.getElementById("peopleSearchForm");
 
     div.innerHTML = '<h2>Find People on LinkedIn</h2>';
     div.innerHTML += '<form action="javascript:PeopleSearch();">' +
                      '<input id="keywords" size="30" value="JavaScript Ninja" type="text">' +
                      '<input type="submit" value="Search!" /></form>';
}
 
function PeopleSearch(keywords) {
     // Call the PeopleSearch API with the viewer's keywords
     // Ask for 4 fields to be returned: first name, last name, distance, and Profile URL
     // Limit results to 10 and sort by distance
     // On success, call displayPeopleSearch(); On failure, do nothing.
     var keywords = document.getElementById('keywords').innerText; 
     IN.API.PeopleSearch()
         .fields("firstName", "lastName", "distance", "siteStandardProfileRequest")
         .params({"keywords": keywords, "count": 10, "sort": "distance"})
         .result(displayPeopleSearch)
         .error(function error(e) { /* do nothing */ }
     );
}
 
function displayPeopleSearch(peopleSearch) {
     var div = document.getElementById("peopleSearchResults");
 
     div.innerHTML = "<ul>";
 
     // Loop through the people returned
     var members = peopleSearch.people.values;
     for (var member in members) {
 
         // Look through result to make name and url.
         var nameText = members[member].firstName + " " + members[member].lastName;
         var url = members[member].siteStandardProfileRequest.url;
 
         // Turn the number into English
         var distance = members[member].distance;
         var distanceText = '';
         switch (distance) {
         case 0:  // The viewer
             distanceText = "you!"
             break;
         case 1: // Within three degrees
         case 2: // Falling through
         case 3: // Keep falling!
             distanceText = "a connection " + distance + " degrees away.";
             break;
         case 100: // Share a group, but nothing else
             distanceText = "a fellow group member.";
             break;
         case -1: // Out of netowrk
         default: // Hope we never get this!
             distanceText = "far, far, away.";
         }
 
         div.innerHTML += "<li><a href=\"" + url + "\">" + nameText + 
         "</a> is " + distanceText + "</li>"
     }
 
     div.innerHTML += "</ul>";
}
</script>
</head>
<body>
<script type="IN/Login"></script>
<div id="peopleSearchForm"></div>
<div id="peopleSearchResults"></div>
</body>
</html>

The Explanation

Lines 4-9 load the LinkedIn JavaScript API framework. The only required option is api_key, which is the API key you received when you created an application. The other two parameters are optional. They specify a callback function and automatically trigger authentication of viewers who have already granted your application access.

Line 11 begins the JavaScript code to wire up the page to the JavaScript API. There are four functions used to make it work.

The onLinkedInLoad() function is triggered by the JavaScript framework after it has completed initialization. Inside, you define a listener for an authentication (auth) event. This means the viewer has signed-in. This can occur because the framework detected a previous grant, or from an explicit sign-in. Line 83 contains a script tag to render a Sign-In button for you that handles all the authentication seamless.

Once authorization occurs, onLinkedInAuth() kicks in, starting on Line 17. When the page first loads, all an unauth'd viewer sees is a button to Sign-In to LinkedIn. This function adds a form asking them to Find People on LinkedIn and includes a

with a search box. The form's action passes the value from the text input to PeopleSearch().

Here's where the API request to LinkedIn takes place. The PeopleSearch() function calls the LinkedIn JavaScript API function IN.API.PeopleSearch() with a number of chained parameters. This function calls the LinkedIn People Search engine to look for members matching the parameters and returns the fields requested. If you have questions about the search engine input fields and output schema, check out its REST API documentation.

On Lines 33-38, you see all the inputs sent in and where the output is directed. The fields() method takes a list of fields that you're asking the API to return. Here you request first name, last name, distance, and Profile URL. Values to this method are camel case.

The params() method specifies the search criteria. The keyword from the form is passed in, along with two hardcoded values to ask for only 10 results sorted by distance away from the viewer. You can't tell from this example, but these values are hyphenated. Don't use camel case here.

The final two methods, result() and error() take callback function. They're triggered on success and failure, respectively. Here we call displayPeopleSearch() on a good request and do nothing on failure.

Only the result() method is required for any JavaScript API call. Everything else is optional. Defaults will be used by the framework instead.

With Line 41 comes the code where the output is displayed to the viewer. The displayPeopleSearch() callback function accept one parameter with the request data. It grabs the peopleSearchResults div, starts parsing the results, and writes each member to a list item.

The peopleSearch.people.values array contains a collection of matching members. You iterate over them and extract the requested information. The firstName and lastName properties are standard strings. The siteStandardProfileRequest buries the actual URL inside a url property, so you need to dereference it.

Starting in Line 51 comes a switch to convert the number returned in distance to an English word. The hardest part is knowing what the values map to. These are documented in the Profile Fields Reference, but there are comments inline, too.

With all the text ready, Lines 74-75 appends a new list item with the name, URL, and connection sentence.

The