python requests not recognizing params - python

I am requesting to mindbodyapi to get token with the following code using requests library
def get_staff_token(request):
URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue"
payload = {
'Api-Key': API_KEY,
'SiteId': "1111111",
'Username': 'user#xyz.com',
'Password': 'xxxxxxxx',
}
r = requests.post(url=URL, params=payload)
print(r.text)
return HttpResponse('Done')
gives a response as follows
{"Error":{"Message":"Missing API key","Code":"DeniedAccess"}}
But if I request the following way it works, anybody could tell me, what I am doing wrong on the above code.
conn = http.client.HTTPSConnection("api.mindbodyonline.com")
payload = "{\r\n\t\"Username\": \"username\",\r\n\t\"Password\": \"xxxxx\"\r\n}"
headers = {
'Content-Type': "application/json",
'Api-Key': API_KEY,
'SiteId': site_id,
}
conn.request("POST", "/public/v6/usertoken/issue", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

In the second one, you are passing the API Key in headers and the credentials in the body of the request. In the first, you are sending both the API Key and credentials together in the query string, not the request body. Refer to requests.request() docs
Just use two dictionaries like in your second code and the correct keywords, I think it should work:
def get_staff_token(request):
URL = "https://api.mindbodyonline.com/public/v6/usertoken/issue"
payload = {
'Username': 'user#xyz.com',
'Password': 'xxxxxxxx',
}
headers = {
'Content-Type': "application/json",
'Api-Key': API_KEY,
'SiteId': "1111111",
}
r = requests.post(url=URL, data=payload, headers=headers)
print(r.text)
return HttpResponse('Done')

Related

Pinterst api: not able to get access token - Stuck in Oauth flow

Using v5 of the pinterest api and stuck on the authentication flow: https://developers.pinterest.com/docs/getting-started/authentication/
Completed the first step and got the access code.
However, I get the below error when I try to use this code to get the access token.
{"code":1,"message":"Missing request body"}
Here is my code:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
params = {
'grant_type':'authorization_code',
'code': code,
'redirect_url':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, params=params)
print(r.json())
Below is the correct way to get the access token:
client_id= 'my_client_id'
client_secret = 'my_client_secret'
data_string = f'{client_id}:{client_secret}'
token = base64.b64encode(data_string.encode())
headers = {
'Authorization': 'Basic ' + token.decode('utf-8'),
'Content-Type': 'application/x-www-form-urlencoded',
}
url = "https://api.pinterest.com/v5/oauth/token"
code = "my_code_that_i_got_in_the_first_step"
data= {
'grant_type':'authorization_code',
'code': code,
'redirect_uri':'https://my_redirect_uri'
}
r = requests.post(url, headers=headers, data=data)
print(r.json())
In my question, I had mistyped redirect_uri as redirect_url. Also, when sending a POST, you should use data instead of params. See the comment by Amos Baker.

How to add pagination to request in Python?

I want to have a python request and add pagination, but for some reason it does not work,
this is my request. Does someone know how to add 'paging': '{"page":0,"size":100}' corretly? The following isn't working?
url = self.get_url_for_endpoint(Constants.PATH_STATISTICS_CUSTOMERS)
payload = {}
params = {
'paging': '{"page":0,"size":100}'
}
headers = {
'Authorization': 'Bearer ' + self.access_token,
'Cookie': 'JSESSIONID=AB52DV8260C*****************',
'Content-Type': 'application/json',
}
r = requests.request("GET", url, headers=headers, data=payload, params=params)
This is working though via postman:
url + ?paging=%7B%22page%22:0,%22size%22:400%7D
So the endpoint has pagination!
I wouldn't recommend using an object as your paging value in the params, instead break down your page and size into individual parameters, like ?page=0&size=100.
But if you want to use an object, your params should be like this:
params = {
"paging": {"page":0,"size":100}
}

converting python oauth to postman request

I am trying to convert successful python (flask) OAuth 2.0 authentication / api request into Postman.
My current process is:
From the front end, I hit an /auth endpoint in python using fetch:
fetch("/auth")
.then(function (response) {
return response.json();
})
.then(function (json) {
const code = json.code;
window.location = `[hostname.com]/auth/authorize?request_token=${code}&redirect_uri=http://[hostname]/menu`;
});
The backend flask auth endpoint looks like this:
url = 'https://[hostname].com/v3/oauth/request'
headers = CaseInsensitiveDict()
headers['Host'] = '[hostname].com'
headers['Content-Type'] = 'application/json'
headers['X-Accept'] = 'application/json'
data = json.dumps({'consumer_key': 'XXXX', 'redirect_uri':'[hostname]/success'})
resp = requests.post(url, headers=headers, data=data)
json_resp = json.loads(resp.content)
auth_code = json_resp['code']
auth_resp = {'code': auth_code}
return jsonify(auth_resp)
The access endpoint takes that auth code to get the token
cur_auth = session.get('auth_code',None)
url = 'https://[hostname.com]/v3/oauth/authorize'
headers = CaseInsensitiveDict()
headers['Host'] = '[hostname].com'
headers['Content-Type'] = 'application/json; charset=UTF-8'
headers['X-Accept'] = 'application/json'
data = json.dumps({'consumer_key': 'XXXX', 'code': cur_auth})
resp = requests.post(url, headers=headers, data=data)
json_resp = resp.json()
access_token = json_resp['access_token']
username = json_resp['username']
session['access_token']=access_token
session['username']=username
access_resp = {'access': access_token, 'user': username}
return jsonify(access_resp)
But when I try to translate this into a postman request, I can't really understand where some of the things like the consumer_key request_token and code get defined.
I'm currently getting a 400 bad request with this setup:
where the consumer_key is in Postman's client secret field, and where
https://[hostname].com/v3/oauth/request is in Postman's auth field and
https://getpocket.com/v3/oauth/authorize is in Postman's access token url field.

Retrieving single json object from python requests results as list

I'm trying to retrieve only requestId object from json results after querying my API.
my code:
def findRequests(group, token, user):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'requests/find'
body = {'groupIDs': [group], "createdDate": {'operator': "BETWEEN", 'fromDate': "01-APR-2020 00:00:00", 'toDate': "21-APR-2020 00:00:00"}}
r = requests.post(url = host + endpoint, headers = headers, json=body, verify=False)
data = json.loads(r.text)
print (data[0]['requestId'])
json data:
[{'requestId': 2567887, 'requestName': 'Here is a sample name', 'requestSubject': 'sample subject', 'createdDate': '01-APR-2020 14:06:03'}, {'requestId': 7665432,...}]
then I would like to save all the values for requestId object found in results as a list:
myRequestsList = print(findRequests(group, token, user))
However the above will only return a single requestId and not all of the ones that were returned in data variable in def findRequests(group, token, user). What am I doing wrong?
Output:
2567887
None
Desired output:
2567887,
7665432
Could someone help me with this? thanks in advance!
First, you should modify your func:
Then, assign the variable to the func, not the print:
myRequestsList = list(findRequests(group, token, user)))
(!) However, I assume that group,token, user are replaced by other variables.
And finally, to get the output:
for req in myRequestsList:
print(req)
Later edit:
def findRequests(group, token, user):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'requests/find'
body = {'groupIDs': [group], "createdDate": {'operator': "BETWEEN", 'fromDate': "01-APR-2020 00:00:00", 'toDate': "21-APR-2020 00:00:00"}}
r = requests.post(url = host + endpoint, headers = headers, json=body, verify=False)
data = json.loads(r.text)
final_list = []
for each_req in data:
final_list.append(each_req['requestId'])
return final_list
myRequestsList = findRequests(group, token, user)
for each in myRequestsList:
print(each)

Google calendar- get modified events with nextSyncToken via API rest

Can anyone please tell me how to write a cURL to get events (only modified) list with nextSyncToken?
This is my code that's not working:
def get_headers():
headers = {
#'Content-Type': "application/json",
'Authorization': access_token_json
}
return headers
def get_nexttokensync_list_event():
url_get_list_event = "https://www.googleapis.com/calendar/v3/calendars/id#gmail.com/events"
querystring = {"nextSyncToken": "CMCEh************jd4CGAU="}
response = requests.request("GET", url_get_list_event, headers=headers, params=querystring)
json_event_list_formatted = response.text
print(json_event_list_formatted)
Yes, i've done it!
Here is my code:
import requests
url = "https://www.googleapis.com/calendar/v3/calendars/here_calendar_id/events"
querystring = {"syncToken":"here_token"}
headers = {
'Content-Type': "application/json",
}
response = requests.request("GET", url, headers=headers, params=querystring)
print(response.text)

Categories

Resources