502 Bad Gateway - calling scoring api endpoint - ibm-cloud

I'm using the following code from the community notebook Predict outdoor equipment purchase with IBM Watson Machine Learning:
...
<code omitted for brevity>
...
import urllib3, requests, json
​
headers = urllib3.util.make_headers(basic_auth='{}:{}'.format(username, password))
url = '{}/v2/identity/token'.format(service_path)
response = requests.get(url, headers=headers)
mltoken = json.loads(response.text).get('token')
endpoint_online = service_path + "/v2/online/deployments/"
header_online = {'Content-Type': 'application/json', 'Authorization': mltoken}
payload_online = {"artifactVersionHref": saved_model.meta.prop("modelVersionHref"), "name": "Product Line Prediction"}
​
response_online = requests.post(endpoint_online, json=payload_online, headers=header_online)
​
print response_online
print response_online.text
scoring_href = json.loads(response_online.text).get('entity').get('scoringHref')
print scoring_href
The response
<Response [201]>
{"metadata":{"guid":"4148","href":"https://ibm-watson-ml.mybluemix.net/v2/online/deployments/4148","createdAt":"2017-06-13T07:54:16.062Z","modifiedAt":"2017-06-13T07:54:16.062Z"},"entity":{"scoringHref":"https://ibm-watson-ml.mybluemix.net/32768/v2/scoring/4148"}}
https://ibm-watson-ml.mybluemix.net/32768/v2/scoring/4148
Next attempt to score:
payload_scoring = {"record":["M", 23, "Single", "Student"]}
response_scoring = requests.put(scoring_href, json=payload_scoring, headers=header_online)
​
print response_scoring.text
The response:
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<center><h1>502 Bad Gateway</h1></center>
<hr><center>nginx/1.10.1</center>
</body>
</html>

I retried the call a few minutes later and the call was successful:
{
"result":{
"PROFESSION_IX":6.0,
"GENDER_IX":0.0,
"MARITAL_STATUS_IX":1.0,
"GENDER":"M",
"features":{
"values":[
0.0,
23.0,
1.0,
6.0
]
},
"predictedLabel":"Personal Accessories",
"prediction":1.0,
...
}

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.

Multipart/mixed request for google drive bulk deletion using request npm package

I was trying to do bulk deletion of files from google drive using rest API. So i was framing the request for bulk deletion request i was able to achieve the deletion with the similar request framing method Bulk delete files on Google Drive with raw XMLHttpRequest but i was trying to achieve this without sending the body instead of sending multipart array in the request object. I am getting error 400 with following response body
<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Bad Request</H1>
<H2>Error 400</H2>
</BODY>
</HTML>
This is my request object which is failing
const _multipart = []
arrayOfFileIds.forEach((current) => {
const obj = {
body: 'Content-Type: application/http\n\n' +
'DELETE https://www.googleapis.com/drive/v3/files/' +
current + '\nAuthorization: Bearer ' + authToken
}
_multipart.push(obj)
})
const requestOptions = {
url: 'https://www.googleapis.com/batch/drive/v3',
method: 'POST',
headers: {
'Content-Type': 'multipart/mixed'
},
multipart: _multipart
}
And below request Object is working
const boundary = 'END_OF_PART'
const separation = '\n--' + boundary + '\n'
const ending = '\n--' + boundary + '--'
const requestBody = arrayOfFileIds.reduce((accum, current) => {
accum += separation +
'Content-Type: application/http\n\n' +
'DELETE https://www.googleapis.com/drive/v3/files/' +
current +
'\nAuthorization: Bearer ' + authToken
return accum
}, '') + ending
const requestOptions = {
url: 'https://www.googleapis.com/batch/drive/v3',
method: 'POST',
headers: {
'Content-Type': 'multipart/mixed; boundary=' + boundary
},
body: requestBody
multipart: _multipart
}
Modification points:
The access token can be included in the request header.
Put Content-Type of each batch request out of body.
When these points are reflected to your script, it becomes as follows.
Modified script:
const _multipart = [];
arrayOfFileIds.forEach((current) => {
const obj = {
"Content-Type": "application/http",
body: "DELETE https://www.googleapis.com/drive/v3/files/" + current + "\n",
};
_multipart.push(obj);
});
const requestOptions = {
url: "https://www.googleapis.com/batch/drive/v3",
method: "POST",
headers: {
"Content-Type": "multipart/mixed",
Authorization: "Bearer " + authToken,
},
multipart: _multipart,
};
Note:
When I tested the above modified script, no error occurs. The files can be deleted. When you tested the above script, when an error occurs, please confirm the script and the access token, again.
Reference:
request

Bad gateway on dataprep job run api

previously same api was working fine but now it shows 502 bad gateway. Here is my api call:
def hit_dataprep_job(receipe_id):
print(receipe_id)
url = "https://api.clouddataprep.com/v4/jobGroups"
body = json.dumps({"wrangledDataset": {"id": receipe_id}})
headers = {"Content-Type": "application/json","Authorization": "Bearer "+str(key)}
response = requests.post(url, data=body, headers=headers)
print(response)
print(response.json())
if response.json()['reason'] == 'JobStarted':
print('started job successfully')
Output:
<Response [502]>
{'code': 13, 'message': 'BAD_GATEWAY', 'details': [{'#type': 'type.googleapis.com/google.rpc.DebugInfo', 'stackEntries': [], 'detail': 'application'}]}
this incident is now resolved. You can subscribe to https://status.trifacta.com/ for the latest update.
Join discussions and collaborations with Dataprep users in our Community, https://community.trifacta.com/s/.

Unable to connect HP ALM API via google script

I'm trying to call HPQC API to get some reports but I'm not able to get the QCsession cookie when I call /qcbin/rest/site-session. I successfully authenticated with /qcbin/authentication-point/authenticate but I'm stuck in the next phase.
Not that I can use the API without any trouble with Postman, but my Google script doesn't work.
Here's a look at the call I'm doing :
var headers = { "Accept":"application/xml",
"Content-Type":"application/xml",
"method": "POST",
"headers" : {"Authorization": digestfull },
"muteHttpExceptions": true
};
var resp = UrlFetchApp.fetch(url,headers);
var cookie = resp.getAllHeaders();//['Set-Cookie'];//.split(';')[0].toString();
Logger.log(cookie);
//Get session cookie
param = "/hp/rest/site-session";
var url2 = hpqc + param + api_key;
var payload = "<session-parameters><client-type>REST Client</client-type></session-parameters>";
var headers2 = { "Accept":"application/json",
"Content-Type":"application/xml",
"method": "POST",
"muteHttpExceptions" : true,
"cookie" : cookie,
"body" : payload
};
resp = UrlFetchApp.fetch(url2,headers2);
The first call works fine, but the second gives me the following response :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Error 401 Authentication failed. Browser based integrations - to login append '?login-form-required=y' to the url you tried to access.</title>
</head>
<body><h2>HTTP ERROR 401</h2>
<p>Problem accessing /qcbin/rest/site-session. Reason:
<pre> Authentication failed. Browser based integrations - to login append '?login-form-required=y' to the url you tried to access.</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/>
It seems that the cookies aren't correctly sent.
Can you please help me find what is wrong with my code ? I'm sorry if it's too obvious, I'm learning to use google script.
Thank you
I changed the following code
var payload = "<session-parameters><client-type>REST Client</client-type></session-parameters>";
var headers2 = { "Accept":"application/json",
"Content-Type":"application/xml",
"method": "POST",
"muteHttpExceptions" : true,
"cookie" : cookie,
"body" : payload
};
with this and it worked
var payload = "<session-parameters><client-type>REST Client</client-type></session-parameters>";
var headers = {// "accept":"application/json",
//"contentType":"application/json",
"method": "POST",
"muteHttpExceptions" : true,
"headers" : {
"Content-type" : "application/xml",
"Accept" : "application/json",
"Cookie" : cookie
},
"payload" : payload
};
Thank you TheMaster for giving me the hint !!

A proper way to debug HTTP POST in Alamofire 4; HTTP POST not working

I have a simple piece of code that used to work below.
let params: Parameters! = ["xmldata": self.makeXML(), "reference": self.questionnaire!.jobRef!]
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default)
.validate()
.responseString { response in
print("Success: \(response.result)")
print("Response: \(response.response)")
print("Request: \(response.request)")
print("Error: \(response.error)")
// print("Response String: \(response.result.value)")
}
The code suppose to request http post to a simple web form below.
<form action="/submit?textarea=1" method="post" enctype="multipart/form-data">
<p>Paste XML data here.</p>
<input id="id_reference" maxlength="50" name="reference" type="text" placeholder="Reference.." /><br>
<textarea id="id_xmldata" maxlength="5000" name="xmldata" rows="10" cols="80"></textarea>
<br>
<input type="submit"
name="textarea_post_form"
value="Send" />
</form>
The code should just post 2 strings as parameters to the form on the website and insert data to the database. It used to work with Alamofire 3 and Swift 2, but not is not working with AlamoFire 4 and Swift 3 anymore. Now I have no idea why it is not working, and have no clue where I should begin to debug since I can't find a way to see if the proper data is sent or if there's some error at the server side.
Is there a way to fix this or perhaps trace the error?
What I got from the print statement doesn't seem to have any error...
Success: SUCCESS
[Timeline]: Timeline: { "Request Start Time": 508807148.851, "Initial Response Time": 508807148.948, "Request Completed Time": 508807148.949, "Serialization Completed Time": 508807148.950, "Latency": 0.098 secs, "Request Duration": 0.099 secs, "Serialization Duration": 0.000 secs, "Total Duration": 0.099 secs }
Response: Optional(<NSHTTPURLResponse: 0x600000225520> { URL: http://philips-survey.in.th/submit?textarea=1 } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Encoding" = gzip;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 14 Feb 2017 23:18:59 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.10 (Debian)";
"Transfer-Encoding" = Identity;
Vary = "Cookie,Accept-Encoding";
"X-Frame-Options" = SAMEORIGIN;
} })
Request: Optional(http://xxxx.com/submit?textarea=1)
Error: nil
Have you tried using uploading multipartFormData with Alamofire? Something like this:
Network.CustomManager.upload(.POST, postEndpoint, headers: headers, multipartFormData: { multipartFormData in ...