How to use linkedin API with python - python

I tried so many methods, but none seem to work. Help me make a connection with linkedin using python. I have all the tokens. I have python 2.7.5. Please post a sample of basic code that establishes a connection and gets a user's name.
Below, I have done character for character like the example said, but it doesn't work.
https://github.com/ozgur/python-linkedin <---This is where I got the api and I copied it exactly. See below:
CONSUMER_KEY = '9puxXXXXXXXX' # This is api_key
CONSUMER_SECRET = 'brtXoXEXXXXXXXX' # This is secret_key
USER_TOKEN = '27138ae8-XXXXXXXXXXXXXXXXXXXXXXXXXXX' # This is oauth_token
USER_SECRET = 'ca103e23XXXXXXXXXXXXXXXXXXXXXXXXXXX' # This is oauth_secret
from linkedin import linkedin
# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
# Use the app....
application.get_profile()
I get this error:
Traceback (most recent call last):
File "C:/Documents and Settings/visolank/Desktop/Python/programs/linkedinapi.py", line 8, in <module>
from linkedin import linkedin
File "C:/Documents and Settings/visolank/Desktop/Python/programs\linkedin\linkedin.py", line 2, in <module>
from requests_oauthlib import OAuth1
File "C:\Python27\lib\site-packages\requests_oauthlib\__init__.py", line 1, in <module>
from .core import OAuth1
File "C:\Python27\lib\site-packages\requests_oauthlib\core.py", line 4, in <module>
from oauthlib.oauth1 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)
File "C:\Python27\lib\site-packages\requests_oauthlib\oauthlib\oauth1\__init__.py", line 12, in <module>
from .rfc5849 import Client
File "C:\Python27\lib\site-packages\requests_oauthlib\oauthlib\oauth1\rfc5849\__init__.py", line 26, in <module>
from oauthlib.common import Request, urlencode, generate_nonce
ImportError: No module named oauthlib.common

Got it. For future reference you need to download the oauthlib from here https://github.com/idan/oauthlib
here is the full functional code:
CONSUMER_KEY = '9pux1XcwXXXXXXXXXX' # This is api_key
CONSUMER_SECRET = 'brtXoXEXXXXXXXXXXXXX' # This is secret_key
USER_TOKEN = '27138ae8-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXb' # This is oauth_token
USER_SECRET = 'ca103e23-XXXXXXXXXXXXXXXXXXXXXXXX7bba512625e' # This is oauth_secret
RETURN_URL = 'http://localhost:8000'
from linkedin import linkedin
from oauthlib import *
# Define CONSUMER_KEY, CONSUMER_SECRET,
# USER_TOKEN, and USER_SECRET from the credentials
# provided in your LinkedIn application
# Instantiate the developer authentication class
authentication = linkedin.LinkedInDeveloperAuthentication(CONSUMER_KEY, CONSUMER_SECRET,
USER_TOKEN, USER_SECRET,
RETURN_URL, linkedin.PERMISSIONS.enums.values())
# Pass it in to the app...
application = linkedin.LinkedInApplication(authentication)
# Use the app....
g = application.get_profile()
print g

You can get USER_TOKEN & USER_SECRET in such way (if you have CONSUMER_KEY & CONSUMER_SECRET):
import oauth2 as oauth
import urllib
consumer_key = '' #from Linkedin site
consumer_secret = '' #from Linkedin site
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken'
resp, content = client.request(request_token_url, "POST")
if resp['status'] != '200' :
raise Exception('Invalid response %s.' % resp['status'])
content_utf8 = str(content,'utf-8')
request_token = dict(urllib.parse.parse_qsl(content_utf8))
authorize_url = request_token['xoauth_request_auth_url']
print('Go to the following link in your browser:', "\n")
print(authorize_url + '?oauth_token=' + request_token['oauth_token'])
accepted='n'
while accepted.lower() == 'n' :
accepted = input('Have you authorized me? (y/n)')
oauth_verifier = input('What is the PIN?')
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, 'POST')
content8 = str(content,'utf-8')
access_token = dict(urllib.parse.parse_qsl(content8))
print('Access Token:', "\n")
print('- oauth_token = ' + access_token['oauth_token']+'\n')
print('- oauth_token_secret = ' + access_token['oauth_token_secret'])
print('You may now access protected resources using the access tokens above.')

Related

JIRA request token fetch error using Python

I am trying to configure and use OAuth to authenticate and request token using Python. I have generated jira private key.
import requests
from oauthlib.oauth1 import SIGNATURE_RSA,SIGNATURE_HMAC
from requests_oauthlib import OAuth1Session
from jira.client import JIRA
import time
def read(file_path):
with open(file_path) as f:
return f.read()
CONSUMER_KEY = "OauthKey"
RSA_KEY = read("jira_privatekey.pem")
JIRA_SERVER = "http://rhtstngjira012:8080"
REQUEST_TOKEN_URL = JIRA_SERVER + "/plugins/servlet/oauth/request-token"
AUTHORIZE_URL = JIRA_SERVER + "/plugins/servlet/oauth/authorize"
ACCESS_TOKEN_URL = JIRA_SERVER + "/plugins/servlet/oauth/access-token"
oauth = OAuth1Session(CONSUMER_KEY, signature_type="auth_header", signature_method=SIGNATURE_RSA, rsa_key=RSA_KEY)
request_token = oauth.fetch_request_token(REQUEST_TOKEN_URL)
But while requesting tokens, I am getting the following error -
Traceback (most recent call last):
File "Access_Tokens_JIRA.py", line 23, in <module>
request_token = oauth.fetch_request_token(REQUEST_TOKEN_URL)
File "/PYTHON_SCRIPTS/Environments/TESTING/lib/python3.6/site-packages/requests_oauthlib/oauth1_session.py", line 287, in fetch_request_token
token = self._fetch_token(url, **request_kwargs)
File "/PYTHON_SCRIPTS/Environments/TESTING/lib/python3.6/site-packages/requests_oauthlib/oauth1_session.py", line 369, in _fetch_token
raise TokenRequestDenied(error % (r.status_code, r.text), r)
requests_oauthlib.oauth1_session.TokenRequestDenied: Token request failed with code 401, response was 'oauth_problem=signature_invalid&oauth_signature=ABC&oauth_signature_base_string=POST%26http%253A%252F%252Frhtstngjira012%253A8080%252Fplugins%252Fservlet%252Foauth%252Frequest-token%26oauth_consumer_key%253DOauthKey%2526oauth_nonce%123%2526oauth_signature_method%253DRSA-SHA1%2526oauth_timestamp%253D1630512420%2526oauth_version%253D1.0&oauth_signature_method=RSA-SHA1'
I have installed all latest libraries and have generated keys too. Could you please advise what I can change to request tokens from JIRA?
You should create API token and encode to base64 the whole String email:your-api-token.
You have to create API token for your user as described here: https://confluence.atlassian.com/cloud/api-tokens-938839638.html.

Linkedin API Python

I'm trying to log-in to Linkedin. I created the App and extract the client_key and client_secret. Also I added http://localhost:8080/ as Redirect URLs.
I have this error:
linkedin.exceptions.LinkedInError: 410 Client Error: Gone for url: https://api.linkedin.com/v1/people/~: This resource is no longer available under v1 APIs
# pip install python-linkedin
from linkedin import linkedin
import oauth2 as oauth
import urllib
consumer_key = ''
consumer_secret = ''
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken'
resp, content = client.request(request_token_url, "POST")
if resp['status'] != '200':
raise Exception('Invalid response %s.' % resp['status'])
content_utf8 = str(content, 'utf-8')
request_token = dict(urllib.parse.parse_qsl(content_utf8))
authorize_url = request_token['xoauth_request_auth_url']
print('Go to the following link in your browser:', "\n")
print(authorize_url + '?oauth_token=' + request_token['oauth_token'])
accepted = 'n'
while accepted.lower() == 'n':
accepted = input('Have you authorized me? (y/n)')
oauth_verifier = input('What is the PIN?')
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, 'POST')
content8 = str(content, 'utf-8')
access_token = dict(urllib.parse.parse_qsl(content8))
USER_TOKEN = access_token['oauth_token']
USER_SECRET = access_token['oauth_token_secret']
RETURN_URL = 'http://localhost:8080'
authentication = linkedin.LinkedInDeveloperAuthentication(
consumer_key,
consumer_secret,
USER_TOKEN,
USER_SECRET,
RETURN_URL,
linkedin.PERMISSIONS.enums.values()
)
application = linkedin.LinkedInApplication(authentication)
application.get_profile()
The v1 APIs are no longer supported.
Applications requesting Version 1.0 APIs may experience issues as they are removing services. Hence, it is highly recommended to change it from v1 to v2.
Link : https://engineering.linkedin.com/blog/2018/12/developer-program-updates
Try updating your code with the new set of APIs (currently v2), and it will work perfectly as you're expecting.
Link : https://pypi.org/project/python-linkedin-v2/
Hope it helps!

Getting OAuth access token for LinkedIn using python-linkedin library

I'm trying to get the LinkedIn user access token using python-linkedin library with the following code. It's giving me access code but not directing to else part after getting the access_code.
from linkedin import linkedin
from lnkd.settings import LINKEDIN_CONSUMER_KEY, LINKEDIN_CONSUMER_SECRET, RETURN_URL
from django.http import HttpResponseRedirect, HttpResponse
def get_linkedin_token(request):
authentication = linkedin.LinkedInAuthentication(
LINKEDIN_CONSUMER_KEY,
LINKEDIN_CONSUMER_SECRET,
RETURN_URL,
linkedin.PERMISSIONS.enums.values()
)
access_code = request.GET.get('code')
if code is None:
application = linkedin.LinkedInApplication(authentication)
return HttpResponseRedirect(authentication.authorization_url)
else:
authentication.authorization_code = access_code
access_token = authentication.get_access_token()
return Httpresponse(access_token)
What am I doing wrong?
I know how to connect doing it step by step, I allways use the OAuth steps and it works for me, tested for XING and Linkedin:
from rauth import OAuth1Service
import webbrowser
CLIENT_ID = 'your client ID'
CLIENT_SECRET = 'your client secret'
RETURN_URL = "http://localhost:8000"
BASE_URL = 'https://api.linkedin.com'
AUTHORIZATION_URL = BASE_URL +'/uas/oauth/authenticate'
REQUEST_TOKEN_URL = BASE_URL +'/uas/oauth/requestToken'
ACCESS_TOKEN_URL = BASE_URL + '/uas/oauth/accessToken'
linkedin = OAuth1Service(
name='linkedin',
consumer_key=CLIENT_ID,
consumer_secret=CLIENT_SECRET,
request_token_url=REQUEST_TOKEN_URL,
access_token_url=ACCESS_TOKEN_URL,
authorize_url=AUTHORIZATION_URL,
base_url=BASE_URL)
token, token_secret = linkedin.get_request_token(
method='GET',
params={'oauth_callback': 'oob'})
url = linkedin.get_authorize_url(token)
webbrowser.open(url)
pin = raw_input('PIN:')
session = linkedin.get_auth_session(
token,
token_secret,
method='POST',
data={'oauth_verifier': pin})
Now, you have a variable called 'session' which allows to handle GET, POST and PUT requests. For an instance, that is for Xing, I didnĀ“t try it with Linkedin but it should be something like:
#Find all IDs from your contacts list
search = "/v1/users/me/contact_ids"
res_ids = session.get(search,params={'format':'json'})
res_ids = res_ids.json()
print res_ids
# PUT a new webpage in your profil
res = session.put(
'/v1/users/me/web_profiles/homepage',
{'url[]': 'http://stackoverflow.com/questions/25183197'}
)

how to access gmail use python?

I wanna access gmail use python and oauth2.0,so I download the oauth2.py from "http://google-mail-oauth2-tools.googlecode.com/svn/trunk/python/oauth2.py". And this is my demo:
import oauth2
import imaplib
import email
from oauth2client.client import OAuth2WebServerFlow
from launchpadlib.credentials import access_token_page
email = 'karlvorndoenitz#gmail.com'
client_id = 'client_id'
client_secret = 'client_secret'
# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://mail.google.com/'
# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
flow = OAuth2WebServerFlow(client_id, client_secret, OAUTH_SCOPE, REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
authorization_code = raw_input("Please input the code:").strip()
response = oauth2.AuthorizeTokens(client_id, client_secret, authorization_code)
access_token = response['access_token']
auth_string = oauth2.GenerateOAuth2String(email,access_token,base64_encode=True)
print auth_string
imap_conn = imaplib.IMAP4_SSL('imap.gmail.com')
imap_conn.debug = 4
imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
imap_conn.select('INBOX')
But the demo has some bugs,I don't know how to debug it.The information from console:
16:58.52 > KOMN1 AUTHENTICATE XOAUTH2
16:58.79 < +
16:58.79 write literal size 204
16:59.27 < + eyJzdGF0dXMiOiI0MDAiLCJzY2hlbWVzIjoiQmVhcmVyIiwic2NvcGUiOiJodHRwczovL21haWwuZ29vZ2xlLmNvbS8ifQ==
16:59.27 write literal size 204
16:59.27 < KOMN1 NO Invalid SASL argument. d10if1169757igr.56
16:59.27 NO response: Invalid SASL argument. d10if1169757igr.56
Traceback (most recent call last):
File "/home/karl/workspace/Gmail/download_gmail/download_gmail_api.py", line 33, in <module>
imap_conn.authenticate('XOAUTH2',lambda x:auth_string)
File "/usr/lib/python2.7/imaplib.py", line 351, in authenticate
raise self.error(dat[-1])
imaplib.error: Invalid SASL argument. d10if1169757igr.56
I need help.
The auth_string should not be base64encoded. I believe the IMAP4.authenticate encodes it for you. It worked for me anyways.
For example:
auth_string = 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)

python dropbox api error

I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.

Categories