My Python code, which I obtained from POSTMAN, throws an error with the string
"code":"E101","message":"JSON Error: Syntax error, malformed JSON"}"
although in POSTMAN, the request was successful and produced the expected JSON result.
below is my python code
import requests
url = "APIURL"
payload={'data': '{
"authenticate":{
"apikey":"ABCSHF"
},
"services":[
{
"call":"history/API",
"identifier":{
"search":"desc"
}
}
]
}'}
files=[
]
headers = {
}
response = requests.request("POST", url, headers=headers, json=payload, files=files)
print(response.text)
Can anyone please help me on this.
I guess you should get clearness what did you code ;):
requests parse a dict to a JSON internally, see explanation here
import json
from pprint import pprint
# some JSON string:
json_string = '{ "authenticate":{ "apikey":"ABCSHF" }, "services":[ { "call":"history/API", "identifier":{ "search":"desc" } } ] }'
# parse JSON string to dict:
json_as_dict = json.loads(json_string)
pprint(json_as_dict)
# >> {'authenticate': {'apikey': 'ABCSHF'},
# >> 'services': [{'call': 'history/API', 'identifier': {'search': 'desc'}}]}
incorrect_payload_as_dict = {'data': json.dumps(json_as_dict)}
pprint(incorrect_payload_as_dict)
# >> {'data': '{"authenticate": {"apikey": "ABCSHF"}, "services": [{"call": '
# >> '"history/API", "identifier": {"search": "desc"}}]}'}
correct_payload_as_dict = {'data': json_as_dict}
pprint(correct_payload_as_dict)
# >> {'data': {'authenticate': {'apikey': 'ABCSHF'},
# >> 'services': [{'call': 'history/API',
# >> 'identifier': {'search': 'desc'}}]}}
Related
I have been trying to find an answer that work on my case but had no success.
I am getting a response 422 when running the code below. I have replaced the json in the response variable and also used json.dumps around the data variable but I am still getting this response. Would you be able to find the issue within my json file? Thanks a lot
todaystr = datetime.today().strftime('%Y-%m-%d')
today = datetime.strptime(todaystr, '%Y-%m-%d')
first_day_of_month = today.replace(day=1)
day_count_str = today - first_day_of_month
day_count_int = day_count_str / timedelta(days=1)
day_count_split = str(day_count_int)
sep = '.'
day_count = day_count_split.split(sep, 1)[0]
dt = str(first_day_of_month.timestamp())
data = {"requestId": "numberOfUniqueAccountsAndVisitors", "timeSeries": {"period": "dayRange", "count": day_count, "first": dt}, "source": {"events": None}, "pipeline": [{"reduce": [{"reduce": {"visitors": {"count": "visitorId"}, "accounts": {"count": "accountId"}}}]}]}
headers = {
'x-pendo-integration-key': API_Key,
'content-type': "application/json"
}
response = requests.post(url, json=data, headers=headers)
print(response)
response_dictionary = json.loads(response.content)
print(response_dictionary)
In the payload to the Pendo Aggregation API, the request object should not be an array. And make sure the "key" should be named as "request"(singular), not as "requests"(plural).
Try something like this
{
"response": {
"mimeType": "application/json"
},
"request": {
"name": "accounts-last7days",
"requestId": "accounts-last7days"
}
}
I am trying to get the values from objects in the following JSON response:
[
{
"compositionId": "-Mkl92Mii2UF3xzi1q7L",
"compositionName": null,
"mainComposition": true,
"animation": {
"state": "Out1"
}
},
{
"compositionId": "bbbbbb",
"compositionName": null,
"mainComposition": true,
"animation": {
"state": "Out1"
}
}
]
What I would like to get in a loop is all the compositionIds but I don't get the correct output.
I can dump the complete JSON with the following code:
import requests
import json
url = 'http://192.168.1.33/data'
r = requests.get(url)
data = json.loads(r.content.decode())
json_str = json.dumps(data)
resp = json.loads(json_str)
print (resp)
You can simply use the requests module, in fact it does provide a builtin json decoder, that is the .json() function. Done that, you can simply iterate over your json objects with a simple for.
You could do something similar to this:
import requests
url = 'http://192.168.1.33/data'
r = requests.get(url)
my_json_file = r.json()
for json_object in my_json_file:
# Do something with json_object['compoitionId']
pass
Try something like this:
import requests
import json
url = 'http://192.168.1.33/data'
r = requests.get(url)
data = json.loads(r.content.decode())
print([d['compositionId'] for d in data])
I have this curl that works, it returns this
curl -X POST \
https://login.smoobu.com/booking/checkApartmentAvailability \
-H 'Api-Key: xxxxx' \
-H 'cache-control: no-cache' \
-d '{
"arrivalDate" : "2018-04-01",
"departureDate": "2019-12-03",
"apartments": [126936, 127858, 126937],
"customerId": 38484
}'
it returns this
{
"availableApartments": [
127858
],
"prices": [],
"errorMessages": {
"126936": {
"errorCode": 405,
"message": "The chosen day of departure is not available.",
"departureDays": [
"Sa"
]
},
"126937": {
"errorCode": 405,
"message": "The chosen day of departure is not available.",
"departureDays": [
"Sa"
]
}
}
}
I rewrote it in python like so
In [1]: import requests
In [2]: headers = {'Api-Key': 'xxxx', 'cache-control': 'no-cache'}
In [8]: payload = {
...: "arrivalDate" : "2018-04-01",
...: "departureDate": "2019-12-03",
...: "apartments": [126936, 127858, 126937],
...: "customerId": 38484
...: }
In [4]: r = requests.post("https://login.smoobu.com/booking/checkApartmentAvailability", data=payload, headers=headers)
In [5]: r
Out[5]: <Response [400]>
In [13]: r.content
Out[13]: b'{"title":"Error occurred","detail":"json is invalid"}'
I got back a response of invalid json, I'm not sure why though since the way I know it works is it takes a dict and turns it into a json request.
For sending JSON, you should use the json parameter:
r = requests.post("https://login.smoobu.com/booking/checkApartmentAvailability", json=payload, headers=headers)
As explained in the docs:
r = requests.post(url, data=json.dumps(payload))
r = requests.post(url, json=payload)
Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically
I'm pretty much a noob with Python (and coding in general), so please excuse me if I'm being stupid.
I'm writing a short script for a custom Zapier step, which is supposed to iterate through a list of URLs, pick the ones that end in .pdf and send those to ConvertAPI in order to be converted to JPGs.
Sending the request to ConvertAPI works so far and ConvertAPI says that the test file has been converted. Here's my question: How do I get the resulting URL of the converted file back? If I print the response, I get Response [200], but nothing else to work with.
I have tried turning on the Async parameter, but so far to no avail. From what I understand, StoreFile has to be set to true, but it doesn't seem to make a difference.
import requests
import json
url = 'https://v2.convertapi.com/convert/pdf/to/jpg?Secret=******' # Hidden
headers = {'content-type': 'application/json'}
payload = {
'Parameters': [
{
'Name': 'File',
'FileValue': {
'Url': 'to be populated'
}
},
{
'Name': 'StoreFile',
'Value': 'true'
}
]
}
a = ['https://www.bachmann.com/fileadmin/02_Produkte/03_Anschlussfelder/CONI/Downloads/CONI_3-4-6-way_Mounting_instructions_REV05.pdf','test2.jpg','test3.jpeg','test4.png','test4.exe']
for x in a:
if x[-3:] == 'pdf':
payload['Parameters'][0]['FileValue']['Url'] = x
response = requests.post(url, data=json.dumps(payload), headers=headers)
print(response)
elif x[-3:] == 'jpg' or x[-3:] == 'png' or x[-4:] == 'jpeg':
print('thats an image, nothing to do here')
A friend helped me, with this IRL, here it goes:
import requests
import json
output = {'output_urls' : []}
url = 'https://v2.convertapi.com/convert/pdf/to/jpg?Secret=xxxxxxx' # Hidden
headers = {'content-type': 'application/json'}
payload = {
'Parameters': [
{
'Name': 'File',
'FileValue': {
'Url': 'to be populated'
}
},
{
'Name': 'StoreFile',
'Value': 'true'
},
{
'Name': 'ScaleImage',
'Value': 'true'
},
{
'Name': 'ScaleProportions',
'Value': 'true'
},
{
'Name': 'ScaleIfLarger',
'Value': 'true'
},
{
'Name': 'ImageHeight',
'Value': '2200'
},
{
'Name': 'ImageWidth',
'Value': '1625'
}
]
}
for x in input_data['input_urls'].split(',') : # input_data is passed by Zapier
if x[-3:] == 'pdf':
payload['Parameters'][0]['FileValue']['Url'] = x
response = requests.post(url, data=json.dumps(payload), headers=headers)
response_obj = json.loads(response._content)
for file_url in response_obj['Files'] :
output['output_urls'].append(file_url['Url'])
elif x[-3:] == 'jpg' or x[-3:] == 'png' or x[-4:] == 'jpeg' :
output['output_urls'].append(x)
return output
print(response)
is receive the status code of response so it's received 200 which mean the request is successfully
to get the url you can use .url
print(response.url)
The ConvertAPI has Python library https://github.com/ConvertAPI/convertapi-python
which would help you easily convert pdf to jpg using code below.
import convertapi
import os
import tempfile
convertapi.api_secret = os.environ['CONVERT_API_SECRET'] # your api secret
jpg_result = convertapi.convert(
'jpg',
{
'File': 'files/test.pdf',
'ScaleImage': True,
'ScaleProportions': True,
'ImageHeight': 300,
'ImageWidth': 300,
}
)
saved_files = jpg_result.save_files(tempfile.gettempdir())
print("The thumbnail saved to %s" % saved_files)
I am facing this error while making request to fetch json from api.
I can get json data using the "/v1/articles' path.
conn = http.client.HTTPSConnection("api.xxxx.com.tr")
headers = {
'accept': "application/json",
'apikey': "cd6b6c96799847698d87dec9f9a731d6"
}
filter = "daily"
conn.request("GET", "/v1/articles", headers=headers)
reader = codecs.getreader("utf-8")
res = conn.getresponse()
data = json.load(reader(res))
json.dumps(data)
return data
But i am having JSONDecodeError if i set filter. Code:
conn = http.client.HTTPSConnection("api.xxxx.com.tr")
headers = {
'accept': "application/json",
'apikey': "cd6b6c96799847698d87dec9f9a731d6"
}
conn.request("GET", "/v1/articles?$filter=Path eq '/daily/'", headers=headers)
reader = codecs.getreader("utf-8")
res = conn.getresponse()
data = json.load(reader(res))
json.dumps(data)
return data
I tried same filter using Postman with no error and i can get Json data.
Returned Json data from Postman:
[
{
"Id": "40778196",
"ContentType": "Article",
"CreatedDate": "2018-03-20T08:28:05.385Z",
"Description": "İspanya'da 2016 yılında çalınan lüks otomobil, şasi numarası değiştirilerek Bulgaristan üzerinden getirildiği Türkiye'de bulundu.",
"Files": [
{
"FileUrl": "http://i.xxxx.com/i/xxxx/98/620x0/5ab0c6a9c9de3d18a866eb54.jpg",
"Metadata": {
"Title": "",
"Description": ""
}
}
],
"ModifiedDate": "2018-03-20T08:32:12.001Z",
"Path": "/gundem/",
"StartDate": "2018-03-20T08:32:12.001Z",
"Tags": [
"ispanya",
"Araç",
"Hırsız",
"Dolandırıcı"
],
"Title": "İspanya'da çalınan lüks araç Türkiye'de bulundu!",
"Url": "http://www.xxxx.com.tr/gundem/ispanyada-calinan-luks-arac-turkiyede-bulundu-40778196"
}
]
I can not figure out the problem. It would be great if anyone help me about this issue. Thank you.
I finally figured out the problem! Using the requests library have solved my problem now I can filter the api request.
data = requests.get('https://api.xxxxx.com.tr/v1/articles', headers =
headers, params={"$filter":"Path eq '/xxxxxx/'"}).json()
I am leaving this answer here for anyone else who can need this solution in the future.
Thanks for all your suggestions.
The problem is in the following line
data = json.load(reader(res))
when your response is not a json string, JSONDecodeError occurs. so, add an additional logic to see if the response is None or a json string. First thing, print the reader(res) and see what the return is