Search code examples
pythonpython-2.7linkedin-api

Python Linkedin, How to share content on user's wall


I am building an app which allow signing in through Linkedin. I am not using linkedin api.. So what i do is take the user through authentication process and in the end generate an authentication token (OAuth2).... Using this token i get its updates and connection details...using urlib

url = "https://api.linkedin.com/v1/people/~/network/updates?type=SHAR&count=50&start=50&oauth2_access_token=XXXX"
lp = urllib2.urlopen(url)

Now what i need to do is Share on user's wall using this token. I already have rw_nus access when i logged in the user... In the documentation it is mentioned to use link "http://api.linkedin.com/v1/people/~/shares" but i am a bit confused on how to send share content which is JSON on this url using the token... i am doing as below

share_object = {
"comment":"comment_text",
"content": {
    "title":"Test",
    "submitted_url":"http://www.test.com/",
},
"visibility": {
    "code": "anyone"
}
}
api_url = "http://api.linkedin.com/v1/people/~/shares?oauth2_access_token=XXXX";

data = json.dumps(share_object)
req = urllib2.Request(api_url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
response = f.read()
f.close()

its giving this error in the line: f = urllib2.urlopen(req)

urllib2.HTTPError: HTTP Error 401: Unauthorized

Solution

  • I wrote below function to share content on Linkedin using OAuth2

    import requests
    import json
    def make_request(method, url, token ,data=None, params=None, headers=None, timeout=60):
        headers = {'x-li-format': 'json', 'Content-Type': 'application/json'}
        params = {} 
        kw = dict(data=data, params=params, headers=headers, timeout=timeout)
        params.update({'oauth2_access_token': token})
        return requests.request(method.upper(), url, **kw)   
    
    def submit_share(comment, title, description, submitted_url, submitted_image_url, token):
        post = {
            'comment': comment,
            'content': {
            'title': title,
            'submitted-url': submitted_url,
            'submitted-image-url': submitted_image_url,
            'description': description
        },
        'visibility': {
            'code': 'anyone'
        }
        }
        url = 'https://api.linkedin.com/v1/people/~/shares'
        try:
            response = make_request('POST', url, token,data=json.dumps(post))
            response = response.json()
            return response
        except Exception:
            return False
    

    I hope it helps somebody. Regards