LinkedIn API Python Key Error 2.7
Question: This code is available online to run a map of your connections in linkedin
This uses linkedin api. I'm able to connect fine and everything runs okay till
the last script of actually writing the data to a csv.

Whenever I run the code

    
    
    import oauth2 as oauth
    import urlparse
    import simplejson
    import codecs
    
    CONSUMER_KEY = "xxx"
    CONSUMER_SECRET = "xxx"
    OAUTH_TOKEN = "xxx"
    OAUTH_TOKEN_SECRET = "xxx"
    
    OUTPUT = "linked.csv"
    
    def linkedin_connections():
    
        # Use your credentials to build the oauth client
    consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
    token = oauth.Token(key=OAUTH_TOKEN, secret=OAUTH_TOKEN_SECRET)
    client = oauth.Client(consumer, token)
    
    # Fetch first degree connections
    resp, content = client.request('http://api.linkedin.com/v1/people/~/connections?format=json')
    results = simplejson.loads(content)    
    
    # File that will store the results
    output = codecs.open(OUTPUT, 'w', 'utf-8')
    
    # Loop thru the 1st degree connection and see how they connect to each other
    for result in results["values"]:
        con = "%s %s" % (result["firstName"].replace(",", " "),    result["lastName"].replace(",", " "))
        print >>output, "%s,%s" % ("John Henry",  con)
    
    # This is the trick, use the search API to get related connections
        u = "https://api.linkedin.com/v1/people/%s:(relation-to-viewer:(related-connections))?format=json" % result["id"]
        resp, content = client.request(u)
        rels = simplejson.loads(content)
    try:
    for rel in rels['relationToViewer']['relatedConnections']['values']:
        sec = "%s %s" % (rel["firstName"].replace(",", " "), rel["lastName"].replace(",", " "))
        print >>output, "%s,%s" % (con, sec)
    except:
        pass
    
    if __name__ == '__main__':
        linkedin_connections()     
    
    for result in results["values"]:
        KeyError: 'values'
    

When I run this I get an error message:

    
    
    Traceback (most recent call last):
    
    File "linkedin-2-query.py", line 51, in <module>
    linkedin_connections()
    File "linkedin-2-query.py", line 35, in linkedin_connections
    for result in results["values"]:
    KeyError: 'values'
    

Any suggestions or help would be greatly appreciated!


Answer: I encountered the same issue working through the post [Visualizing your
LinkedIn graph using Gephi – Part 1](http://dataiku.com/visualizing-your-
linkedin-graph-using-gephi-part-1/#comment-723).

> Python raises a KeyError whenever a dict() object is requested (using the
> format a = adict[key]) and the key is not in the dictionary. [KeyError -
> Python Wiki](http://wiki.python.org/moin/KeyError)

After searching a bit and adding some print statements, I realize that my
OAuth session has expired, so the OAuth token in my
[`linkedin-2-query.py`](https://gist.github.com/micahstubbs/5744765) script
was is longer valid.

Since the OAuth token is invalid, the LinkedIn API does not return a
dictionary with the key `"values"` like the script expects. Instead, the API
returns the string `'N'`. Python tries to find the dict key `"values"`in the
string `'N'`, fails, and generates the `KeyError: 'values'`.

So a new, valid OAuth token & secret should get the API to return a dict
containing connection data.

* * *

I run the [`linkedin-1-oauth.py`](https://gist.github.com/micahstubbs/5744717)
script again, and then visit the LinkedIn [Application details
page](https://www.linkedin.com/secure/developer) to find my new OAuth token.
(The screenshot omits the values for my app. You should see alphanumeric
values for each Key, Token, & Secret.)

![enter image description here](http://i.stack.imgur.com/o4SBc.png)

**...**

![enter image description here](http://i.stack.imgur.com/jDCky.png)

I then update my
[`linkedin-2-query.py`](https://gist.github.com/micahstubbs/5744765) script
with the new **OAuth User Token** and **OAuth User Secret**

    
    
    OAUTH_TOKEN = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # your updated OAuth User Token
    OAUTH_TOKEN_SECRET = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # your updated OAuth User Secret
    

After updating the OAuth token & secret, I immediately run my
[`linkedin-2-query.py`](https://gist.github.com/micahstubbs/5744765) script.
Hooray, it runs without errors and retrieves my connection data from the API.

