title: Accessing Elasticsearch with Python 3
body: <p>I want to use the Python 3 module <a href="https://docs.python.org/3/library/urllib.html" rel="nofollow noreferrer">urllib</a> to access an Elasticsearch database at <code>localhost:9200</code>. My script gets a valid request (generated by Kibana) piped to STDIN in JSON format.</p>
  
  <p>Here is what I did:</p>
  
  <pre><code>import json
  import sys
  import urllib.parse
  import urllib.request
  
  er = json.load(sys.stdin)
  data = urllib.parse.urlencode(er)
  data = data.encode('ascii')
  uri = urllib.request.Request('http://localhost:9200/_search', data)
  with urllib.request.urlopen(uri) as repsonse:
      response.read()
  </code></pre>
  
  <p>(I understand that my <code>repsonse.read()</code> doesn't make much sense by itself but I just wanted to keep it simple.)</p>
  
  <p>When I execute the script, I get an</p>
  
  <pre><code>HTTP Error 400: Bad request
  </code></pre>
  
  <p>I am very sure that the JSON data I'm piping to the script is correct, since I had it printed and fed it via <code>curl</code> to Elasticsearch, and got back the documents I expected to get back.</p>
  
  <p>Any ideas where I went wrong? Am I using <code>urllib</code> correctly? Do I maybe mess up the JSON data in the <code>urlencode</code> line? Am I querying Elasticsearch correctly?</p>
  
  <p>Thanks for your help.</p>