Microsoft Face API [find similar] api key error - python-3.x

So I'm trying to follow The microsoft face api documentation here for the "FindSimilar" feature. There is an example at the bottom of the page where I use this code:
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '{api key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/face/v1.0/findsimilars?%s" % params, "{body}",
headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
I'm getting an error where it tells me my subscription key is invalid, but I checked my azure account status and I see no issues:
b'\n\t\t\t\t\t{"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}\n \t\t'

Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key.
It indicates that Invalid subscription Key or user/plan is blocked. I recommand that you could check the APi Key.
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '3c658abc64b348c1a5...',
}

Related

Get a SAS on a azure snapshot - Using Azure Compute API

I am trying to generate the SAS URI for one of the snapshot exist on resource group using microsoft provided API.
Below is the snippet code:
url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{target_resource_group}/providers/Microsoft.Compute/snapshots/{snap_name}/beginGetAccess"
headers = {'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json'}
params = {'api-version': '2021-12-01'}
body= {
"access": "Read",
"durationInSeconds": 3000
}
json_body= json.dumps(body, indent=2)
accessSAS=requests.post(url, headers=headers, params=params, data=json_body, verify=False)
But I am receiving the response as <Response [202]>.
Could anyone help me with the issue.
Response 202 means that Azure accepts your request but it is handling your request. It is an asynchronous operation. Therefore, the response header will give you another url for getting the result. You can refer the following link to get what you want.
https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/async-operations

Add (AWS Signature) Authorization to python requests

I am trying to make a GET request to an endpoint which uses AWS Authorization. I made request using postman, It works. But when i tried following method in python, it's giving error.
CODE
url = 'XXX'
payload = {}
amc_api_servicename = 'sts'
t = datetime.utcnow()
headers = {
'X-Amz-Date': t.strftime('%Y%m%dT%H%M%SZ'),
'Authorization': 'AWS4-HMAC-SHA256 Credential={}/{}/{}/{}/aws4_request,SignedHeaders=host;x-amz-date,Signature=3ab1067335503c5b1792b811eeb84998f3902e5fde925ec8678e0ff99373d08b'.format(amc_api_accesskey, current_date, amc_api_region, amc_api_servicename )
}
print(url, headers)
response = requests.request("GET", url, headers=headers, data=payload)
ERROR
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method.
Please point me in the right direction.
import boto3
client = boto3.client('sts')
respone=client.assume_role(RoleArn='your i am urn',RoleSessionName='PostmanNNN')

URLFetch does not support granular timeout settings, reverting to total or default URLFetch timeout

We have an application (app-a) that is on python2.7 standard google app engine. We are attempting to do programmatic authentication to access another application (app-b) using service account based on the example here. App-b is on python3.7 standard google app engine.
When we do the iap authenticated call we get the following error in the logs of App-A.
resp = requests.request(
method, url,
headers={'Authorization': 'Bearer {}'.format(
google_open_id_connect_token)}, **kwargs)
AppEnginePlatformWarning: urllib3 is using URLFetch on Google App Engine sandbox instead of sockets. To use sockets directly instead of URLFetch see https://urllib3.readthedocs.io/en/latest/reference/urllib3.contrib.html.
AppEnginePlatformWarning: URLFetch does not support granular timeout settings, reverting to total or default URLFetch timeout.
The requests.request errors with
Exception("Bad response from application: 500 / {'content-type': 'text/html', 'x-cloud-trace-context':
In App-B we are trying to receive the data sent from app-a.
json.loads(request.data)
We get the following error in the logs of app-b.
in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/opt/python3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This leads me to believe that app-a is able to call app-b successfully. But for some reason it is not able to pass the data. Please help.
UPDATE -
Per suggestion to use HTTPlib we tried this.
payload = {
'test_data' : "data_test"
}
payload_json_dumps = json.dumps(payload)
conn = httplib.HTTPConnection(host)
conn.request("POST", path, payload_json_dumps, request_headers)
resp = conn.getresponse()
Added the following to app.yaml.
env_variables:
GAE_USE_SOCKETS_HTTPLIB : 'true'
In App-B we changed to
from flask import request
#app.route('url', methods = ['GET','POST'])
def content_from_client():
if (request.data):
data_received = request.get_json()
We are still not able to get the data on App-B. We get
AttributeError("'NoneType' object has no attribute 'get'")
UPDATE -
Changed the header formation and got it working.
request_headers = {
"Content-Type": 'application/json',
"follow_redirects": False,
"X-Appengine-Inbound-Appid": "app-A.appspot.com",
"Connection": "keep-alive",
'Authorization': 'Bearer {}'.format(google_open_id_connect_token)
}
AppEnginePlatformWarning is raised by urllib3 which is used by the requests library.
Urllib3 provides a pool manager that uses URL Fetch API by default. Sometimes though may not be the best option for your use case. A solution is to use sockets instead. In order to do that you have to configure your app.yamland include the following field:
env_variables:
GAE_USE_SOCKETS_HTTPLIB : 'true'
You may also find this documented in Google documentation.
As of the error on your app-B I would use response.json() method, requests builtin method instead of json.loads() as it detects automatically which decoder to use.
Let me know if this was helpful.
Per suggestion above the following helped solve the issue. Changed to httplib instead of urlfetch.
conn = httplib.HTTPConnection(host)
conn.request("POST", path, payload_json_dumps, request_headers)
resp = conn.getresponse()
Added the following to app.yaml -
env_variables:
GAE_USE_SOCKETS_HTTPLIB : 'true'
Changed header formation to -
request_headers = {
"Content-Type": 'application/json',
"follow_redirects": False,
"X-Appengine-Inbound-Appid": "app-A.appspot.com",
"Connection": "keep-alive",
'Authorization': 'Bearer {}'.format(google_open_id_connect_token)
}

Microsoft Emotion Video API Python 3.2

I am trying to analyze a video via Emotion API by Microsoft using Python 3.2
I am encountering the following error:
b'{ "error": { "code": "Unauthorized", "message": "Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key." } }'
I am using Emotion API subscription key (i have also used the Face API key, and computer vision key just in case).
Code:
import http.client, urllib.request, urllib.parse, urllib.error, base64
headers = {
# Request headers
'Ocp-Apim-Subscription-Key': '{subscription key}',
}
params = urllib.parse.urlencode({
})
try:
conn = http.client.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("GET", "/emotion/v1.0/operations/{oid}?%s" % params, "{body}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
Your code works. Just make sure you wait 10 minutes after generating the API key so that it starts working (it says so in the Azure Portal).
Also, in general for Cognitive Services, make sure that the API key you have corresponds to the region you're trying to hit (West US, etc.)

How to access secured soap endpoint in nodejs

Here is a service I need to access from nodejs:
https://test.matrikkel.no/endringsloggapi_v3/endringslogg/EndringsloggWebService?WSDL
I have the username and password.
How can I connect to service and issue requests?
Tried using 'soap' package in nodejs, but cannot understand where do I have to pass username and password.
Here is a working version done in python. Can anyone show how it works in nodejs.
import httplib, urllib
params = {}
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
"Authorization": "Basic 123"}
conn = httplib.HTTPSConnection("test.matrikkel.no")
conn.request("GET", "/endringsloggapi_v3/endringslogg/EndringsloggWebService?WSDL", params, headers)
response = conn.getresponse()
# print response.status, response.reason, response.read() to verify that call went through
conn.close()
Best Regards,
Edijs

Resources