python - 使用 Python 向 RESTful API 发出请求

标签 python rest

我有一个 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 将上述转换为 API 请求(不确定该选择哪一个 - 一直在使用 urllib2,但听到请求更好......)?我是作为标题传递还是以其他方式传递?

最佳答案

使用 requests :

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 首先)。请参阅快速入门文档 here , 特别是 this section .

关于python - 使用 Python 向 RESTful API 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17301938/

相关文章:

Python -- 正则表达式 -- 如何在两组字符串之间找到一个字符串

python - 如何在 div 中的 span 中找到 URL?

Python:有 check_call 输出连续输出到文件吗?

api - Swagger 集成到 Dropwizard 中

node.js - 是否在 Mongoose 良好实践之上使用 Joi 进行验证?

python - SciPy NumPy 和 SciKit-learn ,创建一个稀疏矩阵

python - 使用 sqlalchemy 将 CSV 导入数据库

java - Jersey 1.17 速率限制

java - 使用 Gson 在 Java 中反序列化 RouteXL 响应很困难,因为 RouteXL 返回多个对象而不是数组

python - 将 Python 类函数公开为 REST 服务