I had created App to exporting excel file from Zendisk to help my to Analysis data
But yesterday stop working with this error
line 20, in <module>
tickets = page_data['tickets'] # extract the "tickets" list from the page
KeyError: 'tickets'
I know this error mean key tickets not found in JSON file but actually there are tickets in file
Code:
print(f'Getting tickets from view ID {view_id}')
url = f'https://****.zendesk.com/api/v2/views/{view_id}/tickets.json'
while url:
response = requests.get(url, auth=auth)
page_data = response.json()
tickets = page_data['tickets'] # ERROR here
view_tickets.extend(tickets)
url = page_data['next_page']
JSON Page
{
"tickets": [
{
"url": "https://****.zendesk.com/api/v2/tickets/55251281.json",
"id": *******,
"external_id": null,
"via": {
"channel": "api",
"source": {
"from": {},
"to": {},
"rel": null
}
},
Current code:
...
response = requests.get(url, auth=auth)
page_data = response.json()
tickets = page_data['tickets'] # ERROR here
...
Required code in order to find the problem:
(The code below will catch 2 situations. 1) HTTP GET failed 2) No 'tickets' in the response )
...
response = requests.get(url, auth=auth)
if response.status_code == 200:
page_data = response.json()
print(page_data)
if 'tickets' in page_data:
tickets = page_data['tickets']
else:
print(f'no tickets in the response (url: {url})')
else:
print(f'HTTP GET (url: {url}) failed with status code {response.status_code}')
...
Related
I have this code and i want to place a buy order using the binance spot api, but it doesn't like my symbol that i am using showing me the error:
{'code': -1102, 'msg': "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed."}
import json
import requests
import time
API_KEY = "apikey"
SECRET_KEY = "secretkey"
ENDPOINT = "https://api.binance.com/api/v3/order"
HEADERS = {
"X-MBX-APIKEY": API_KEY
}
PAYLOAD = {
"symbol": "BTCUSDT",
"side": "BUY",
"type": "MARKET",
"quantity": "0.1",
"timestamp": int(time.time() * 1000)
}
response = requests.post(ENDPOINT, headers=HEADERS, params=json.dumps(PAYLOAD))
if response.status_code != 200:
print("Error placing buy order:")
print(response.json())
else:
print("Buy order placed successfully:")
print(response.json())
I wanted it to tell me that i had insufficient funds (true) but just to know that if i had money on it, it would place the order.
EDIT: Changed to most recent comment, the prevailing error occurs.
Can you try this:
import json
response = requests.post(ENDPOINT, headers=HEADERS, params=json.dumps(PAYLOAD))
I am trying to use the POST method of Amadeus flight availabilities API on Python, but is is still giving me error 400. Any suggestions? Many thanks.
from amadeus import Client, ResponseError, Location
import requests
amadeus = Client(
client_id='My ID',
client_secret='My Secret')
try:
flights = amadeus.get('/v2/shopping/flight-offers',originLocationCode = "GIG",destinationLocationCode = "ATL",departureDate = "2023-01-31",nonStop = "true",travelClass = "BUSINESS",adults = 1)
body = flights.data[0]
print(body)
except ResponseError as error:
print(error)
try:
availability = amadeus.post('/v1/shopping/availability/flight-availabilities', body)
print(availability.result)
except ResponseError as error:
print('headers: ', error.response.request.headers)
print('body: ', error.response.request.params)
As per their API documentation, the body of the second API call needs to be in the following format:
{
"originDestinations": [
{
"id": "1",
"originLocationCode": "BOS",
"destinationLocationCode": "MAD",
"departureDateTime": {
"date": "2021-11-14",
"time": "21:15:00"
}
}
],
"travelers": [
{
"id": "1",
"travelerType": "ADULT"
}
],
"sources": [
"GDS"
]
}
Right now you are just feeding the second call the return from the first, which doesn't seem to be what they're looking for.
You might also need to feed the proper headers, something like:
headers = {"Content-Type": "application/json; charset=utf-8"}
then you would do
response = requests.post(url, headers=headers, json=body)
I'm trying to use the free api https://www.qrcode-monkey.com and I can't find anywhere a valid example for python, I think I followed thru the documentation. I'm doing some trial and on POST I continue getting method errors and on GET I get a lot of 400 errors...
Here is the code with both, anyone knows what I'm doing wrong? Thank you!
import requests
from urllib.parse import quote, urlencode
class QrManager:
def __init__(self):
self.url = "https://qrcode-monkey.com/"
def get_data_post(self):
url = self.url + "qr/custom"
payload = {
"data": "https://www.google.com",
"config": {
"body": "circle",
},
"size": 300,
"download": False,
"file": "png"
}
req = requests.post(url, json=payload)
return req
def get_data_get(self):
template_url = self.url + "qr/custom/?{}"
params = {
"data": "https://www.google.com",
"config": {
"body": "circle",
},
"size": 300,
"download": False,
"file": "png"
}
url = template_url.format(urlencode(params, safe="()", quote_via=quote))
req = requests.get(url)
return req
qrm = QrManager()
# response = dm.get_data_post()
response = qrm.get_data_get()
print(response.status_code)
print(response.url)
print(response.text)
They didn't show it in documentation but it needs different URL - with api. instead of www.
https://api.qrcode-monkey.com/qr/custom
I used DevTools in Firefox/Chrome (tab:Network) to see url used when page generates QR.
There is other problem.
POST gives QR with circles but GET gives with normal squares.
GET needs to convert config to json to get circles
"config": json.dumps({"body": "circle"})
(but it doesn't need urlencode)
Full code.
import requests
#from urllib.parse import quote, urlencode
import json
class QrManager:
def __init__(self):
self.url = "https://api.qrcode-monkey.com/qr/custom"
def get_data_post(self):
# it converts `config` to `json` automatically (because it sends all `payload` as `json`)
payload = {
"data": "https://blog.furas.pl",
"config": {
"body": "circle",
},
"size": 300,
"download": False,
"file": "png"
}
response = requests.post(self.url, json=payload)
return response
def get_data_get(self):
# it needs to convert `config` to `json` manually
payload = {
"data": "https://blog.furas.pl",
"config": json.dumps({
"body": "circle"
}),
"size": 300,
"download": False,
"file": "png"
}
#payload = urlencode(payload, safe="()", quote_via=quote)
response = requests.get(self.url, params=payload)
return response
# --- main ---
qrm = QrManager()
print('\n--- GET ---\n')
response = qrm.get_data_get()
print('status:', response.status_code)
print('url:', response.url)
print(response.text[:100])
with open('QR_GET.png', 'wb') as f:
f.write(response.content)
print('\n--- POST ---\n')
response = qrm.get_data_post()
print('status:', response.status_code)
print('url:', response.url)
print(response.text[:100])
with open('QR_POST.png', 'wb') as f:
f.write(response.content)
Result:
--- GET ---
status: 200
url: https://api.qrcode-monkey.com/qr/custom?data=https%3A%2F%2Fblog.furas.pl&config=%7B%22body%22%3A+%22circle%22%7D&size=300&download=False&file=png
�PNG
IHDR\\t�{bKGD��������IDATx��ON[��š�6#�P��hŮ#H� ��[��M��T=3#J
--- POST ---
status: 200
url: https://api.qrcode-monkey.com/qr/custom
�PNG
IHDR\\t�{bKGD��������IDATx��ON[��š�6#�P��hŮ#H� ��[��M��T=3#J
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'm using requests lib to fetch data from remote server and I'm saving the data in the model, but I need to handle pagination, currently I'm only loading one page from server.
I have a url for pagination like so
{
"status": "success",
"count": 32,
"total": 32,
"next": "https://pimber.ly/api/v2/products?sinceId=5c3ca8470985af0016229b5b",
"previous": "https://pimber.ly/api/v2/products?maxId=5c3ca8470985af0016229b04",
"sinceId": "5c3ca8470985af0016229b04",
"maxId": "5c3ca8470985af0016229b5b",
"data": [
{
"Primary ID": "API_DOCS_PROD1",
"Product Name": "Example Product 1",
"Product Reference": "Example Reference 1",
"Buyer": "Example Buyer 1",
"_id": "5c3ca8470985af0016229b04",
"primaryId": "API_DOCS_PROD1"
},
I've tried to use python generator to handle current situation but, that does not do anything
_plimber_data = response.json()
yield _plimber_data
_next = _plimber_data['next']
print(_next)
for page in _next:
_next_page = session.get(_plimber_data, params={'next': page}).json()
yield _next_page['next']
for _data in page:
Product.objects.create(
qr_id=_data['primaryId'],
ean_code=_data['EAN'],
description=_data['Description105'],
category=_data['Category'],
marketing_text=_data['Marketing Text'],
bullet=_data['Bullet 1'],
brand_image=_data['Brand Image'],
image=_data['Images']
)
logger.debug(f'Something went wrong {_data}')
print(f'This is the Data:{_data}')
Can someone please explain me how to handle this so I can load all the data into the database, thanks.
Ok so I've solved it, two thinks first generator function
def _get_product():
"""
TODO: Fetch data from server
"""
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': settings.TOKEN
}
try:
response = requests.get(
url=f'{settings.API_DOMAIN}',
headers=headers
)
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
else:
_plimber_data = response.json()
while _plimber_data['next'] is not None:
response = requests.get(
_plimber_data['next'],
headers=headers
)
_plimber_data = response.json()
for _data in _plimber_data['data']:
yield _data
Then I iterate over generator function, and save the data:
def run(self):
_page_data = _get_product()
for _product in _page_data:
Product.objects.create(
qr_id=_product['primaryId'],
ean_code=_product['EAN'],
description=_product['Description105'],
category=_product['Category'],
marketing_text=_product['Marketing Text'],
bullet=_product['Bullet 1'],
brand_image='\n'.join(_product['Brand Image']),
image='\n'.join(_product['Images'])
)
logger.debug(f'Something went wrong {_product}')
print(f'This is the Data:{_product}')