I wonder how I can properly handle this invalid response. How to check if the response has status: 400
or perhaps has a title: Bad Request
?
url = f"https://api123.com"
substring = "title: Bad Request"
response = requests.get(url, headers=headers).json()
if substring in response:
print ("Your Data is Invalid")
else:
print ("Valid data")
response: #-- Response from url
https://api.xyzabc.com/data/abc1234
{'type': 'h---s://abc.com/data-errors/bad_request', 'title': 'Bad Request', 'status': 400, 'detail': 'The request you sent was invalid.', 'extras': {'invalid_field': 'account_id', 'reason': 'Account is invalid'}}
CodePudding user response:
An example to check status
url = 'https://api.github.com/search/repositories?q=language:python&sort=starts'
headers = {'Accept': 'application/vnd.github.v3 json'}
r = requests.get(url, headers=headers)
# check the request (200 is successful)
print(f"Satus code: {r.status_code}")
get dict from json
response_dict = r.json()
CodePudding user response:
You have a dictionary right there.
>>> response = {'type': 'h---s://abc.com/data-errors/bad_request', 'title': 'Bad Request', 'status': 400, 'detail': 'The request you sent was invalid.', 'extras': {'invalid_field': 'account_id', 'reason': 'Account is invalid'}}
>>> response["status"] == 400
True
response = {'type': 'h---s://abc.com/data-errors/bad_request', 'title': 'Bad Request', 'status': 400, 'detail': 'The request you sent was invalid.', 'extras': {'invalid_field': 'account_id', 'reason': 'Account is invalid'}}
if response["status"] == 400:
print(response["extras"]["reason"])
# prints: Account is invalid