我想我的问题是相对简单和天真的,但我是新手使用REST,所以我会感激任何帮助或提示。
我试图用urllib (或另一个不需要安装的Python库)发送请求。根据它们的指南,格式是:
POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEYJSON请求格式是:
{
"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的另一个位置?
发布于 2019-06-28 11:47:16
这对我来说很管用:
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)发布于 2019-03-26 10:48:30
如果需要将Request Body与URL一起发送,则可以使用CURL。为了测试REST,有一个名为邮递员的著名软件。通过使用它,您可以发送请求并接收响应。
卷曲,
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,您可以给出这些值,并得到结果。
给URL,
https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY选择HTTP方法,
POST并在raw字段下添加请求体并选择JSON(application/json),
{
"requests":[
{
"image":{
"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
},
"features":[
{
"type":"LABEL_DETECTION",
"maxResults":1
}
]
}
]
}发布于 2019-10-10 22:54:14
这是经过测试和工作的完美。
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.texthttps://stackoverflow.com/questions/55354832
复制相似问题