使用python向RESTful API发出请求

我有一个RESTful API,使用EC2实例上的Elasticsearch实现来公开一个内容语料库。 我可以通过从我的terminal(MacOSX)运行以下命令来查询search:

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返回的响应types,您可能会想要查看response.textresponse.json() (或者可能首先检查response.status_code )。 请参阅此处的快速入门文档,特别是本节 。

使用请求和json使得它很简单。

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

请求模块为您提供有用的function来循环成功和失败。

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

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

以下是进行此类API调用的示例代码。 也可以在github中find。 该代码假定API使用摘要式身份validation。 您可以跳过此选项或使用其他适当的身份validation模块来validation调用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() 

所以你想传递一个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() 

您可以使用[ http://stackandqueue.com/?p=75%5D中的请求查看更多电话;

下面是在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) 

首先下载请求模块

 import requests url="any url here" # if url is like https instead of http then its certified # so you should give verify=false t=requests.get(url,verify=False) t.text