unable to Authenticate on RESTAPI - python

I want to access Snov.io API but there is Error Unauthenticated. but I authenticated. and I can print Acces token too. am I missing anything here?
import requests
import json
def get_access_token():
params = {
'grant_type': 'client_credentials',
'client_id': '59e814b92ded8ed6b5537718495bf2a5',
'client_secret': '9cc7012893ff220c6935440b8e216ac1'
}
res = requests.post(
'https://api.snov.io/v1/oauth/access_token', data=params)
resText = res.text.encode('ascii', 'ignore')
return json.loads(resText)['access_token']
def user_lists(token):
params = {'access_token': token}
res = requests.get(
'https://api.snov.io/v1/get-user-campaigns', data=params)
return json.loads(res.text)
token = get_access_token()
resp = user_lists(token)
print(token)
print(resp)
get_access_token() is working fine . that's what I am assuming because it's return CODE 200 and access_toke also.
user_lists() return error
ERROR
<Response [401]>

Related

Python: POST request to API failed

I am trying to send a POST request to Walmart API to request reports. But it is returning me 'Report request failed.' message with json. What am I doing wrong? I don't really have that much experience with API calls in python. Here is my code.
I have a class called "Walmart" to interact with the Walmart Marketplace API. It has methods to authenticate with the API, send requests and handle responses.
class Walmart(object):
def __init__(self, client_id, client_secret):
"""To get client_id and client_secret for your Walmart Marketplace
visit: https://developer.walmart.com/#/generateKey
"""
self.client_id = client_id
self.client_secret = client_secret
self.token = None
self.token_expires_in = None
self.base_url = "https://marketplace.walmartapis.com/v3"
session = requests.Session()
session.headers.update({
"WM_SVC.NAME": "Walmart Marketplace",
"WM_QOS.CORRELATION_ID": uuid.uuid4().hex,
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
})
session.auth = HTTPBasicAuth(self.client_id, self.client_secret)
self.session = session
# Get the token required for API requests
self.authenticate()
def authenticate(self):
data = self.send_request(
"POST", "{}/token".format(self.base_url),
body={
"grant_type": "client_credentials",
},
)
self.token = data["access_token"]
self.token_expires_in = data["expires_in"]
self.session.headers["WM_SEC.ACCESS_TOKEN"] = self.token
#property
def report(self):
return Report(connection=self)
def send_request(
self, method, url, params=None, body=None, json=None,
request_headers=None
):
# A unique ID which identifies each API call and used to track
# and debug issues; use a random generated GUID for this ID
headers = {
"WM_QOS.CORRELATION_ID": uuid.uuid4().hex,
"WM_SVC.NAME": "Walmart Marketplace",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
}
if request_headers:
headers.update(request_headers)
response = None
if method == "GET":
response = self.session.get(url, params=params, headers=headers)
elif method == "PUT":
response = self.session.put(
url, params=params, headers=headers, data=body
)
elif method == "POST":
request_params = {
"params": params,
"headers": headers,
}
if json is not None:
request_params["json"] = json
else:
request_params["data"] = body
response = self.session.post(url, **request_params)
if response is not None:
try:
response.raise_for_status()
except requests.exceptions.HTTPError:
if response.status_code == 401:
raise WalmartAuthenticationError((
"Invalid client_id or client_secret. Please verify "
"your credentials from https://developer.walmart."
"com/#/generateKey"
))
elif response.status_code == 400:
data = response.json()
if "error" in data and data["error"][0]["code"] == \
"INVALID_TOKEN.GMP_GATEWAY_API":
# Refresh the token as the current token has expired
self.authenticate()
return self.send_request(
method, url, params, body, request_headers
)
raise
try:
return response.json()
except ValueError:
# In case of reports, there is no JSON response, so return the
# content instead which contains the actual report
return response.content
And here goes authentication and the request itself. I think I am doing it wrong with the send_request method, should I do it in a different way?
api_key = '<key>'
api_secret='<secret>'
wm = Walmart(api_key, api_secret)
wm.authenticate()
url = "https://marketplace.walmartapis.com/v3/reports/reportRequests"
headers = {
"WM_QOS.CORRELATION_ID": uuid.uuid4().hex,
"WM_SVC.NAME": "Walmart Marketplace",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
}
data= {
"reportType": "ITEM_PERFORMANCE",
"reportVersion": "v1",
}
method="POST"
response_dict = wm.send_request(method, url, request_headers=headers, params=data)
if 'status_code' in response_dict and response_dict['status_code'] == 200:
response_json = response_dict.get('json')
request_id = response_json.get('requestId')
print(f'Report request submitted. Request ID: {request_id}')
else:
print('Report request failed.')
if 'json' in response_dict:
print(response_dict['json'])
else:
print(response_dict)
The response that I got was in the following form.
Report request failed.
{'requestId': '46a864e8-80e8-4019-86f0-d7a1575349a4', 'requestStatus': 'RECEIVED', 'requestSubmissionDate': '2023-02-15T18:55:03Z', 'reportType': 'ITEM_PERFORMANCE', 'reportVersion': 'v1'}
Any help is appreciated
You can try to print the response to see his contents, and there may be some additional info that will help you to fix your code. Also, you can try to debug your code line by line using this https://pypi.org/project/ipdb/
The response you get seems to be a successful response, as the property requestStatus is RECEIVED, and not ERROR (which is a possible value according to the API docs you linked).
So, the issue is probably with your response checks.
Based on your checks for response:
if 'status_code' in response_dict and response_dict['status_code'] == 200:
response_json = response_dict.get('json')
request_id = response_json.get('requestId')
print(f'Report request submitted. Request ID: {request_id}')
else:
print('Report request failed.')
if 'json' in response_dict:
print(response_dict['json'])
else:
print(response_dict)
either 'status_code' in response_dict or response_dict['status_code'] == 200 is false, what makes the else block to be executed. I recommend you to print(response_dict) before the if-else block, to see the whole content and see which of those 2 conditions is false and handle it accordingly.
I think that the issue is that the object you get from wm.send_request() does not contain status_code, since you get the content of the response (when you return response.json()) and not the session.Response object from the requests lib (see the docs).

Does Robinhood still support its API?

Does Robinhood still support its API. I keep getting a login failed error. Here's what I tried:
import requests
def login():
u = "myusername"
p = "mypassword"
url = "https://api.robinhood.com/api-token-auth/"
data = {"username": u, "password": p}
r = requests.post(url, json=data)
return r.text
print login()
I also unsuccessfully tried most of the "Python API Wrappers" on Github.
Give this a try:
import requests
def login():
username = 'username'
password = 'password'
header = {"Accept": "application/json"}
data = {"client_id": "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS",
"expires_in": 86400,
"grant_type": "password",
"password": "pword",
"scope": "internal",
"username": "uname"}
url = "https://api.robinhood.com/oauth2/token/"
r = requests.post(url, data=data, headers=header)
return r.text
print(login())

Getting eBay Access Token (Exchanging auth token) with python requests

I'm trying to use this guide to get access token.
Here is my main file:
import requests
from utils import make_basic_auth_header, conf
code = '<Auth code here>'
url = "%s/identity/v1/oauth2/token" % conf('EBAY_API_PREFIX')
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': make_basic_auth_header()
}
data = {
'grant_type': 'authorization_code',
# 'grant_type': 'refresh_token',
'state': None,
'code': code,
'redirect_uri': conf('EBAY_RUNAME')
}
r = requests.post(
url,
data=data,
headers=headers,
)
Here's the make_basic_auth_header() function:
def make_basic_auth_header():
auth_header_payload = '%s:%s' % (conf('EBAY_APP_ID'), conf('EBAY_CERT_ID'))
auth_header_base64 = base64.b64encode(auth_header_payload)
auth_header = 'Basic %s' % auth_header_base64
return auth_header
But all I get in r.json() is:
{u'error_description': u'request is missing a required parameter or malformed.', u'error': u'invalid_request'}
I'm frustrated - what am I doing wrong?
sorry, I was stupid enough and I didn't see the tickbox on ebay.

Authenticating Yelp Fusion API with Python requests

According to Yelp docs: "To authenticate API calls with the access token, set the Authorization HTTP header value as Bearer access_token."
https://www.yelp.com/developers/documentation/v3/get_started
I have gotten a Yelp API access token using requests, but cannot authenticate:
>>> data = {"grant_type": "client_credentials", "client_id": "foo", "client_secret": "bar"}
>>> r = requests.post("https://api.yelp.com/oauth2/token", data=data)
>>> r
<Response [200]>
>>> r.text
'{"expires_in": 15550795, "token_type": "Bearer", "access_token": "foobar"}'
>>> params = json.loads(r.text)
>>> url = "https://api.yelp.com/v3/autocomplete?text=del&latitude=37.786882&longitude=-122.399972&"
>>> test = requests.get(url, params=params)
>>> test.text
'{"error": {"description": "An access token must be supplied in order to use this endpoint.", "code": "TOKEN_MISSING"}}'
You should pass only access token , not the entire response. Please see below code. Basicaly you can start from the middle, as you already got access token, but i would reccomend to rewrite your entire code for better readability.
import requests
app_id = 'client_id'
app_secret = 'client_secret'
data = {'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': app_secret}
token = requests.post('https://api.yelp.com/oauth2/token', data=data)
access_token = token.json()['access_token']
url = 'https://api.yelp.com/v3/businesses/search'
headers = {'Authorization': 'bearer %s' % access_token}
params = {'location': 'San Bruno',
'term': 'Japanese Restaurant',
'pricing_filter': '1, 2',
'sort_by': 'rating'
}
resp = requests.get(url=url, params=params, headers=headers)
import pprint
pprint.pprint(resp.json()['businesses'])

Dailymotion API get refresh token by request.post python

I want to get refresh token from Dailymotion API by this code
def get_refresh_token(code):
platform = Platform.objects.get(name='Dailymotion')
secret_key = platform.secret_key
api_key = platform.api_key
redirect_uri = platform.callback_url
params = {
'code' : code,
'client_id' : api_key,
'client_secret' : secret_key,
'grant_type':'authorization_code',
'redirect_uri':redirect_uri
}
r = requests.post('https://api.dailymotion.com/oauth/token',data=params)
print (r.json())
print(code)
print(r.data)
refresh_token = r.json().get('refresh_token')
return refresh_token
but it's not working. the error is : {'error_description': 'Invalid authorization code.', 'error': 'invalid_grant'}
.I tried with the same code,grant_type... post from Chrome extensions and it works. What did i do wrong with python code?
def get_refresh_token(self, code):
args = {
'grant_type': 'refresh_token',
'refresh_token': code,
'client_id': DAILYMOTION_API_KEY,
'client_secret': DAILYMOTION_API_SECRET,
}
url = 'https://api.dailymotion.com/oauth/token'
data = urllib.urlencode(args)
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
html = response.read()
obj_Response = literal_eval(html)
return obj_Response
while getting AccessToken we get a parameter 'code' here we have to put that value in place of code.

Categories