Maximo REST API : MXAPIMeter Create Meter Failed - api

I tried to create Meter using HTTP POST olscmeter and mxapimeter.
My python code is
postReq = mxURL + "/maximo/oslc/os/oslcmeter"
headers = {'Content-type': 'application/json', 'maxauth' : maxAuth}
body = {'METERNAME' : meterName, 'METERTYPE' : meterType, 'DESCRIPTION' : description, 'READINGTYPE' : 'ACTUAL', 'MEASUREUNITID' : ''}
print(postReq, headers, body)
r = requests.post(url = postReq, headers = headers, json = body)
print(r.status_code, r.text)
And I kept encountering the under-mentioned error.
400
{"oslc:Error":
{"oslc:statusCode":"400",
"errorattrname":"metername",
"spi:reasonCode":"BMXAA4195E",
"errorobjpath":"meter",
"correlationid":null,
"oslc:message":"BMXAA4195E - A value is required for the Meter field on the METER object.",
"oslc:extendedError":{"oslc:moreInfo":{"rdf:resource":"http:\/\/mx7vm\/maximo\/oslc\/error\/messages\/BMXAA4195E"}
}
}
}
Any advice on what I have missed?
Thank you.

BMXAA4195E is just a generic error that means a required field is missing.
I have never generated MBOs this way, but I think the issue is that JSON keys are case sensitive. In all the examples I've seen online, the attributes in the body are always lowercase. This also makes sense with the error message.
Try using all lowercase keys in your body.

Related

Karate - Trouble passing correct headers for authorization

I am have some problems passing in the correct headers for my graphql endpoints
The use case in Postman:
call requestToken endpoint to obtain sessionToken value
requestToken response contains Key Value " and Token Value.
For subsequent calls, I set postman headers as:
Key = X_SESSION_TOKEN Value = Token Value
The user case in Karate
1st feature 'requestToken.feature' successfully calls and stores key + tokenValue
2nd feature successfully defines and prints the token value
here is my 2nd request:
Feature: version
Background:
* url 'http://api-dev.markq.com:5000/'
* def myFeature = call read('requestToken.feature')
* def authToken = myFeature.sessionToken
* configure headers = { 'X_SESSION_TOKEN': authToken , 'Content-Type': 'application/json' }
Scenario: get version
Given path 'query'
Given text query =
"""
query {
version
}
"""
And request { query: '#(query)' }
When method POST
Then status 200
And print authToken
And print response
I am not sure I send the headers right. Its coming back 200, but I keep getting a error 'token malformed' in the response message
Any suggestions? New at this, thanks!
Honestly this is hard to answer, a LOT depends on the specific server.
EDIT: most likely it is this change needed, explained here: https://github.com/intuit/karate#embedded-expressions
* configure headers = { 'X_SESSION_TOKEN': '#(authToken)' , 'Content-Type': 'application/json' }
2 things from experience:
should it be X-SESSION-TOKEN
add an Accept: 'application/json' header
And try to hardcode the headers before attempting call etc.
Here is an example that works for me:
* url 'https://graphqlzero.almansi.me/api'
* text query =
"""
{
user(id: 1) {
posts {
data {
id
title
}
}
}
}
"""
* request { query: '#(query)' }
* method post
* status 200

Karate doesn't recognize dashes

I wrote a simple mock that checks if a specific header exists then return a specif response based on that, but karate doesn't understand dashes(-) in my headers for an example Client-ID gives an error of ReferenceError: "ID" is not defined in <eval> at line number 1 but header Accept work fine. i'm passing this header through postman.
and this how the code looks
* def fun = function(){ var test = requestHeaders; for(i in test) if(test.Client-ID) return true}
When you have characters like - part of the JSON key, you need to use quotes.
* def foo = { 'Content-Type': 'application/json' }
* match foo['Content-Type'] == 'application/json'
Also try if this works for you, it may be simpler:
Scenario: pathMatches('/v1/headers') && karate.get("requestHeaders['Client-ID']")
And in case you are testing a value, headerContains() can be used: https://github.com/intuit/karate/tree/master/karate-netty#headercontains

Bittrex API Invalid Signature Response With Python

I am trying to view my open orders through the Bittrex API but all I get is an INVALID_SIGNATURE response.
I'm using Python 3.6. Here is my code:
import time
import hmac
import hashlib
import requests
apikey = '12345'
apisecret = '56789'
nonce = str(time.time())
url = 'https://bittrex.com/api/v1.1/market/getopenorders?&apikey=' + apikey + '&nonce=' + nonce
signature = hmac.new(apisecret.encode(), url.encode(), hashlib.sha512).hexdigest()
hdrs = {'apisign' : signature}
r = requests.get(url, headers = hdrs)
print(r.json())
I'm expecting a response like:
{
"success" : true,
"message" : "",
"result" : [{
"Uuid" : null,
"OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
"Exchange" : "BTC-LTC",
"OrderType" : "LIMIT_SELL",
"Quantity" : 5.00000000,
…
}
]
}
But instead I get:
{'success': False, 'message': 'INVALID_SIGNATURE', 'result': None}
I know my keys are correct, and using purposely incorrect keys changes the INVALID_SIGNATURE response to
APIKEY_INVALID. I've tried to pull other information such as "getbalance", "getorderhistory", etc., but they all give the same result.
I've found many variations of the code above, but each one I try ends with the same result. I'm sure I'm just missing something simple but after a week of searching, I still don't know why it isn't working.
Any insight is appreciated.
Thanks.

POSTMAN: Extracting Values from body

I'm trying to recreate a scenario with the postman and there is a _csrf value in the previous GET request response body to be passed with the next POST request.
I Can't find a way to extract the value from POSTMAN.
NOTE: What I want is something similar to Regular Expression Extractor in Jmeter.If you have any Idea about extracting a value form the response body and setting it to a variable. Please let me know.
Cheers,
Muditha
This might help you https://media.readthedocs.org/pdf/postman-quick-reference-guide/latest/postman-quick-reference-guide.pdf
They use Cheerio
2.2.5 How to parse a HTML response to extract a specific value?
Presumed you want to get the _csrf hidden field value for assertions or later use from the response below:
To parse and retrive the value, we will use the cherrio JavaScript library:
responseHTML = cheerio(pm.response.text());
console.log(responseHTML.find('[name="_csrf"]').val());
Cheerio is designed for non-browser use and implements a subset of the jQuery functionality. Read more about it at
https://github.com/cheeriojs/cheerio
responseHTML = cheerio(pm.response.text());
var po= responseHTML.find('[name="_csrf"]').val();
console.log(po);
pm.environment.set("token", po);
/* You need to set the environment in Postman and capture the CSRF token in variable "here po" using a get request. Next in post request the environment variable token can be used */
Just made this JS in post man to parse Without a REGEx. Hope it will help people in the futur
Text to parse : Json : Extract data-id :
{
"code": "OK",
"response": {
"append": {
"html": {
"< .folders": "<a class=\"folder\" href=\"/foobarfoo\" data-id=\"ToExtract\"><div><i class=\"far fa-fw fa-folder\"></i></div><div class=\"folder-name\">blabla</div><div><div class=\"badge\">0</div></div></a>"
}
}
}
}
console.log(responseBody.response);
var jsonData = JSON.parse(responseBody);
var iStart = responseBody.indexOf("response\":")+10;
var scenarioId = responseBody.substr(iStart,10);
var iEnd = scenarioId.indexOf("}");
var scenarioId = scenarioId.substr(0,iEnd);
console.log("scenarioId:" + scenarioId + "iStart: "+ iStart + " scenarioId : " + scenarioId);
pm.environment.set("scenario", scenarioId);

How to pass same parameter with different value

I am trying the following API using Alamofire, but this API has multiple "to" fields. I tried to pass an array of "to" emails as parameters. It shows no error but did not send to all emails. API is correct, I tested that from terminal. Any suggestions will be cordially welcomed.
http -a email:pass -f POST 'sampleUrl' from="email#email.com" to="ongkur.cse#gmail.com" to="emailgmail#email.com" subject="test_sub" bodyText="testing hello"
I am giving my code:
class func sendMessage(message:MessageModel, delegate:RestAPIManagerDelegate?) {
let urlString = "http://localhost:8080/app/user/messages"
var parameters = [String:AnyObject]()
parameters = [
"from": message.messageFrom.emailAddress
]
var array = [String]()
for to in message.messageTO {
array.append(to)
}
parameters["to"] = array
for cc in message.messageCC {
parameters["cc"] = cc.emailAddress;
}
for bcc in message.messageBCC {
parameters["bcc"] = bcc.emailAddress;
}
parameters["subject"] = message.messageSubject;
parameters["bodyText"] = message.bodyText;
Alamofire.request(.POST, urlString, parameters: parameters)
.authenticate(user: MessageManager.sharedInstance().primaryUserName, password: MessageManager.sharedInstance().primaryPassword)
.validate(statusCode: 200..<201)
.validate(contentType: ["application/json"])
.responseJSON {
(_, _, jsonData, error) in
if(error != nil) {
println("\n sendMessage attempt json response:")
println(error!)
delegate?.messageSent?(false)
return
}
println("Server response during message sending:\n")
let swiftyJSONData = JSON(jsonData!)
println(swiftyJSONData)
delegate?.messageSent?(true)
}
}
First of all if you created the API yourself you should consider changing the API to expect an array of 'to' receivers instead of multiple times the same parameter name.
As back2dos states it in this answer: https://stackoverflow.com/a/1898078/672989
Although POST may be having multiple values for the same key, I'd be cautious using it, since some servers can't even properly handle that, which is probably why this isn't supported ... if you convert "duplicate" parameters to a list, the whole thing might start to choke, if a parameter comes in only once, and suddendly you wind up having a string or something ...
And I think he's right.
In this case I guess this is not possible with Alamofire, just as it is not possible with AFNetworking: https://github.com/AFNetworking/AFNetworking/issues/21
Alamofire probably store's its POST parameter in a Dictionary which doesn't allow duplicate keys.