How to handle API response in python

Question:

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'}}
Asked By: rbutrnz

||

Answers:

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
Answered By: picobit

An example to check status

import requests

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()
Answered By: burak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.