close

How to determine if my Python Requests call to API returns no data

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to determine if my Python Requests call to API returns no data in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

HHow to determine if my Python Requests call to API returns no data?

  1. HHow to determine if my Python Requests call to API returns no data?

    You have a couple of options depending on what the response actually is. I assume, case 3 applies best:

  2. determine if my Python Requests call to API returns no data

    You have a couple of options depending on what the response actually is. I assume, case 3 applies best:

Method 1

You have a couple of options depending on what the response actually is. I assume, case 3 applies best:

# 1. Test if response body contains sth.
if response.text:
    # ...

# 2. Handle error if deserialization fails (because of no text or bad format)
try:
    responses = response.json()
    # ...
except ValueError:
    # no JSON returned

# 3. check that .json() did NOT return an empty dict
if responses:
    # ...

# 4. safeguard against malformed data
try:
    data = responses[some_key][some_index][...][...]
except (IndexError, KeyError, TypeError):
    # data does not have the inner structure you expect

# 5. check if data is actually something useful (truthy in this example)
if data:
    # ...
else:
    # data is falsy ([], {}, None, 0, '', ...)

Method 2

If your APIs has been written with correct status codes, then

  1. 200 means successful response with a body
  2. 204 means successful response without body.

In python you can check your requirement as simply as the following

if 204 == response.status_code :
    # do something awesome

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read