使用python向RESTful API发出请求

编程入门 行业动态 更新时间:2024-10-27 05:30:22
本文介绍了使用python向RESTful API发出请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个RESTful API,我已经在EC2实例上使用Elasticsearch的一个实现来暴露了索引一个内容的语料库。我可以通过从我的终端(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 'ES_search_demo/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将其转换为API请求/ request 或 python / urllib2 (不知道要去哪一个 - 一直在使用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 = 'ES_search_demo/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返回的响应类型,您可能需要查看 respo nse.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发出请求

本文发布于:2023-10-09 18:51:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476492.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:python   RESTful   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!