使用python向RESTful API发出请求

用户7289:

我有一个RESTful API,我已在EC2实例上使用Elasticsearch的实现公开了该索引,以索引内容的语料库。我可以通过从终端机(MacOSX)运行以下命令来查询搜索:

curl -XGET 'http://ES_search_demo.com/document/record/_search?pretty=true' -d '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'

我如何使用python/requestspython/urllib2(不确定要使用哪一个-一直在使用urllib2,但听说请求更好...)将上述请求转换为API请求是否以标头形式传递?

不同地:

使用请求

import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'''
response = requests.post(url, data=data)

然后,根据您的API返回的响应类型,您可能需要查看response.textresponse.json()(或可能response.status_code检查)。请参阅此处的快速入门文档,尤其是本节

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章