Trying to run code in IBM Cloud Functions - ibm-cloud

I have following code I am trying to run in IBM function to get billing data out:
iam_token = 'Bearer eyJraWQiOiIyMDE3MTAzMC0wM****'
def processResourceInstanceUsage(account_id, billMonth):
METERING_HOST = "https://metering-reporting.ng.bluemix.net"
USAGE_URL = "/v4/accounts/"+account_id + \
"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url = METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
print("\n\nResource instance usage for first 100 items")
return response.json()
processResourceInstanceUsage('*****', '11')
For some reason, I keep on getting 201 unauthorized error. I tried creating iam_token many times. It still gives the same error.

There are few things that should be taken care in the code you provided.
The month you are passing is wrong. It should be in YYYY-MM format.
account_id should be the id next to your Account name when you run ibmcloud target
For IAM token, run this command ibmcloud iam oauth_tokens. If you want to generate access token using your Platform API Key, refer to this link. The word Bearer is not required as this is not an authorization token.
Once you have all this in place, create an IBM Cloud function (Python 3), add the below code, pass the account_id and token and invoke the action to see the result . IBM Cloud function expects a dictionary as an input/parameter and JSON as response
import sys
import requests
def main(dict):
METERING_HOST="https://metering-reporting.ng.bluemix.net"
account_id="3d40d89730XXXXXXX"
billMonth="2018-10"
iam_token="<IAM_TOKEN> or <ACCESS_TOKEN>"
USAGE_URL="/v4/accounts/"+account_id+"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url=METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response=requests.get(url, headers=headers)
print ("\n\nResource instance usage for first 100 items")
return { 'message': response.json() }
This worked for me and returned a JSON with region-wise billing data.
Reference: https://stackoverflow.com/a/52333233/1432067

Related

Failed to upload apk via Connect API

I am working on a python script to update the app on Huawei AppGallery via Connect API.
I successfully fetched the token and upload URL but not able to upload the APK/AAB.
Getting this error -
{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}
Here's my python script
def uploadAAB(uploadUrl, authCode, accessToken, appId):
try:
fileName = 'latest_hms.apk'
headers = {
"Authorization": "Bearer " + accessToken,
"accept": "application/json",
"client_id": clientId,
"Content-Type": "multipart/form-data"
}
uploadBody = {
"authCode": authCode,
"fileCount": 1
}
with open(aabPath, 'rb') as f:
f.seek(0, os.SEEK_END)
print(f.tell()) # printing the correct size
first_phase = requests.post(
uploadUrl,
files={fileName: f},
data=uploadBody,
headers=headers)
if first_phase.status_code == 200:
print(first_phase.json())
body = {
'fileType': 5,
'files': [{
'fileName': fileName,
'fileDestUrl': first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['fileDestUlr'],
'size': str(first_phase.json()['result']['UploadFileRsp']['fileInfoList'][0]['size'])
}]
}
fileHeader = {
'client_id': clientId,
'Authorization': 'Bearer ' + accessToken,
}
params = {
'appId': appId,
}
second_phase = requests.put(
BASE_URL + "/publish/v2/app-file-info",
headers=fileHeader,
json=body,
params=params)
print(second_phase.json())
except (requests.exceptions.RequestException, requests.exceptions.HTTPError, KeyError) as err:
stopOnError(repr(err))
Please help me out here.
{'result': {'CException': {'errorCode': 70001405, 'errorDesc': 'get no file from request!'}, 'resultCode': '70001405'}}
This error means there is no file in the request. the file is not include successfully in the request. Please make sure the file is achievable.
It seems Huawei made a change to the AppGallery API in February 2022. I don't know if this was intentional, but you must now specify a filename of "file" instead of your original filename (which worked before). See my pull request on Natgho's HMS-Publishing-API code.

Using Smartsheet API with Swift

Is it possible to use Alamofire like so:
AF.request("https://api.smartsheet.com/2.0/sheets/",method: .get).responseJSON { Data in debugPrint(Data.result) }
in Swift to interact with the Smartsheet API?
I'd hope that swapping out the current https with an reasonable one would do what I want.
I would like to get information from the API. The error thrown is that I don't have authorization for the API:
Swift.Result<Any, Alamofire.AFError>.success({ errorCode = 1004; message = "You are not authorized to perform this action."; refId = 1ca40zco0itdd; }).
I just needed to understand end points better and read the documentation on Alamofire. I changed my code to the following and it worked!
let headers: HTTPHeaders = [
"Authorization": "Bearer " + api_key_smartsheet,
"Accept": "application/json"
]
AF.request("https://api.smartsheet.com/2.0/sheets/?includeAll=True", method: .get,headers: headers).responseJSON { response in
debugPrint(response)
}'''

Paypal UNSUPPORTED_MEDIA_TYPE

I am trying to get an access token from paypal's authorization api.
When I make post request to the api I get UNSUPPORTED_MEDIA_TYPE i.e. 415 response.
Below is the snippet that I used.
const auth = await fetch(PAYPAL_OAUTH_API, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${ basicAuth }`
},
body: JSON.stringify({"grant_type": "client_credentials"})
});
I have fixed my issue by setting Content-Type to application/x-www-form-urlencoded.
My guess is paypal accepts only application/x-www-form-urlencoded for authorization api.
I ran into same issue, and the solution is following (using Postman):
Select POST
Add Token into Authorization, type is Bearer-Token
Select Content-Type: application/json in headers
Use RAW as body, and in TEXT dropdown, select JSON (application/JSON)
Copy body as raw object and change info accordingly.
Step 4 and 5 are what solved the error, you must send raw json object.

Error while generating access_token using Ebay 's REST API - Python requests

I'm trying to use the ebay REST-API for the first. I am simply trying to generate an access_token using the client credentials grant-request. I followed the instructions here https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html
HTTP method: POST
URL (Sandbox): https://api.sandbox.ebay.com/identity/v1/oauth2/token
HTTP headers:
Content-Type = application/x-www-form-urlencoded
Authorization = Basic <B64-encoded_oauth_credentials>
Request body (wrapped for readability):
grant_type=client_credentials&
redirect_uri=<RuName-value>&
scope=https://api.ebay.com/oauth/api_scope
I'm getting this error: {'error': 'invalid_client', 'error_description': 'client authentication failed'} and my code looks like this:
path = 'https://api.sandbox.ebay.com/'
app_json = 'application/json'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': base64.b64encode(b'Basic CLIENT_ID:CLIENT_SECRET')
}
payload = 'grant_type=client_credentials&redirect_uri=Searchez&scope=https://api.ebay.com/oauth/api_scope'
def get_oath_token():
url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token'
r = requests.post(url, headers=headers, data=payload)
print(r.json())
get_oath_token()
What do I have configured incorrectly? Thanks.
You're base64encoding "Basic " and shouldn't be.
The doc says just encode your Client ID + ":" + Client Secret, and leave the word "Basic" and the space that follows it alone.
In your code, i can see sandbox endpoint URI but in the request body scope, you have used production URL, instead of sandbox

loopback access_token not found

followed by the access documentation
both are not working by using
Authorization Header
Query Parameter
Using the latest version of loopback 2.1.X.
I turned off the email verification and successfully got the AccessToken object from the initial login. The header and the query request are not working now.
ACCESS_TOKEN=6Nb2ti5QEXIoDBS5FQGWIz4poRFiBCMMYJbYXSGHWuulOuy0GTEuGx2VCEVvbpBK
Authorization Header
curl -X GET -H "Authorization: $ACCESS_TOKEN" \
http://localhost:3000/api/widgets
Query Parameter
curl -X GET http://localhost:3000/api/widgets?access_token=$ACCESS_TOKEN
In header pass key as authorization not ACCESS_TOKEN
In query params pass key as accessToken not access_token
Here is what works for me in Angular 2 :
initRequestOptions(accessToken:any) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Authorization', accessToken);
return new RequestOptions({headers: headers});
}
makeRequest(accessToken:any){
let options = this.initRequestOptions(accessToken);
this.http.get('http://' + apiUrl + '/api/MyModel, options)
.subscribe(
//...
)
}
So basically you need to create a headers object , add an 'Authorization' item whoes value is the access token , and use the headers object to create a RequestOptions object to be inserted in the request.
Also loopback explorer passes the access token as a url encoded parameter so this should work too :
http://localhost:3000/api/MyModel?access_token=X3Ovz4G1PfmPiNGgU5YgORPwPGLaVt9r8kU7f4tu1bDMyA4zbqiUEgeDAC3qkZLR