Home > Net >  Payload from a defined list in Python
Payload from a defined list in Python

Time:10-12

I am pretty new to python and I am trying to create a script that will pull data from a ticketing platform.

I got the list of agents and their ids but when I try to pull the data it's giving me this error:

KeyError: 'data'

Is there a way for me to have the parameter "agents": to automatically update using the agent_id list?

Here is the code, I removed the links and the API key for privacy reasons:

import requests
import json
from cgitb import text
from openpyxl import Workbook
import openpyxl
import requests
from datetime import date
from datetime import timedelta
#Agents list
agents_list = ["Agent1", "Agent2", "Agent3"]
agent_id = []
agents_names = []

today = date.today()
yesterday = today - timedelta(days = 1)

start_date = str(yesterday)
end_date = str(yesterday)

def extragere_date_agenti():
    url = "https://x.gorgias.com/api/users?limit=100&order_by=name:asc&roles=agent&roles=admin"

    headers = {
        "accept": "application/json",
        "authorization": "Basic"
    }
    response = requests.get(url, headers=headers)
    text_name_id = json.loads(response.text)
    for names in text_name_id["data"]:
        agent_name = names["firstname"]
        agents_id = names["id"]
        if agent_name in agents_list:
            agents_names.append(agent_name)
            agent_id.append(agents_id)
extragere_date_agenti()

def extragere_numere():
    url = "https://x.gorgias.com/api/stats/total-messages-sent"

    payload = {"filters": {
            "period": {
                "start_datetime": start_date   "T00:00:00-05:00",
                "end_datetime": end_date   "T23:59:59-05:00"
            },
            "agents": [agent_id], #This is the value that I want to modify
            "channels": ["email"]
        }}
    headers = {   
        "accept": "application/json",
        "content-type": "application/json",
        "authorization": "Basic"
    }
    response = requests.post(url, json=payload, headers=headers)
    text_numere = json.loads(response.text)
    numere_finale = text_numere["data"]["data"]["value"]
    print(numere_finale)

I've tried to do a for loop but it's giving me the same error. Any suggestions?

CodePudding user response:

First, add the condition to check the response status code Also, add another condition to prevent this type of key error:

if "data" in text_name_id:

CodePudding user response:

Your Error:

KeyError: 'data'

Means that in text_name_id is no Key named "data".

Difficult to tell you how to fix it without any more info...

Are you sure, that request returns a positiv status?? I see no ErrorHandling, if respone.status_code == 200: should be enough to check.

Are you sure that the response json has a Key named "data"? Try this to set a default if key is missing:

text_name_id.get("data", [{"firstname": "error", "id": 0}])

--- Edit ---

Okay, is that the right one I don't see a "id" or "firstname" key. But if it is the right JSON, than you can't iterate over dict like you did in Python. To do so you would want to do this:

for key, value in text_name_id['data']['data'].items():
    ...
  • Related