Is there any way to skip the parameter or define it later? I'm trying to check the values in the json by using if-elif-else method< but i confronted with a problem.
Here is my code:
import requests
ps = {"page_size": 1}
resp = requests.get("api.url.com", params=ps)
json_response=resp.json()
if len(json_response["items"])==5:
print(json_response)
elif len(json_response["items"])==10 or len(json_response["items"])==15:
print("Page size is not 5")
else:
print(json_response["error"]["message"])
The problem is that with my params use. With this particular API, you can use "page_size": 5, 10 or 15 and get a json like:
{
"total": ,
"items": [
{
"id": 1,
"name": "Frank"
}
]
}
However, when I'm trying to use negative parameters like "page_size": 1, API responds with different body:
{
"error": {
"id": "71f2",
"message": "Wrong data"
}
}
With my code, I'm getting an error in line 7 (KeyError: 'items'). As far as I understand, my code can't find any items in error response, since there none, and it's failing to proceed with the last "else".
Is there any way to correctly set the parameters, so with the different response from API my code will act accordingly? In my last else I want to print the error message, that's why I need to go through this method.
CodePudding user response:
You can use .get()
to supply a default value if the key doesn't exist.
items = json_response.get("items", [])
if len(items) == 5:
print(json_response)
elif len(items) == 10 or len(items) == 15:
print("Page size is not 5")
else:
print(json_response["error"]["message"])
But better would be to just check if it's an error first:
if "error" in json_response:
print(json_response["error"]["message"])
elif len(json_reponse["items"]) == 5:
print(json_response)
elif len(json_response["items"])==10 or len(json_response["items"])==15::
print("Page size is not 5")
BTW, what should happen if you use "page_size": 5
but there are less than 5 items to return? You won't print the response.