如何确定我的Python请求调用API是否返回数据

时间:2016-06-03 03:01:42

标签: python json

我使用Python请求查询作业板API。然后它写入一个包含在网页中的表。有时请求将不返回任何数据(如果没有打开的作业)。如果是这样,我想写一个字符串到包含的文件而不是表。识别无数据响应的最佳方法是什么?它是如此简单:如果响应=“”,或沿着这些线? 这是我发布API请求的Python代码:

#!/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': "jcarroll@fec.gov",
    '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

2 个答案:

答案 0 :(得分:14)

根据实际响应的不同,您有几个选项。我认为,案例3最适用:

# 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, '', ...)

答案 1 :(得分:0)

如果您的 API 已使用正确的状态代码编写,则

  1. 200 表示使用 body 成功响应
  2. 204 表示没有正文的成功响应。

在python中,您可以像下面一样简单地检查您的要求

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