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

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

Related

REST API Post method Recursive run returning Different data-probably data with error in Azure Functions

I am using REST API Post method and deployed to Azure functions .The First Run[immediate run post changes and deployment to azure] is success and subsequent runs are showing error in data and counts are not same as the first Run.Following is the code snippet that I am using.
` def __init__(self):
url = "https://login.microsoftonline.com/abcdefgh12345/oauth2/v2.0/token"
payload = 'grant_type=client_credentials&scope=api%AB1234567890CDE%.default'
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + "ABCDEFG",
'Cookie': 'XYZMANOP'
}
response = requests.request("POST", url, headers=headers, data=payload)
self.auth = response.json()`
Then I am using self.auth in other methods
Why is this happening and what is the solution???PS:When I try the code in local it works like a charm.
I tried extracting the access_token and added it in subsequent functions. But the result is also the same. Also I changed the schedule since access_token is valid only for 3600s and rescheduled to execute post 2 hours.But its returning same result

HP ALM API : Attaching file to run step through ALM REST API not working

We have fetched Run Steps details using ALM REST API.
(for reference ALM API Documentation
Same question is being asked in ALM community, Community Microfocus ALM
https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/runs/<run-id>/run-steps
and passed Run Step id to below API and tried to attach file using POST and PUT.
https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/runs/<run-id>/run-steps/<run-step-ID>/attachments
we are getting 404 response.
Bad request.
URL = "https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/runs/<run-id>/run-steps/<step-id>/attachments"
METHOD = "PUT"
HEADERS = {
'cache-control': "no-cache",
"Slug": "some.html",
'Content-Type': "application/octet-stream"
}
def attach_to_run_step():
f = open("/path/to/some.html", "rb")
response = requests.put(URL, headers=HEADERS, cookies=cookies, data=f.read())
print(response.content)
Expected : 200 response
Actual : 404 status code
I think you need to use the following URL for your POST request:
https://some.almserver.com/qcbin/rest/domains/DOMAIN/projects/PROJECT/run-steps/<run-step-id>/attachments (remove /runs/<run-id>)
Update:
Here is an example, generated from Postman:
import requests
url = "http://xxx.xxx.xxx.xxx:8080/qcbin/rest/domains/DEFAULT/projects/demo/run-steps/1263/attachments"
payload="<file contents here>"
headers = {
'Content-Type': 'application/octet-stream',
'Slug': '1.jpg',
'Cookie': 'JSESSIONID=<session>; ALM_USER=2e69...; LWSSO_COOKIE_KEY=PTKYM...; QCSession=MTQwM...; XSRF-TOKEN=3dfa4...'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
P.S. We are developing commercial platform for integrating various test frameworks with ALM, which is called Agiletestware Bumblebee, so you might want to have a look at it.

Error calling CF API login one time passcode

I am working with the CF API RESTful services. Trying to get an access token from cloud foundry's UAA API using https://login..../oauth/token web method.
I have verified that headers & body content is correct, but calling the api always returns a 400 error code with message missing grant type.
I have implemented this call in Objective-C, Swift & now Python. All tests return the same result. Here is my code example in Python:
import json
import requests
import urllib
params = {"grant_type": "password",
"passcode": "xxx"
}
url = "https://login.system.aws-usw02-pr.ice.predix.io/oauth/token"
headers = {"Authorization": "Basic Y2Y6", "Content-Type": "application/json", "Accept": "application/x-www-form-urlencoded"}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(rjson)
Each time I run this, I get the response
error invalid request, Missing grant type
Any help would be greatly appreciated.
Your code mostly worked for me, although I used a different UAA server.
I had to make only one change. You had the Accept and Content-Type headers flipped around. Accept should be application/json because that's the format you want back, and Content-Type should be application/x-www-form-urlencoded because that's the format you are sending.
See the API Docs for reference.
import json
import requests
import urllib
import getpass
UAA_SERVER = "https://login.run.pivotal.io"
print("go to {}/passcode".format(UAA_SERVER))
params = {
"grant_type": "password",
"passcode": getpass.getpass(),
}
url = "https://login.run.pivotal.io/oauth/token"
headers = {
"Authorization": "Basic Y2Y6",
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json"
}
encodeParams = urllib.parse.urlencode(params)
response = requests.post(url, headers=headers, data=encodeParams)
rjson = response.json()
print(json.dumps(rjson, indent=4, sort_keys=True))
I made a couple other minor changes, but they should affect the functionality.
Use getpass.getpass() to load the passcode.
Set the target server as a variable.
Pretty print the JSON response.
The only other thing to note, is that the OAuth2 client you use must be allowed to use the password grant type. It looks like you're using the same client that the cf cli uses, so if your UAA server is part of a standard Cloud Foundry install that is likely to be true, but if it still doesn't work for you then you may need to talk with an administrator and make sure the client is set up to allow this.

Request too large error making a request to App Engine

I have an app on App Engine Flex using the Python 3 runtime. I get the base64 encoded byte string of a resume file from Google Storage with the code below.
storage_client = storage.Client(project=[MYPROJECT])
bucket = storage_client.get_bucket([MYBUCKET])
blob = bucket.blob([MYKEY])
resume_file = blob.download_as_string()
resume_file = str(base64.b64encode(resume_file))[2:-1]
I send that as part of my request parameters like so:
headers = {'Authorization': 'Bearer {}'.format(signed_jwt),
'content-type': 'application/json'}
params = {'inputtype': 'file',
'resume': resume_file}
response = requests.get(HOST, headers=headers, params=params)
However, I get the following error:
Error 413 (Request Entity Too Large)
Your client issued a request that was too large
That's all we know
App Engine has a file size limit of 32MB. However, my file is only 24KB. How can I fix this error?
I had to change my application to accept POST requests instead of GET requests.
Previously, I was sending the resume as a parameter. I'm now sending it as data:
payload = json.dumps({
'inputtype': inputtype,
'resume': inputresume
})
response = requests.post(HOST, headers=headers, data=payload)
I am using Flask. Previously I was reading in the params using:
request.args.get('resume')
I changed it to:
request.get_json().get('resume')
This is an extension of the question/answer here

Microsoft Face API [find similar] api key error

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...',
}

Resources