I have a valid S9 subscription key that I use which is sufficient for visual search. And I'm using an official code. Despite all, I'm getting a Bad Request error:
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/requests/models.py", line 941, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://api.bing.microsoft.com/v7.0/images/visualsearch
import json
import os
from pprint import pprint
import requests
'''
This sample uses the Bing Visual Search API with an image URL and returns several web links
and data of the exact image and/or similar images.
Documentation: https://docs.microsoft.com/en-us/bing/search-apis/bing-visual-search/overview
'''
# Add your Bing Search V7 subscriptionKey and endpoint to your environment variables.
endpoint = "https://api.bing.microsoft.com/v7.0/images/visualsearch"
subscription_key = " "
image_url = 'https://example.com/my-image.jpg' # for example: https://example.com/my-image.jpg
# Construct the request
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
data = {'imageInfo': {'url': image_url}}
# Call the API
try:
response = requests.post(endpoint, headers=headers, data=json.dumps(data))
response.raise_for_status()
print("\nHeaders:\n")
print(response.headers)
print("\nJSON Response:\n")
pprint(response.json())
except Exception as ex:
raise ex
I tried the different ways of uploading an image instead of a URL. For example, like the code below but I got the very same error:
import json
import os
from pprint import pprint
import requests
'''
This sample uses the Bing Visual Search API with a local, query image and returns several web links
and data of the exact image and/or similar images.
Documentation: https://docs.microsoft.com/en-us/bing/search-apis/bing-visual-search/overview
'''
# Add your Bing Search V7 subscriptionKey and endpoint to your environment variables.
endpoint = "https://api.bing.microsoft.com/v7.0/images/visualsearch"
subscription_key = " "
image_path = 'photo.jpg' # for example: my_image.jpg
# Construct the request
headers = {'Ocp-Apim-Subscription-Key': subscription_key, 'Content-Type': 'multipart/form-data'}
file = {'image' : ('photo.jpg', open(image_path, 'rb'))} # Use the actual name of the image file, with the extension
# Call the API
try:
response = requests.post(endpoint, headers=headers, files=file)
response.raise_for_status()
print("\nHeaders:\n")
print(response.headers)
print("\nJSON Response:\n")
pprint(response.json())
except Exception as ex:
raise ex