当前位置: 首页 > 知识库问答 >
问题:

使用Python向RESTful API发出请求

卜弘文
2023-03-14

我有一个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": {}
}'

我如何使用python/requests或python/urllib2将上述内容转换为API请求(不确定应该选择哪一个-一直在使用urllib2,但听说请求更好?我是作为标题传递还是以其他方式传递?

共有3个答案

商辰钊
2023-03-14

因此,您想在GET请求的正文中传递数据,最好是在POST调用中进行。您可以通过使用这两个请求来实现这一点。

原始请求

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": {}
}

带有请求的示例调用

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()
仲孙逸明
2023-03-14

使用请求和json使其变得简单。

  1. 调用API
  2. 假设API返回一个JSON,使用json.loads函数
  3. 将JSON对象解析为Python语句
  4. 遍历判决以提取信息。

请求模块为您提供了有用的函数来循环成功和失败。

if(Response.ok):将帮助您确定API调用是否成功(响应代码-200)

<代码>响应。raise\u for\u status()将帮助您获取从API返回的http代码。

下面是进行此类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()
萧飞
2023-03-14

使用请求:

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返回的响应类型,您可能需要查看响应。文本或响应。json()。请参阅此处的快速入门文档,尤其是本节。

 类似资料:
  • 问题内容: 我有一个RESTful API,我已在EC2实例上使用Elasticsearch的实现公开了索引内容的语料库。我可以通过从终端机(MacOSX)运行以下命令来查询搜索: 如何使用或(不确定要使用哪个请求- 一直在使用urllib2,但听说请求更好…)将以上转换为API请求?我是否可以通过标题? 问题答案: 使用请求: 然后,根据您的API返回的响应类型,您可能需要查看或(或可能先检查)

  • 问题内容: 我正在尝试向以下页面发出POST请求:http : //search.cpsa.ca/PhysicianSearch 为了模拟单击“搜索”按钮而不填写任何表单,该表单会将数据添加到页面。通过在chrome开发人员工具中查看“网络”标签时点击按钮,我获得了POST标头信息。我之所以发布此信息,而不是仅仅从其他类似问题中复制解决方案,是因为我认为我可能没有获得正确的标题信息。格式是否正确,

  • 问题内容: 我需要在应用程序中使用SOAP端点进行请求。因此,我需要在请求中传递xml数据,并在响应中接收xml数据。 我已将axios帖子与json数据一起使用,但如何将其用于xml?PFB我正在使用相同的代码,但是它不起作用。 JSON发布请求: TIA,如果您有任何经验,请分享。 问题答案: 此代码有助于提出肥皂请求

  • 问题内容: 我想使用Tor向网页发出多个GET请求。我想为每个请求使用不同的ipaddress。 使用此,我提出了一个请求。如何更改ipaddress来做另一个? 问题答案: 这是您要使用的代码(使用来下载词干包) 祝你好运,希望能成功。

  • thinkphp5编写的restful风格的API,集API请求处理,权限认证,自动生成文档等功能

  • 问题内容: 是否可以使用Python的库发送SOAP请求? 问题答案: 确实有可能。 这是一个使用普通请求lib调用Weather SOAP Service的示例: 一些注意事项: 标头很重要。没有正确的标头,大多数SOAP请求将无法工作。可能是更 正确 使用的标头(但weatherservice更喜欢 这将以xml字符串形式返回响应-然后,您需要解析该xml。 为简单起见,我以纯文本形式包含了该