使用 python 向 RESTful API 发出请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17301938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making a request to a RESTful API using python
提问by user7289
I have a RESTful API that I have exposed using an implementation of Elasticsearch on an EC2 instance to index a corpus of content. I can query the search by running the following from my terminal (MacOSX):
我有一个 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": {}
}'
How do I turn above into a API request using python/requests
or python/urllib2
(not sure which one to go for - have been using urllib2, but hear that requests is better...)? Do I pass as a header or otherwise?
我如何使用python/requests
or python/urllib2
(不确定要使用哪个 - 一直在使用 urllib2,但听说请求更好......)我是作为标题传递还是以其他方式传递?
采纳答案by andersschuller
Using 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)
Depending on what kind of response your API returns, you will then probably want to look at response.text
or response.json()
(or possibly inspect response.status_code
first). See the quickstart docs here, especially this section.
根据您的 API 返回的响应类型,您可能需要查看response.text
或response.json()
(或可能response.status_code
首先检查)。请参阅此处的快速入门文档,尤其是本节。
回答by HVS
Using requestsand jsonmakes it simple.
- Call the API
- Assuming the API returns a JSON, parse the JSON object into a
Python dict using
json.loads
function - Loop through the dict to extract information.
- 调用 API
- 假设 API 返回一个 JSON,使用
json.loads
函数将 JSON 对象解析为 Python dict - 循环遍历字典以提取信息。
Requestsmodule provides you useful function to loop for success and failure.
请求模块为您提供有用的功能来循环成功和失败。
if(Response.ok)
: will help help you determine if your API call is successful (Response code - 200)
if(Response.ok)
:将帮助您确定您的 API 调用是否成功(响应代码 - 200)
Response.raise_for_status()
will help you fetch the http code that is returned from the API.
Response.raise_for_status()
将帮助您获取从 API 返回的 http 代码。
Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.
下面是进行此类 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()
回答by gvir
So you want to pass data in body of a GET request, better would be to do it in POST call. You can achieve this by using both Requests.
因此,您想在 GET 请求的正文中传递数据,最好在 POST 调用中进行。您可以通过使用这两个请求来实现这一点。
Raw Request
原始请求
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": {}
}
Sample call with Requests
带有请求的示例调用
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()
回答by Shashank G
Below is the program to execute the rest api in python-
下面是在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)