Reputation: 13
I need help my friends, it's my first project with Api, and I'm not able to pull the data from the Api, it returns the following error.
Script:
response = data.json()
for number in response['mobile_phones']:
dd = resposta['ddd']
num = resposta['number']
whatsapp = resposta['whatsapp_datetime']
print(dd+num+whatsapp)
Erro:
Erro: KeyError: 'mobile_phones'
Response Api
{
"cpf": 52289257591,
"mobile_phones": [
{
"ddd": 27,
"number": "999111151",
"priority": 1,
"cdr_datetime": null,
"hot_datetime": null,
"whatsapp_datetime": "2022-03-05 00:00:00",
"cpc_datetime": null
},
{
"ddd": 27,
"number": "998608229",
"priority": 2,
"cdr_datetime": null,
"hot_datetime": null,
"whatsapp_datetime": "2022-03-07 00:00:00",
"cpc_datetime": null
},
{
"ddd": 27,
"number": "992250660",
"priority": 3,
"cdr_datetime": null,
"hot_datetime": null,
"whatsapp_datetime": "2022-03-12 00:00:00",
"cpc_datetime": null
}
],
"ip": "135.199.5.98",
"plan": "Consulta simples"
}
]
Upvotes: 1
Views: 44
Reputation: 832
Is the API actually returning an array of these objects? If so,
response = data.json()
for thing in response:
for number in thing['mobile_phones']:
dd = number['ddd']
num = number['number']
whatsapp = number['whatsapp_datetime']
print(dd+num+whatsapp)
though I'd generally recommend using .get("mobile_phones")
anyways especially if this is some API you don't control so that if the response shape were to change ever to like "phones", your code can be more resilient to blowing up.
Upvotes: 0
Reputation: 16081
You can do this,
for number in response[0]['mobile_phones']:
dd = number['ddd']
num = number['number']
whatsapp = number['whatsapp_datetime']
print(dd, num, whatsapp)
response
is a list, which has dictionary of values.
The list you are looking its need to access like this, response[0]['mobile_phones']
Output:
27 999111151 2022-03-05 00:00:00
27 998608229 2022-03-07 00:00:00
27 992250660 2022-03-12 00:00:00
Upvotes: 1