使用python向RESTful API发出请求

use*_*289 194 python api rest elasticsearch

我有一个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": {}
}'
Run Code Online (Sandbox Code Playgroud)

我如何使用python/requestspython/urllib2(不确定要使用哪一个 - 使用urllib2,但听到请求更好......)将上面变成API请求?我是否以标题或其他方式传递?

and*_*ler 302

使用请求:

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)
Run Code Online (Sandbox Code Playgroud)

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

  • "requests.get"不接受"data"参数.它可以采用可选的"params"参数,该参数通常是带有查询字符串的字典.如果需要有效负载来获取数据(例如发布的示例),则需要使用"requests.post".另外使用"json"库可以更轻松地解析json响应. (6认同)
  • 我认为,它应该是:response = requests.post(url,data = data) (3认同)
  • @ParveenShukhala"请求正式支持Python 2.6-2.7和3.3-3.5,并且在PyPy上运行得很好." - https://pypi.python.org/pypi/requests/ (3认同)
  • 由于您发送的是 JSON,因此您可以使用 json 参数而不是像这样的数据: response = requests.post(url, json=data) (2认同)

HVS*_*HVS 93

使用请求json使它变得简单.

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

请求模块为您提供循环成功和失败的有用功能.

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()
Run Code Online (Sandbox Code Playgroud)

  • 在键上进行迭代的最后部分将始终无法工作,因为JSON文档可能会将数组作为顶层元素。因此,尝试获取`jData [key]`将是一个错误。 (2认同)
  • 在python3下,以下内容被吐出'JSON must be str not bytes'。这是通过解码输出来修复的,即 json.loads(myResponse.content.decode('utf-8'))。此外,您应该使用 str() 包装键和 jData 键,以便当 RESTful API 返回整数时,它不会抱怨。 (2认同)

gvi*_*vir 9

因此,您希望在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": {}
}
Run Code Online (Sandbox Code Playgroud)

使用请求进行示例调用

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()
Run Code Online (Sandbox Code Playgroud)

  • 应该使用headers变量:request.get(... headers = headers,....) (3认同)

Sha*_*k G 7

下面是在python中执行其余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)
Run Code Online (Sandbox Code Playgroud)