Microsoft Face API [Find Similar]接口密钥错误问题求助
Hey there, let's work through that API key error you're hitting when using the Face API's Find Similar functionality. Here are the most common fixes to get you back on track:
1. Replace the placeholder API key correctly
Looking at your code, you've got '{api key}' in the headers—this is just a placeholder. You need to replace that entire string (including the curly braces) with your actual Face API key from the Azure portal. For example:
headers = { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': 'abc123-your-real-api-key-xyz789', }
Make sure there are no extra spaces, quotes, or leftover curly braces in the key value.
2. Match your API key to the correct region
Your code uses the westus.api.cognitive.microsoft.com endpoint. Double-check that the API key you're using was created for a Face API resource in the West US region in Azure. Keys are region-locked—using a key from a different region (like East US) will throw an authentication error.
3. Verify the key is valid and active
Head over to the Azure portal, navigate to your Face API resource, and check the Keys and Endpoint section:
- Ensure you're using either the Primary or Secondary key (both work, so if one gives issues, try the other)
- Confirm the resource hasn't been deleted or expired (most Azure resources don't expire automatically, but it's worth checking)
- Don't confuse the resource ID with the API key—they're two different values; you need the actual key string.
4. Check the request header spelling
The header name Ocp-Apim-Subscription-Key is case-sensitive. Make sure you haven't misspelled it (e.g., lowercase "key" at the end, or missing a hyphen). Even a tiny typo here will cause an authentication failure.
5. Ensure your full request is complete
Your code snippet cuts off before the request body—just a reminder that the Find Similar API requires a valid JSON body with parameters like faceId, faceIds, and mode. A complete, working example might look like this:
import http.client, urllib.request, urllib.parse, urllib.error, base64 import json headers = { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': 'your-real-api-key', } params = urllib.parse.urlencode({}) # Example request body for Find Similar body = json.dumps({ "faceId": "target-face-id-here", "faceIds": ["comparison-face-id-1", "comparison-face-id-2"], "maxNumOfCandidatesReturned": 3, "mode": "matchPerson" }) try: conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com') conn.request("POST", "/face/v1.0/findsimilar?%s" % params, body, headers) response = conn.getresponse() data = response.read() print(data.decode("utf-8")) conn.close() except Exception as e: print("[Errno {0}] {1}".format(e.errno, e.strerror))
Sometimes authentication errors can be a red herring for other issues like an invalid request body, but fixing the key-related issues first is the priority.
内容的提问来源于stack exchange,提问作者Gabriel

