【问题标题】:How to send rest API (Google Vision's API) request with python?如何使用 python 发送 REST API(Google Vision 的 API)请求?
【发布时间】:2023-03-08 16:38:01
【问题描述】:

我想我的问题相对简单和幼稚,但我是使用 REST API 的新手,所以我将不胜感激任何帮助或提示。

我正在尝试使用 urllib(或我不需要安装的另一个 Python 库)发送请求。 根据他们的guide,格式为:

POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY

JSON request format 是:

{
  "requests":[
    {
      "image":{
        "content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
      },
      "features":[
        {
          "type":"LABEL_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
}

当我尝试在浏览器的 URL 行中发送以下文本(仅用于测试)时:

https://vision.googleapis.com/v1/images:{
  "requests":[
    {
      "image":{
        "content":"/9j/7QBEUGhvdG9eYxxxzj/Coa6Bax//Z"
      },
      "features":[
        {
          "type":"LABEL_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
}?key=my_api_key

不幸的是,我收到了 404 错误。

我该怎么办?我应该使用任何库来生成请求吗?还是应该将 JSON 请求放在 URL 中的另一个位置?

【问题讨论】:

  • 你需要什么?发送请求时是否需要软件来测试此 URL?
  • 我不确定我是否理解您的问题。我想用 Python 的 urllib 进行 API 调用。我想使用 API 来存储和处理输出。

标签: python rest api post google-vision


【解决方案1】:

如果您需要发送带有 URL 的Request Body,您可以使用CURL。为了测试 REST API,有一个名为POSTMAN 的著名软件。通过使用它,您可以发送请求并接收响应。

卷曲,

curl -v -H "Content-Type: application/json" -X POST \
     -d '{"image":{"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"}, "features":[{"type":"LABEL_DETECTION","maxResults":1}]}' https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY

使用 POSTMAN 你可以给它这些值并得到结果。

给出网址,

https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY

选择 HTTP METHOD 为,

POST

并在raw字段下添加REQUEST BODY并选择JSON(application/json)

{
  "requests":[
    {
      "image":{
        "content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
      },
      "features":[
        {
          "type":"LABEL_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
}

【讨论】:

  • 我可以在浏览器中使用简单的 URL 请求发出这个请求还是必须使用 POSTMAN?
  • 使用邮递员。这是一个轻量级的软件。否则你可以使用Firefox。阅读第二个答案。 stackoverflow.com/questions/4797534/…
【解决方案2】:

这对我有用:

import base64
import requests
import json

URL = "https://vision.googleapis.com/v1/images:annotate?key=YOUR_TOKEN"

#image to base64, which is a long long text
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read())

#make api call
def image_request(image_path):
    data = {
            "requests":[
                        {
                        "image":{
                            "content":encode_image(image_path)
                                },
                        "features":[
                                    {
                                    "type":"LABEL_DETECTION", #other options: LABEL_DETECTION FACE_DETECTION LOGO_DETECTION CROP_HINTS WEB_DETECTION
                                    "maxResults": 10
                                    }
                                   ]
                        }
                    ]
}
    r = requests.post(URL, json = data)
    return r.text


#arg = path of image
def main(argv):
    api_answer = json.loads(image_request(argv[1]))
    try:
        rows = api_answer['responses'][0]['labelAnnotations']
    except:
        print(file_to_proccess)
        print(api_answer)
    data = []
    for item in rows:
        data.append([item['mid'], item['description'], item['score'], item['topicality']])

    # save somewhere the data list...

if __name__ == "__main__":
    main(sys.argv)

【讨论】:

    【解决方案3】:

    这已经过测试并且工作完美

                import base64
                import requests
                import json
    
                url = "https://vision.googleapis.com/v1/images:annotate"
    
                querystring = {"key":".........."}
                headers = {
                        'Content-Type': "application/json",
                        }
                def encode_image(image_path):
                    with open(image_path, "rb") as image_file:
                        return base64.b64encode(image_file.read())
    
                def image_request(image_path):
    
                    payload = '{  \"requests\":[    {      \"image\":{        \"content\":\"'+encode_image(image_path).decode('utf-8')+'"      },      \"features\":[        {          \"type\":\"TEXT_DETECTION\" }      ]    }  ]}'
                    response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
    
                    return response.text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2017-03-05
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2019-03-13
      相关资源
      最近更新 更多