使用 python 向 RESTful API 发出请求

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

我有一个 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 '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/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 = '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 返回的响应类型,您可能需要查看 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 发出请求

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

发布评论

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

>www.elefans.com

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