262

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

4

4 回答 4

373

使用请求

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首先检查)。请参阅此处的快速入门文档,尤其是本节

于 2013-06-25T19:55:36.693 回答
114

使用请求json使其变得简单。

  1. 调用 API
  2. json.loads假设 API 返回一个 JSON,使用函数将 JSON 对象解析为 Python dict
  3. 循环遍历字典以提取信息。

Requests模块为您提供有用的函数来循环成功和失败。

if(Response.ok):将帮助您确定您的 API 调用是否成功(响应代码 - 200)

Response.raise_for_status()将帮助您获取从 API 返回的 http 代码。

下面是进行此类 API 调用的示例代码。也可以在github中找到。该代码假定 API 使用摘要式身份验证。您可以跳过此步骤或使用其他适当的身份验证模块来验证调用 API 的客户端。

#Python 2.7.6
#RestfulClient.py

import requests
from requests.auth import HTTPDigestAuth
import json

# Replace with the correct URL
url = "http://api_url"

# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)

# For successful API call, response code will be 200 (OK)
if(myResponse.ok):

    # Loading the response data into a dict variable
    # json.loads takes in only binary or string variables so using content to fetch binary content
    # Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
    jData = json.loads(myResponse.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print key + " : " + jData[key]
else:
  # If response code is not ok (200), print the resulting http error code with description
    myResponse.raise_for_status()
于 2015-09-22T16:23:57.450 回答
12

因此,您想在 GET 请求的正文中传递数据,最好在 POST 调用中进行。您可以通过使用这两个请求来实现这一点。

原始请求

GET http://ES_search_demo.com/document/record/_search?pretty=true HTTP/1.1
Host: ES_search_demo.com
Content-Length: 183
User-Agent: python-requests/2.9.0
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate

{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}

带有请求的示例调用

import requests

def consumeGETRequestSync():
data = '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url,data = data)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)

consumeGETRequestSync()
于 2016-01-19T17:01:03.347 回答
10

下面是在python中执行rest api的程序-

import requests
url = 'https://url'
data = '{  "platform": {    "login": {      "userName": "name",      "password": "pwd"    }  } }'
response = requests.post(url, data=data,headers={"Content-Type": "application/json"})
print(response)
sid=response.json()['platform']['login']['sessionId']   //to extract the detail from response
print(response.text)
print(sid)
于 2017-05-18T10:12:47.483 回答