I am trying to connect with Reddit API to get data for analysis, but am meeting a roadblock of not being able to retrieve the "access_token". Below is the code I have written, I really need the solution to this problem, below is the code
client_id = 'r7L-BcPLzoXkPl4*****'
secret = 'E1uNURdvTwu6kT09ertNNqo5*****'
import requests
auth = requests.auth.HTTPBasicAuth(client_id, secret)
with open('password.txt', 'r') as fp:
pwd = fp.read()
data = {'grant_type': 'password',
'username': 'josehope',
'password': pwd}
headers = {'User-Agent': 'Hitan/0.0.1'}
res = requests.post('https://www.reddit.com/api/v1/access_token',
auth=auth, data=data, headers=headers)
res
output ---> <Response [200]>
token = res.json()["access_token"]
This is the error I get after running the above code
KeyError Traceback (most recent call last)
<ipython-input-18-e2a3bbd5aa7e> in <module>
----> 1 token = res.json()["access_token"]
KeyError: 'access_token'
Related
I'm getting the following error:
Traceback (most recent call last):
File "authenticate-smartling.py", line 20, in
api_response.json()['response']['data']['accessToken']
KeyError: 'data'
import sys
import os
import requests
import json
# Read authentication credentials from environment
user_id = os.environ.get('DEV_USER_IDENTIFIER')
user_secret = os.environ.get('DEV_USER_SECRET')
project_id = os.environ.get('DEV_PROJECT_ID')
# Authenticate
api_url = 'https://api.smartling.com/auth-api/v2/authenticate'
api_parameters = {
'userIdentifier': user_id,
'userSecret': user_secret
}
api_response = requests.post(api_url, json = api_parameters)
# Store access token for use in subsequent API calls
api_response.json()['response']['data']['accessToken']
So far this is my code
import requests, json
API_ENDPOINT = 'https://discord.com/api/v8'
CLIENT_ID = '82'
CLIENT_SECRET = 'db'
REDIRECT_URI = 'https://google.com'
def refresh_token(refresh_token):
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'refresh_token',
'refresh_token': refresh_token
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers)
r.raise_for_status()
return r.json()
js = json.loads(open("token.json", "r").read())
for i in js:
js[i] = refresh_token(js[i]["refresh_token"])
open("token.txt", "w").write(json.dumps(js))
Every time I run it, I get a 400 error
Traceback (most recent call last):
js[i] = refresh_token(js[i]["refresh_token"])
File "c:\Users\c\Downloads\discord-oauth2-example-master\discord-oauth2-example-master\refresh.py", line 18, in refresh_token
r.raise_for_status()
File "C:\Users\c\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\requests\models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://discord.com/api/v8/oauth2/token
The code is taken directly from the discord website, so i have no idea what is going wrong. My original token grants are working but not this. Any ideas?
Thanks
I think you should provide the scope key in the data object itself. The scope is the key that you initially set when you created the access_token;
Example of scope key that is separated by whitespace:
identify email guilds
If you check the discord-oauth2 library, it requires us to pass the "scope" key into the data object
https://www.npmjs.com/package/discord-oauth2
I'm having a similar issue to this recently answered question: Authenticate & Embed Tableau Rest API using python 2.7
I'm using the same code, but getting a different error. Confirmed that I am calling the correct API version for my Tableau server version.
from urllib2 import urlopen, Request
import xml.etree.ElementTree as ET # for parsing XML responses
server_name = "http://dashboard.myorg.org"
user_name = "abc"
password = "abc"
site_url_id = ""
signin_url = "{server}/api/2.4/auth/signin".format(server=server_name)
request_xml = ET.Element('tsRequest')
credentials = ET.SubElement(request_xml, 'credentials',
name=user_name, password=password)
site_element = ET.SubElement(credentials, 'site',
contentUrl=site_url_id)
request_data = ET.tostring(request_xml)
req = Request(signin_url, data=request_data)
req = urlopen(req)
server_response = req.read
response_xml = ET.fromstring(server_response)
token = response_xml.find('.//t:credentials',
namespaces={'t': "http://tableau.com/api"}).attrib['token']
site_id = response_xml.find('.//t:site',
namespaces={'t': "http://tableau.com/api"}).attrib['id']
print('Sign in successful!')
print('/tToken: {token}'.format(token=token))
print('/tSite ID: {site_id}'.format(site_id=site_id))
headers = {'X-tableau-auth': token}
signout_url = "{server}/api/2.4/auth/signout".format(server=server_name)
req = Request(signout_url, headers=headers, data=b'')
req = urlopen(req)
print('Sign out successful!')
My error is:
Traceback (most recent call last):
File "api_call.py", line 20, in <module>
response_xml = ET.fromstring(server_response)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in XML
parser.feed(text)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1311, in feed
self._parser.Parse(data, 0)
TypeError: Parse() argument 1 must be string or read-only buffer, not instancemethod
As mentioned by #mzjn, issue is resolved by updating
server_response = req.read
to
server_response = req.read()
I wrote a small app to clean out errors in Google's Search Console (formally Google Webmaster Tools) using Oauth to connect accounts. This was running fine for the past two weeks, however, today I have noticed the the following error:
Error
Traceback (most recent call last):
File "/home/graingerkid/search_console_auto/scripts/error_count.py", line 97, in <module>
get_error_stats()
File "/home/graingerkid/search_console_auto/scripts/error_count.py", line 19, in get_error_stats
access_token = get_refreshed_tokens(refresh_token)
File "/home/graingerkid/search_console_auto/scripts/refresh_token.py", line 25, in get_refreshed_tokens
access_token = keys['access_token']
KeyError: 'access_token'
After investigating and trying to debug my code I realised I was not getting an access_token when requesting one with the refresh_token, here is the output:
Output
{
"error" : "invalid_grant"
}
Here is the function I wrote to grab the access_tokens (I've changed sensitive info):
Code
#-*- coding:utf-8 -*-
import json
import httplib2
import urllib
import pprint
def get_refreshed_tokens(refresh_token):
GOOGLE_CLIENT_ID = '98997543650-f0tn93u86vmts4j2m987654359shue6gu9g.apps.googleusercontent.com'
GOOGLE_CLIENT_SECRET = 'TFGZVLVG7VtnnrbNDTYFNBRgbfdFuENkBY'
h = httplib2.Http(".cache")
url = 'https://accounts.google.com/o/oauth2/token'
body = {
'client_secret': GOOGLE_CLIENT_SECRET,
'grant_type': 'refresh_token',
'refresh_token': refresh_token,
'client_id': GOOGLE_CLIENT_ID
}
headers = {'Content-type': 'application/x-www-form-urlencoded', 'cache-control': 'no-cache'}
response, content = h.request(url, 'POST', headers=headers, body=urllib.urlencode(body))
print content
keys = json.loads(content)
try:
access_token = keys['access_token']
except Exception as e:
pass
access_token = None
return access_token
get_refreshed_tokens('1/lWS6Fu3Hz5dMBPk9huVu6mt5yrnj5hrunhMEf7vs_UdibrBactUREZofsF9C7PrpE-j')
When requesting access to a users account I use the following:
google = oauth.remote_app('google',
base_url='https://www.google.com/accounts/',
authorize_url='https://accounts.google.com/o/oauth2/auth',
request_token_url=None,
request_token_params={'scope': 'https://www.googleapis.com/auth/webmasters https://www.googleapis.com/auth/userinfo.email',
'response_type': 'code',
'access_type':'offline',
'approval_prompt':'force'},
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_method='POST',
access_token_params={'grant_type': 'authorization_code'},
consumer_key=GOOGLE_CLIENT_ID,
consumer_secret=GOOGLE_CLIENT_SECRET)
Bearing in mind this worked fine for several weeks, I'm struggling to understand what's gone wrong, and searches on SO have not yielded answers.
Can anyone help with this?
(the accounts connected to these are mine, I have checked their access and the API access in Google API console is still intact, nothing has changed.)
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.