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!
Related
I am trying to block a user account with the Twitter API through Python. Here's what my method looks like:
def block_user():
payload = {"target_user_id": "amazon"}
# Get request token
request_token_url = "https://api.twitter.com/oauth/request_token"
oauth = OAuth1Session(consumer_key, client_secret=consumer_secret,)
try:
fetch_response = oauth.fetch_request_token(request_token_url)
except ValueError:
print(
"There may have been an issue with the consumer_key or consumer_secret you entered."
)
resource_owner_key = fetch_response.get("oauth_token")
resource_owner_secret = fetch_response.get("oauth_token_secret")
print("Got OAuth token: %s" % resource_owner_key)
# Get authorization
base_authorization_url = "https://api.twitter.com/oauth/authorize"
authorization_url = oauth.authorization_url(base_authorization_url)
print("Please go here and authorize: %s" % authorization_url)
verifier = input("Paste the PIN here: ")
# Get the access token
access_token_url = "https://api.twitter.com/oauth/access_token"
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
verifier=verifier,
# I tried this, it didn't work
#oauth_callback='oob',
)
oauth_tokens = oauth.fetch_access_token(access_token_url)
access_token = oauth_tokens["oauth_token"]
access_token_secret = oauth_tokens["oauth_token_secret"]
# Make the request
oauth = OAuth1Session(
consumer_key,
client_secret=consumer_secret,
resource_owner_key=access_token,
resource_owner_secret=access_token_secret,
)
# Making the request
response = oauth.post(
"https://api.twitter.com/2/users/{}/blocking".format(id), json=payload
)
if response.status_code != 200:
raise Exception(
"Request returned an error: {} {}".format(response.status_code, response.text)
)
print("Response code: {}".format(response.status_code))
# Saving the response as JSON
json_response = response.json()
print(json.dumps(json_response, indent=4, sort_keys=True))
In the terminal when I run the script, I get this:
Got OAuth token: 9SL...BGo
Please go here and authorize: https://api.twitter.com/oauth/authorize?oauth_token=9SL...BGo
Paste the PIN here:
So I go to the URL and it asks me to authorize the app. I authorize it, and then get redirected immediately to the redirect page of the Twitter API app settings (default.com in this case). I don't get shown a PIN to put into the prompt, I don't see any success message or anything, it just redirects immediately. Can't find anyone else with that issue using traditional search terms.
Anyone got any ideas?
I found the answer myself. So you need to add the following URL parameters to your auth/request_token URL. For me, that meant changing this line (the third line in my code block):
request_token_url = "https://api.twitter.com/oauth/request_token"
to this:
request_token_url = "https://api.twitter.com/oauth/request_token?oauth_callback=oob&x_auth_access_type=write"
I had tried using oauth_callback=oob in a few other places including my OAuth1Session object and on the authentication URL. Needs to be on the request_token URL.
sorry i can't comment right now so i will type this here :
i really recommend using the Twitter library :
Twitter python library
My pytumblr version is 0.0.6, the one in the repo. Imports work properly. I'm using Python 2.7.8, with that said:
I have logged into my account.
I went to https://api.tumblr.com/console
I have put the consumer_key & consumer_secret keys
I have allowed it and
I have copied this code:
client = pytumblr.TumblrRestClient(
'my_consumer_key',
'my_consumer_secret',
'my_access_token',
'my_token_secret'
)
Then I have tried to create a text post. The next code is taken from the pytumblr github readme page. I've just added the response code.
response = client.create_text("codingjester", state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")
print(response)
But, this is what it say...
{u'meta': {u'status': 401, u'msg': u'Not Authorized'}, u'response': []}
¿ Why ?
Ps: Doing other oauth call like client.followers("blogname") works, but not when trying to post as I have said above.
EDIT: I tried to use three legged oauth authorization. With Selenium to automate the http request to get the oauth_verifier and then get the oauth_token and oauth_token_secret with this and the consumer_key and consumer_secret should be enough to use pytumblr... But I'm still getting the 401 Not Authorized response :( Oh, and I'm using "http://localhost/" as my callback_url, otherwise or with just "/" the autorization url doesn't return the oauth_verifier key
Here's the code:
import urlparse
import oauth2 as oauth
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
consumer_key = 'my_consumer_key'
consumer_secret = 'my_consumer_secret'
callback_url = 'http://localhost/'
request_token_url = 'http://www.tumblr.com/oauth/request_token'
access_token_url = 'http://www.tumblr.com/oauth/access_token'
authorize_url = 'http://www.tumblr.com/oauth/authorize'
consumer = oauth.Consumer(consumer_key, consumer_secret)
client = oauth.Client(consumer)
# Step 1: Get a request token. This is a temporary token that is used for
# having the user authorize an access token and to sign the request to obtain
# said access token.
resp, content = client.request(request_token_url, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
request_token = dict(urlparse.parse_qsl(content))
print "Request Token:"
print " - oauth_token = %s" % request_token['oauth_token']
print " - oauth_token_secret = %s" % request_token['oauth_token_secret']
print
# Step 2: HERE's WHAT I HAVE MODIFIED. I USE SELENIUM TO GET THE oauth_verifier
driver = webdriver.Firefox()
driver.get("https://www.tumblr.com/login")
wait1 = WebDriverWait(driver, 10)
u = wait1.until(EC.element_to_be_clickable((By.XPATH, "//input[#type='email']")))
driver.execute_script("arguments[0].value = 'my_username';", u)
p = driver.find_element_by_xpath("//input[#type='password']")
driver.execute_script("arguments[0].value = 'my_password';", p)
p.submit()
time.sleep(10)
driver.get("http://www.tumblr.com/oauth/authorize?oauth_token=" + request_token['oauth_token'])
time.sleep(5)
allow = driver.find_element_by_xpath("(//button)[2]")
driver.execute_script("arguments[0].click();", allow)
time.sleep(5)
a = driver.current_url
a = a.replace(callback_url + '?oauth_token=' + request_token['oauth_token'] + "&oauth_verifier=", "")
a = a.replace("#_=_", "")
print(a)
oauth_verifier = a
# Step 3: Once the consumer has redirected the user back to the oauth_callback
# URL you can request the access token the user has approved. You use the
# request token to sign this request. After this is done you throw away the
# request token and use the access token returned. You should store this
# access token somewhere safe, like a database, for future use.
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")
access_token = dict(urlparse.parse_qsl(content))
print "Access Token:"
print " - oauth_token = %s" % access_token['oauth_token']
print " - oauth_token_secret = %s" % access_token['oauth_token_secret']
print
print "You may now access protected resources using the access tokens above."
print
client = pytumblr.TumblrRestClient(
consumer_key,
consumer_secret,
access_token['oauth_token'],
access_token['oauth_token_secret'],
)
response = client.create_text("codingjester", state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")
print(response)
Maybe would be better to learn how to issue a pure oauth requests using the endpoint... and desist using the pytumblr wrapper... I'm starting to think that it sucks and that is really unmaintained library.
response = client.create_text("**codingjester**", state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")
But is "codingjester" actually your blog? otherwise it is right to get not authorized.
The first argument for client.create_text or client.create_photo needs to be the blogname of your blog, so for a photo, do:
client.create_photo('yourblogname', 'stringlinktolocalfileorURL')
That works for me.
I had the same issue. I fixed by hard-coding the oauth_token and oauth_token_secret (obtained from https://api.tumblr.com/console/calls/user/info) rather than using the request_token calls. Perhaps whatever is going wrong with those calls can be fixed but in the meantime hard-coding works as a workaround.
Taken from: http://yuluer.com/page/bgfbhjgf-python-tumblr-api-cannot-log-in-to-my-own-tumblr-to-create-posts.shtml
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'}
)
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.')
I have been working with the protected authentication of the netflix api and the python oauth2 library. I have no problem making signed requests, however, to allow users to sign in using their netflix accounts, I am running into a few problems when I try to get the access_token, I know there cases in which OAuth doesn't return a verifier, even if its supposed to, however after being redirected from the authorization page of netflix I get something like this: http://127.0.0.1:5000/authorized_user?oauth_token=some_token&oauth_verifier= with the verifier empty.
I am new to the library and quite didn't understand what to do when the verfier is not present. Since, I successfully redirect the user to the netflix sign in/authorization page. I assume my error comes from this step which I don't fully understand. Below is a simplified (shell) version of what I am attempting. I would appreciate a push in the right direction, I read netflix documentation and read the library documentation but couldn't figure out what to do.
# Get request token (temporary)
resp, content = client.request(REQUEST_TOKEN_URL, "GET")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
request_token = dict(parse_qsl(content))
print 'Request token'
print ' --> oauth_token = %s' % request_token['oauth_token']
print ' --> oauth_token_secret = %s' % request_token['oauth_token_secret']
print ' --> login_url = %s' % request_token['login_url']
# Redirect to netflix for user authorization
print 'Go to the following link: '
login_url = request_token['login_url']
access_token_url = '%s&oauth_consumer_key=%s' % (login_url, CONSUMER_KEY)
accepted = 'n'
while accepted.lower() == 'n':
accepted = raw_input('Have you authorized me? (y/n) ')
resp, content = client.request(access_token_url, "POST")
token = oauth.Token(request_token['oauth_token'],
request_token['oauth_token_secret'])
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "POST")
access_token = dict(parse_qsl(content))
print "Access Token:"
print " - oauth_token = %s" % access_token['oauth_token']
print " - oauth_token_secret = %s" % access_token['oauth_token_secret']
So it sounds like you're attempting to use python-oauth2. Unfortunately this library is widely considered abandoned-ware. I would highly recommend using a maintained library. For that I can recommend rauth. I'm the maintainer of rauth, for what it's worth.
Now unfortunately Netflix is not accepting new applications to their OAuth infrastructure. However I did write up an example for you that could try if you're willing to give rauth a shot. I can't promise it won't work without some tweaks, but here it is:
from rauth import OAuth1Service
import re
import webbrowser
request_token_url = 'http://api-public.netflix.com/oauth/request_token'
access_token_url = 'http://api-public.netflix.com/oauth/access_token'
authorize_url = 'https://api-user.netflix.com/oauth/login'
base_url = 'http://api-public.netflix.com/'
netflix = OAuth1Service(consumer_key='123',
consumer_secret='456',
request_token_url=request_token_url,
authorize_url=authorize_url,
access_token_url=access_token_url,
base_url=base_url)
request_token, request_token_secret = netflix.get_request_token()
oauth_callback = 'http://example.com/oauth/authorized'
params = {'oauth_callback': oauth_callback, 'application_name': 'your_app'}
authed_url = netflix.get_authorize_url(request_token, **params)
print 'Visit this URL in your browser: ' + authed_url
webbrowser.open(authed_url)
url_with_token = raw_input('Copy URL from your browser\'s address bar: ')
request_token = re.search('\?oauth_token=([^&]*)', url_with_token).group(1)
s = netflix.get_auth_session(request_token, request_token_secret)
r = s.get('users/current')
print r.content
A couple of things to note here: Netflix makes no mention of the verifier in their documentation. So I'm guessing that's why you see none. Secondly they are returning an "authorized" request token in place. Basically this token replaces the verifier pin in their flow.
Hope this helps!