Ebram Shehata
Ebram Shehata

Reputation: 33

KeyError: 'tickets' Json API with Python

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
        }
      },

Upvotes: 0

Views: 489

Answers (1)

balderman
balderman

Reputation: 23815

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

Upvotes: 1

Related Questions