Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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:

#!/usr/bin/python
import requests
import json
from datetime import datetime
import dateutil.parser
url = "https://data.usajobs.gov/api/Search"

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

headers = {
   'authorization-key': "ZQbNd1iLrQ+rPN3Rj2Q9gDy2Qpi/3haXSXGuHbP1SRk=",
    'user-agent': "[email protected]",
    'host': "data.usajobs.gov",
    'cache-control': "no-cache",
    }

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


responses=response.json()



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">
    <tbody>
    <tr>
    <th>Vacancy</th>
    <th>Grade</th>
    <th>Open Period</th>        
    <th>Who May Apply</th>
    </tr>"""
    jobtable.write(table_head)
    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>")

jobtable.write("</tbody></table>")

jobtable.close
like image 212
JohnnyP Avatar asked Jun 03 '16 03:06

JohnnyP


People also ask

How check response is JSON or not in Python?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.

What does Python requests get return?

When one makes a request to a URI, it returns a response. This Response object in terms of python is returned by requests. method(), method being – get, post, put, etc. Response is a powerful object with lots of functions and attributes that assist in normalizing data or creating ideal portions of code.


2 Answers

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, '', ...) 
like image 130
user2390182 Avatar answered Oct 09 '22 22:10

user2390182


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
like image 25
Kuldeep Yadav Avatar answered Oct 09 '22 23:10

Kuldeep Yadav