要制作一个RESTful API使用Python的请求 [英] Making a request to a RESTful API using python

查看:132
本文介绍了要制作一个RESTful API使用Python的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我一直在使用的EC2实例Elasticsearch的实现索引内容语料库露出一个RESTful 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 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":{}}'

我如何把上面到使用蟒蛇/请求蟒蛇/ 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 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.get(url, data=data)

根据什么样的回应你的API返回,您将可能想看看 response.text response.json()(也可能是检查 response.status_ code 第一)。请参阅快速入门文档这里,尤其是<一个href=\"http://docs.python-requests.org/en/latest/user/quickstart/#more-complicated-post-requests\">this部分。

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.

这篇关于要制作一个RESTful API使用Python的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆