title: KeyError when connecting to API
body: <p>I'm trying to connect my Django application with the API my teammates made. I wrote a script that builds the string and then makes a request. I want to return the results to a view so I can display them on a webpage. I'm debugging the script by calling it from a terminal, but I will call the run_query method from my views file once it works. The terminal from which I'm executing the script returns this error, however:</p>
  
  <pre><code>Traceback (most recent call last):
    File "website/api.py", line 45, in &lt;module&gt;
      run_query("Statistics", 42)
    File "website/api.py", line 32, in run_query
      for result in json_response[0]['results']:
  KeyError: 0
  </code></pre>
  
  <p>I've replaced some values because the data is not meant to be public.</p>
  
  <p>This is what the API returns:</p>
  
  <p><code>{"Statistics":[{"DateTime":"2015-03-10T06:20:39Z","Percentage":33},{"DateTime":"2015-03-10T06:21:39Z","Percentage":23},(Hundred more records){"DateTime":"2015-03-19T21:15:35Z","Percentage":9}],"AverageStatistics":11}</code></p>
  
  <p>This is the Python script.</p>
  
  <pre><code>import json
  import requests
  
  def run_query(type, id):
      # Base URL
      root_url = "https://api.com/"
  
      if type == "Statistics":
          data_type = "Statistics"
      else:
          print("Error: Invalid type input.")
  
      request_url = root_url + data_type + "?Id=" + str(id)
      print request_url
  
      results = []
  
      try:
          # Connect
          response = requests.get(request_url)
          print response
  
          # Convert response to dictionary object
          json_response = response.json()
          print json_response
  
          # Loop through results
          if type == "Statistics":
              for result in json_response[0]['results']:
                  results.append({
                  'DateTime': result['DateTime'],
                  'Percentage': result['Percentage']})
  
      # Catch URLError exception
      except requests.exceptions.RequestException, e:
          print "Error querying API: ", e
  
      return results
  
  if __name__ == '__main__':
      print "Connecting with API..."
      run_query("Statistics", 42)
  </code></pre>
  
  <p>The line <code>for result in json_response[0]['results']:</code> is what throws the error. I've read that the response should be a list object, so 0 as the key should work, right? I've tried using "Statistics" as a key, but then Python tells me that I should've input an integer.</p>
  
  <p><code>print json_response</code> prints this:</p>
  
  <pre><code>{u'AverageStatistics': 11.739414713896636, u'Statistics': [{u'Percentage': 33.23, u'DateTime': u'2015-03-10T06:20:39Z'},
  </code></pre>
  
  <p>And then a lot more records.</p>