Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python发送RESTAPI(Google Vision的API)请求?_Python_Rest_Api_Post_Google Vision - Fatal编程技术网

如何使用python发送RESTAPI(Google Vision的API)请求?

如何使用python发送RESTAPI(Google Vision的API)请求?,python,rest,api,post,google-vision,Python,Rest,Api,Post,Google Vision,我想我的问题相对简单和幼稚,但我对使用RESTAPI是新手,所以如果有任何帮助或提示,我将不胜感激 我正在尝试使用urllib(或我不需要安装的另一个Python库)发送请求。 根据他们的情况,格式为: POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY 最重要的是: 当我尝试在浏览器的URL行中发送以下文本(仅用于测试)时: https://vision.googleapis.com/v1/images

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

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

POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
最重要的是:

当我尝试在浏览器的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发送
请求正文
,您可以使用
CURL
。为了测试RESTAPI,有一个著名的软件叫做。通过使用它,您可以发送请求并接收响应

卷曲

使用POSTMAN,您可以将这些值赋给它并获得结果

给出URL

https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
选择HTTP方法作为

POST
并在
raw
字段下添加请求主体,然后选择
JSON(application/JSON)

这对我很有用:

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)

这是测试和工作完美

            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

你需要什么?发送请求时是否需要软件来测试此URL?我不确定是否理解您的问题。我想用Python的urllib进行API调用。我想使用API来存储和处理输出。我可以在浏览器中通过简单的URL请求发出此请求,还是必须使用POSTMAN?使用POSTMAN。这是一个轻量级软件。否则,您可以使用Firefox。阅读第二个答案。
{
  "requests":[
    {
      "image":{
        "content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
      },
      "features":[
        {
          "type":"LABEL_DETECTION",
          "maxResults":1
        }
      ]
    }
  ]
}
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)
            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