Create variable string for request API payload - python-3.x

I have a list of URLs that all refer to images. I want to loop through the list and call a face recognition API that accepts these URLs. To call the API, I need to provide the payload dictionary. However, the example code from the API requires the following form for the payload dictionary:
payload = "{\"url\":\"https://inferdo.com/img/face-3.jpg\",\"accuracy_boost\":3}"
The URL in this example payload dictionary would look like this in my list:
list_of_urls = ["https://inferdo.com/img/face-3.jpg", ...]
How can I insert the entries of my list into the payload dictionary with a for loop?
I tried to use a "regular" payload dictionary, but it did not work:
for url_path in list_of_urls:
payload = {'url' : url_path,'accuracy_boost':3}

I went to the API documentation and found you need to send the payload as JSON. Something like this will do the job:
import requests
import json
endpoints = {
'face': 'https://face-detection6.p.rapidapi.com/img/face'
'face_age_gender': 'https://face-detection6.p.rapidapi.com/img/face-age-gender'
}
urls = [
'https://inferdo.com/img/face-3.jpg'
]
headers = {
'x-rapidapi-host': 'face-detection6.p.rapidapi.com',
'x-rapidapi-key': 'YOUR-API-KEY',
'content-type': 'application/json',
'accept': 'application/json'
}
for url in urls:
payload = {
'url': url,
'accuracy_boost': 3
}
r = requests.post(
endpoints.get('face'), # or endpoint.get('face_age_gender')
data=json.dumps(payload),
headers=headers
)
if r.ok:
# do something with r.content or r.json()
I hope it helps.

Related

Upload attachments using clickup api

I'm trying to upload the attachments to a task on clickup.
Clickup API
Click up does provide example code the below is clickup example code
from urllib2 import Request, urlopen
values = """
attachment: raw_image_file (file)
filename: example.png (string)"""
headers = {
'Authorization': '\'access_token\'',
'Content-Type': 'multipart/form-data'
}
request = Request('https://private-anon-f799579c66-clickup20.apiary-mock.com/api/v2/task/{task_id}/attachment?custom_task_ids=&team_id=
', data=values, headers=headers)
response_body = urlopen(request).read()
print response_body
I used it as reference and used requests lib for the project
Here's the code using request lib
import requests
attachment_headers = {'Authorization': self.access_token, 'Content-Type': 'multipart/form-data'}
r = requests.post(f"https://private-anon-df9b125a00-clickup20.apiary-mock.com/api/v2/task/{task_id}/attachment",
files={"attachment": ("attachment", open("attachment.png", "rb")), "filename": "example.png"},
headers=attachment_headers)
print(r)
print(r.json())
I do get the status code as 200 and no error message but when I check on clickup task it doesn't show any attachments
Thanks for the help in advance!
You must remove the 'filename' part of your files param.
file = {"attachment": ('choose_your_name.png', open('file.png', 'rb'))}
headers = {'Authorization': config.clickup_access_token}
request = requests.post(f'https://api.clickup.com/api/v2/task/{task_id}/attachment', files=file, headers=headers)
print(request.json())

Cloud Functions with Requests return 'Could not parse JSON' error

I'm running a cloud function in python to return some data from an api. The function is not executed and I have the error {'code': 400, 'message': 'Could not parse JSON'}.
Here is my code:
import requests
import json
def my_function(request):
url = 'https://blablabla/detailed'
headers = {'X-Api-Key': 'XXXXXXXX',
'content-type': 'application/json'}
data = '{"dateRangeStart":"2020-05-10T00:00:00.000","dateRangeEnd":"2020-05-16T23:59:59.000","amountShown": "HIDE_AMOUNT","detailedFilter":{ "page":"1","pageSize":"50"}}'
#req = requests.post(url, headers=headers, json=data)
req = requests.post(url, headers=headers, data=json.dumps(data))
print(req.json())
how should I format my data variable?
Just give your dict as your json argument, you don't need to specify the content-type headers requests will do it for you.
import requests
def my_function(request):
url = 'https://blablabla/detailed'
headers = {'X-Api-Key': 'XXXXXXXX', }
data = {"dateRangeStart": "2020-05-10T00:00:00.000", "dateRangeEnd": "2020-05-16T23:59:59.000", "amountShown": "HIDE_AMOUNT", "detailedFilter": { "page": "1", "pageSize": "50", }, }
req = requests.post(url, headers=headers, json=data)
print(req.json())
If you do not set a content-type header will try to set it for you:
When using the keyword argument json: it will set it to application/json
When using the keyword argument data (and the value passed respects some criteria, most of the time you don't have to worry about it): it will set it to application/x-www-form-urlencoded
If both kwargs are present data takes priority for the header so it will be set to application/x-www-form-urlencoded
I have not detailed the behaviour when the kwarg files is used as it would be really lengthy and is out of scope here.
Here's the source code.

Google Oaut2 - Python using requests whiout Library

I am trying to authenticate not google by means of requests if I use the api but I don't know what I put in the "code" field and it will work, you can help me, or the code follows below.
import requests
url = "https://accounts.google.com/o/oauth2/token"
payload='grant_type=authorization_code&client_secret=xxxxx&client_id=xxxx&redirect_uri=https%3A%2F%2Fpushsistemas.com.br%2F&code='
headers = {
'content-type': 'application/x-www-form-urlencoded',
'Cookie': 'NID=219=RgUebbUM4k3WX0uQr8HVcIZkQ5-rMrb4HHnfnRzNTxUse776sG6-LItgXwpdv-MmaFYf3Tu4otJN-UfP70OzDtdnfam2dwAZkd6yMsr8BW_7lGE4FTaas9QkoG-hOMqXgYEHvI4YK39dWgXhWnL0E5LcsOv0DXnfjJ2kUf7VlTs; __Host-GAPS=1:jGXTa0ipDEC58oJF7pZwNBVeSXCQRw:3IRHy3GC9mAq4nqt'
}
response = requests.request("POST", url, headers=headers, data=payload)
This output
{
"error": "invalid_request",
"error_description": "Missing required parameter: code"
}
if it is not possible to do this way could you send me how to do it using the google library?

How to send POST request after form submit 302 in Django?

I have an implementation as follows:
There is a payment form wherein user fills all the details.(API1), here I'm getting an error 302:
On submit of that form one of the function in my views is called.
In the backend implementation ie. in views.py, I want to send a POST request to one of the gateways I have integrated.(API2)
But the problem is coming as the request is going as GET and hence it is dropping all the form data I'm sending along with the request.
Following is the code.
views.py -->
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
content = response.url
return_config = {
"type": "content",
"content": redirect(content)
}
return return_config
How do I send the 2nd request(API2) as POST request along with all parameters? What am I doing wrong here?
Thank you for your suggestions.
If the requests returns a 302 status, the new url is available in response.headers['Location']. You can keep following the new url, till you end up with a valid response.
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
'CustomerID': 'abc',
'TxnAmount': '1.00',
'BankID': '1',
'AdditionalInfo1': '999999999',
'AdditionalInfo2': 'test#test.test',
}
payload_encoded = urlencode(payload, quote_via=quote_plus)
response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)
while response.status_code == 302:
response = requests.post(response.headers['Location'], data=payload_encoded, headers=headers)
content = response.text
return_config = {
"type": "content",
"content": content
}
return return_config
# here you are assigning the post url to content ie. 'https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****'
content = response.url
return_config = {
"type": "content",
"content": redirect(content) # calling redirect with the response.url
}
change to:
# check status code for response
print(response)
content = response.json() # if response is of json in format
content = response.text # if response is of plain text
return_config = {
"type": "content",
"content": content
}
return return_config
request.post() returns requests.Response object. inorder to get the response data you need to access it using .text or .json() depending on the format in which the response is sent.

How to get a POST request using python on HERE route matching API?

I've tried to do a POST request using python's request library, which looked something like below:
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url,data='Datasets/rtHereTest.csv')
The response I've been getting a code 400
{'faultCode': '16a6f70f-1fa3-4b57-9ef3-a0a440f8a42e',
'responseCode': '400 Bad Request',
'message': 'Column LATITUDE missing'}
However, in my dataset, here I have all the headings that's required from the HERE API documentation to be able to make a call.
Is there something I'm doing wrong, I don't quite understand the POST call or the requirement as the HERE documentation doesn't explicitly give many examples.
The data field of your post request should contain the actual data, not just a filename. Try loading the file first:
f = open('Datasets/rtHereTest.csv', 'r')
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url, data=f.read())
f.close()
Here's what I use in my own code, with the coordinates defined before:
query = 'https://rme.api.here.com/2/matchroute.json?routemode=car&app_id={id}&app_code={code}'.format(id=app_id, code=app_code)
coord_strings = ['{:.5f},{:.5f}'.format(coord[0], coord[1]) for coord in coords]
data = 'latitude,longitude\n' + '\n'.join(coord_strings)
result = requests.post(query, data=data)
You can try to post the data using below format.
import requests
url = "https://rme.api.here.com/2/matchroute.json"
querystring = {"routemode":"car","app_id":"{app_id}","app_code":"{app_code}","filetype":"CSV"}
data=open('path of CSV file','r')
headers = {'Content-Type': "Content-Type: text/csv;charset=utf-8",
'Accept-Encoding': "gzip, deflate",
}
response = requests.request("POST", url, data=data.read().encode('utf-8'), params=querystring,headers=headers)
print(response.status_code)

Resources