pythonhttpgethttplib

Python - check if empty response from GET request with HTTP lib


I have a simple basic question but I cannot find a reliable answer online nor in the lib's docs.

I have a sample code with does a GET request in Python, using lib http.client . I want to check if the response body is empty or not before performing the json.loads(response) .

In the docs it's not explained how and the resources online I find use request or urllib, but I can only use http.client.

I tried considering checking the response length

if conn.getresponse().length < 1:
   print("Error: empty response")
else:
   json.loads(conn.getresponse().read().decode())

but I don't reckon it's reliable, so I'm considering something like

if conn.getresponse().read():
   json.loads(conn.getresponse().read().decode())
else:
   print("Error: empty response")

which I like more, but I'm not sure if it works: since the conn.getresponse().read returns an object in binary like

b'{\n  "field" : "0"}

my question here is if b'{} would be considered empty or not.

Thank you in advance.


Solution

  • Question: "Is b'{}' considered empty or not?"

    Answer: No

    bool(b'') # False <=> Empty.
    bool(b'{}') # True <=> Not Empty.
    

    Read Bytes Literals.


    However, an empty dictionary would be considered empty:

    bool({}) # True <=> Empty.
    

    And a Bytes Literal can be trivially turned into a string by decode-ing it.

    b'{}'.decode() # Return '{}'
    

    And you can turn a string of a dictionary into an actual Python dictionary by using the eval() function or read Convert a String representation of a Dictionary to a dictionary for a safer(?) option.


    Additionally, if it is not too fragile for your use-case, you may use the expression:

    if response == b'{}': 
        ...