JohnnyP JohnnyP - 9 months ago 33
Python Question

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

I have a query to an job board API using Python Requests. It then writes to a table, that is included in a web page. Sometimes the request will return no data(if there are no open jobs). If so, I want to write a string to the included file instead of the table. What is the best way to identify a response of no data? Is it as simple as: if response = "", or something along those lines?
Here is my Python code making the API request:

import requests
import json
from datetime import datetime
import dateutil.parser
url = ""

querystring = {"Organization":"LF00","WhoMayApply":"All"}

headers = {
'authorization-key': "ZQbNd1iLrQ+rPN3Rj2Q9gDy2Qpi/3haXSXGuHbP1SRk=",
'user-agent': "",
'host': "",
'cache-control': "no-cache",

response = requests.request("GET", url, headers=headers, params=querystring)


with open('/Users/jcarroll/work/infoweb_branch4/rep_infoweb/trunk/fec_jobs.html', 'w') as jobtable:

jobtable.write("Content-Type: text/html\n\n")
table_head="""<table class="job_table" style="border:#000">
<th>Open Period</th>
<th>Who May Apply</th>
for i in responses['SearchResult']['SearchResultItems']:
start_date = dateutil.parser.parse(i['MatchedObjectDescriptor']['PositionStartDate'])
end_date = dateutil.parser.parse(i['MatchedObjectDescriptor']['PositionEndDate'])
jobtable.write("<tr><td><strong><a href='" + i['MatchedObjectDescriptor']['PositionURI'] + "'>" + i['MatchedObjectDescriptor']['PositionID'] + ", " + i['MatchedObjectDescriptor']['PositionTitle'] + "</a></strong></td><td>" + i['MatchedObjectDescriptor']['JobGrade'][0]['Code'] + "-" + i['MatchedObjectDescriptor']['UserArea']['Details']['LowGrade']+ " - " + i['MatchedObjectDescriptor']['UserArea']['Details']['HighGrade'] + "</td><td>" + start_date.strftime('%b %d, %Y')+ " - " + end_date.strftime('%b %d, %Y')+ "</td><td>" + i['MatchedObjectDescriptor']['UserArea']['Details']['WhoMayApply']['Name'] + "</td></tr>")




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)
    # ...
except ValueError:
    # no JSON returned

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