How to pass multiple list values as function parameters? - python

Would someone be able to help me understanding how can I pass values from multiple lists as function parameters? I'm trying to update email for each of myemailId with url that includes customerId.
my code so far:
emailId = [732853380,7331635674]
customerId = ['cust-12345-mer','cust-6789-mer']
for x, y in zip(emailId, customerId):
def update_email(emailId, token, user, notes="https://myurl.com/customer?customerId =" + customerId):
headers = { 'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'email/'
body = {'emailId': emailId, 'user': user, 'notes': notes}
requests.put(url = host + endpoint, headers = headers, json=body)
return True
but receiving this error that is corresponding to the line that starts with def update_email...:
TypeError: must be str, not list
Thanks in advance!

First of all, you shouldn't define the function for each loop iteration but once before executing the loop.
In order to pass the values, use:
emailId = [732853380, 7331635674]
customerId = ['cust-12345-mer', 'cust-6789-mer']
def update_email(emailId, token, user, customerId):
notes = "https://myurl.com/customer?customerId =" + customerId
headers = {'accept': 'application/json',
'Content-Type': 'application/json',
'token': token,
'user': user}
endpoint = 'email/'
body = {'emailId': emailId, 'user': user, 'notes': notes}
requests.put(url=host + endpoint, headers=headers, json=body)
return True
for x, y in zip(emailId, customerId):
update_email(x, token, user, y)

customerId is the list, y is the value from that list. Use
notes="https://myurl.com/customer?customerId =" + y

Related

python requests not recognizing params

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')

python set returned value from another function as a variable to use in header

Trying to get token as a variable in auth header in request in submit_documents() function it works fine if it was hard coded ; however I need to get from the return from log_in_as_taxpayer() function :
import json
class ETax_Integration(object):
"""docstring for ETax_Integration"""
def __init__(self, arg):
super(ETax_Integration, self).__init__()
self.arg = arg
def log_in_as_taxpayer(self):
client_id='###'
# print(client_id)
url = "https://url/connect/token"
client_secret='###'
# print(client_secret)
payload={'grant_type':'client_credentials','client_id':{client_id},'client_secret':{client_secret},'scope':'InvoicingAPI'}
headers = {
'Content-Type':'application/x-www-form-urlencoded'
}
response = requests.request("POST", url, headers=headers, data=payload, verify=False)
values=json.loads(response.text)
# print(values['access_token'])
# print( response.raise_for_status())
return (values['access_token'])
def submit_document(self):
token=self.log_in_as_taxpayer()
print(token)
submit_payload = json.dumps({
"documents": []
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer {token}'
}
submit_url = "https://api/link"
response = requests.request("POST", submit_url, headers=headers, data=submit_payload,verify=False)
print(response.text)
print( response.raise_for_status())
test=ETax_Integration(object)
# test.log_in_as_taxpayer()
test.submit_document()
f'Bearer {token}', notice the leading f. See here and here for more info or search python f-string with your favorite search engine ;)

How to config Bearer Token when making a GET request?

Here is the Bearer Token in Postman:
Here is what I do in code:
url_apollo = https://
params_apollo = {
'ID': 123,
}
Here is the requests that I made:
r_apollo = requests.get(url = url_apollo,
params = params_apollo,
headers={'Authorization': 'Bearer ' + 'Token'})
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1
(char 0)
You could do it like this:
url_apollo = https://
params_apollo = {'ID': 123}
headers = {'Authorization': 'Bearer YOURTOKENHERE'}
r_apollo = requests.get(url=url_apollo,
params=params_apollo,
headers=headers)
The reason why you get that error message is within the "params_apollo" variable. Since "ID" is the last line in the JSON, the comma after the value is incorrect and raises a JSONDecodeError.

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)

HTTP 400 on payout

I've been trying to build Paypal cash out system for my website, I viewed countless Paypal API pages and interpreted all the examples to Python:
import requests
import string
import random
import json
from requests.auth import HTTPBasicAuth
class makePayment(object):
def __init__(self, paypal_email, subject, amount, note, clientid, secret):
self.access_token = self.obtain_access_token(clientid, secret) # Successfully obtained access token
self.headers = {"Content-type": "application/json", "Authorization": "Bearer {0}".format(self.access_token)}
self.sender_batch_id = self.generate_sender_batch_id() # Randomly generated sender_batch_id in base36 ([A-Z] and [1-9])
self.payout_form = self.create_payout_form(self.sender_batch_id, paypal_email, subject, amount, note) # Not encoded in JSON, just normal HTML form
self.response = requests.post("https://api.sandbox.paypal.com/v1/payments/payouts",
data=self.payout_json,
headers=self.headers)
def httpResponse(self):
return self.response
#staticmethod
def obtain_access_token(clientid, secret):
headers = {"Accept": "application/json", "Accept-Language": "en_US"}
response = requests.post("https://api.sandbox.paypal.com/v1/oauth2/token",
auth=HTTPBasicAuth(clientid, secret),
data={"grant_type": "client_credentials"},
headers=headers)
return dict(response.json()).get("access_token")
#staticmethod
def generate_sender_batch_id():
base36 = str(string.digits + string.ascii_lowercase)
return "".join([random.choice(base36) for char in range(1, 9)])
#staticmethod
def create_payout_form(sender_batch_id, paypal_email, subject, amount, note):
payout_dict = {
'sender_batch_header': {
'sender_batch_id': sender_batch_id,
'email_subject': subject,
},
'items': [{
'recipient_type': 'EMAIL',
'amount': {
'value': amount,
'currency': 'USD'
},
'receiver': paypal_email,
'note': note,
'sender_item_id': '${0} item'.format(amount),
}]
}
return payout_dict
token generator, payout example
I get http error 400 (bad request), before that i've tried encoding data in json and got http error 422 (UNPROCESSABLE ENTITY), maybe json encoding was the proper method?
Take in note that sender_batch_id is randomly generated, since i don't know any other method to obtain it.
What am i doing incorrectly? Is there a possibility that i'm missing some parameters? I think there's some problem with the authentication header. Thanks!
most of the times - POST requests that are from type "application/json" need to be sent in a json format :
response = requests.post("https://api.sandbox.paypal.com/v1/oauth2/token",
auth=HTTPBasicAuth(clientid, secret),
json={"grant_type": "client_credentials"},
headers=headers)
i used
json
instead of
data
in your POST request

Categories

Resources