使用 python 向 RESTful API 发出请求 [英] Making a request to a RESTful API using python
问题描述
我有一个 RESTful API,我使用 EC2 实例上的 Elasticsearch 实现公开了该 API,以索引内容语料库.我可以通过从我的终端 (MacOSX) 运行以下命令来查询搜索:
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):
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/requests
或 python/urllib2
将上面的请求转换为 API 请求(不确定要使用哪个 - 一直在使用 urllib2,但听说那个要求更好......)?我是作为标题传递还是以其他方式传递?
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?
推荐答案
使用请求:
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.text
或 response.json()
(或可能检查 response.status_code
首先).查看快速入门文档此处,尤其是本节.
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.
这篇关于使用 python 向 RESTful API 发出请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!