I am using some of the auto generated parameters in my request body in a postman request(i.e: {{$guid}}).
I would like in my test to retrieve the request that was sent to the server to compare what this variable value was, and what the response parroted back to me me in my request.
for example, my request's body looks like this:
{
"Description": "testing this {{$guid}}"
}
and I would in the tests be able to do:
var req = JSON.parse(requestBody);
var resp = JSON.parse(responseBody);
test['description should match'] = req.Description === resp.Description;
is this doable?
This is possible.
But you have several small syntax errors.
To access the request body data use:
var req = JSON.parse(request.data);
I named the variable req to not be confused with the predefined request variable. You can log the result like this:
console.log(req.Description);
In the tests tab make sure you reference the correct variable tests with "s". Also you pass the test case name as a string e.g. "description should match".
var res = JSON.parse(responseBody);
console.log(res.Description);
tests["description should match"] = req.Description === res.Description;
Related
I'm trying to pass parameters in the request body, the documentation says :
The request to be sent was defined in a prior call to the Open method. The calling application can provide data to be sent to the server through the Body parameter. If the HTTP verb of the object's Open is "GET", this method sends the request without Body, even if it is provided by the calling application.
So, I need to use POST with body. But when I use use POST with body I have error "Bad Request: message text is empty" and when I use GET with body result is ok. Why?
My code:
WinHttp = NEW COMObject("WinHttp.WinHttpRequest.5.1");
WinHttp.Open("GET", "http://api.telegram.org/botbotname/sendMessage", 0);
WinHttp.setRequestHeader("Content-type", "application/json");
JSONWr = New JSONWriter();
JSONWr.ValidateStructure = False;
JSONParams = New JSONWriterSettings( , Chars.Tab);
JSONWr.SetString(JSONParams);
JSONWr.WriteStartObject();
JSONWr.WritePropertyName("chat_id");
JSONWr.WriteValue(UserId);
JSONWr.WritePropertyName("text");
JSONWr.WriteValue(Text);
JSONWr.WriteEndObject();
JSONString = JSONWr.Close();
WinHttp.Send(JSONString);
work, but how? And why the same with POST doesn`t work?
I'm trying to make an authenticated api call to VALR crypto exchange as first step towards automated trading. They provide most of the code so I thought it would be easy even as a non coding techie. The code below does actually create the correct HMAC SHA512 signature using the API Secret provided for testing but I have a problem in passing this result along to the next section of code to request balances (starting at line 17). If I cut and paste the result/displayed 'signature' and 'timestamp' (after running the code) back into the code it does in fact work. So what changes do I need to make the code automatically pick up the signature and timestamp. The user defined function appears to keep all parameters "secret" from the rest of the code, especially after using return.
import time
import hashlib
import hmac
def sign_request( api_key_secret,timestamp, verb,path,body=""):
payload = "{}{}{}{}".format(timestamp, verb.upper(), path, body)
message = bytearray(payload, 'utf-8')
signature = hmac.new(bytearray(api_key_secret, 'utf-8'), message, digestmod=hashlib.sha512).hexdigest()
print("Signature=",signature)
print ("Timestamp",timestamp)
return signature
sign_request( verb = "GET", timestamp = int(time.time()*1000),path="/v1/account/balances",api_key_secret="4961b74efac86b25cce8fbe4c9811c4c7a787b7a5996660afcc2e287ad864363" )
import requests
url = "https://api.valr.com/v1/account/balances"
payload = {}
headers = {
'X-VALR-API-KEY': '2589fb273e86aeee10bac1445232aa302feb37e27d32c1c599abc3757599139e',
'X-VALR-SIGNATURE': 'signature',
'X-VALR-TIMESTAMP': 'timestamp'
}
response = requests.request("GET", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
Well after some hard thinking I decided to change to using global variables. The hmac still worked fine and gave me a signature. Then I removed the quotes around signature and timestamp and realised they were both integers. I was then able to convert that signature and timestamp to a string and everything started to work perfectly. Maybe someone else will make use of this. If you want to make a POST request remember to put single quotes around anything in the {body} statement to make it a string.
Here is the code that I am currently using for a GET request from VALR. It's been working fine for many months. You will need to change the path and the url to correspond to whatever you are trying to get, and obviously you will need to add your_api_key and your_api_secret.
If you need to send through other request parameters like transaction types etc. then you will ned to include them in the path and the url e.g. https://api.valr.com/v1/account/transactionhistory?skip=0&limit=100&transactionTypes=MARKET_BUY¤cy=ZAR
def get_orders(): # to get open orders from valr
timestamp = int(time.time()*1000)
verb = "GET"
path = "/v1/orders/open"
body = ""
api_key_secret = 'your_api_secret'
payload = "{}{}{}".format(timestamp, verb.upper(), path)
message = bytearray(payload, 'utf-8')
signature = hmac.new(bytearray(api_key_secret, 'utf-8'), message, digestmod=hashlib.sha512).hexdigest()
timestamp_str = str(timestamp)
url = "https://api.valr.com/v1/orders/open"
headers = {
'Content-Type': 'application/json',
'X-VALR-API-KEY': 'your_api_key',
'X-VALR-SIGNATURE': signature,
'X-VALR-TIMESTAMP': timestamp_str,
}
response = requests.request("GET", url, headers=headers, data=body)
dict = json.loads(response.text)
dict = pd.DataFrame.from_dict(dict)
print(dict)
This is my response body, I want to get the value of status by using an environment variable.
{
"success":[
{
"code":"200",
"message":"Success",
"details":"Station was retrieved successfully."
}
]
}
i can get value of status code as: jsonData.success.code,
But instead of this, I'm doing it like,
I m setting an environment variable named 'sh' n I gave value as "code"...
pm.environment.set("sh","code");
var s = pm.environment.get("sh")
jsonData.status.success[0].s
By doing like this I'm not able to get the path...Any solutions?
Thanks in advance.
It's hard to tell what your actual response body is but this should probably work:
let statusCode = pm.response.json().success[0].code
pm.environment.set("statusCode", statusCode)
Ensure that you create an environment file before running the request.
I am trying to set an env variable with a query param received in the response.
i am sending a POST request and in the response I am getting a resource id i need to use in the next request (therefore need to add it as an env variable).
the response Header:
location →
https://mmmmmmmm.nnnnnnnn.xxxxxx/oauth-signin?client_id=bbbnnnmmmm-bbnn-46ba-a287-nnhhyyy&redirect_uri=https://mmm.nnnn.nnnn/galaxy-backend/redirect/oauth/token&response_type=code&state=kYIL97&protocol=berlin-v13&consent_id=5d1372ebfb0b3a09b2ea4ddb&scope=accounts.accountDetails.read+accounts.transactions.read+accounts.balances.read
i am trying to retrieve the value form the query param 'consent_id' and set it in env variable.
my env variable is named 'ConsentId'.
i tried:
pm.environment.set('ConsentId', JSON.stringify(pm.response.header.getQueryString("consent_id")));
No luck.
Would appreciate help with how to write it so the script will get the field from the a url param in the header and place it in the env variable.
To get ConsentId parameter value in Location response header and set it as environment variable in Postman:
var key = 'consent_id';
var regex = new RegExp('[?&]' + key + '(=([^&#]*)|&|#|$)');
var redirectURL = postman.getResponseHeader('Location');
var matchResult = regex.exec(redirectURL);
var consentId = decodeURIComponent(matchResult[2].replace(/\+/g, ' '));
pm.environment.set('ConsentId', consentId);
BTW, to make above code work well, "Automatically follow redirects" option should be turned off:
Note: I failed to extract Location header from pm.response.headers, that's why postman.getResponseHeader() is used in above code.
I am completely new to coding. I am trying to build a dashboard in Klipfolio. I am using a CATSone API to pull data from CATSone to Klipfolio. However, I can only get 100 rows a time, which means I would have to pull data 2600 times.
I am now trying to build a script to get data from the API through Google Script Editor. However, since I have no experience in this, I am just trying stuff. I watched some videos, also from Ben Collins. The basis is simple, and I get what he is doing.
However, I have a problem with putting the API key.
var API_KEY = 'key'
function callCATSone(){
//Call the CATSone API for all candidate list
var response = UrlFetchApp.fetch("https://api.catsone.nl/v3/candidates");
Logger.log(response.getContentText());
// URL and params for the API
var url = 'https://api.catsone.nl/v3/candidates';
var params = {
'method': 'GET',
'muteHttpExceptions': true,
'headers': {
'Authorization': 'key ' + apikey
}
};
// call the API
var response = UrlFetchApp.fetch(url, params);
var data = response.getContentText();
var json = JSON.parse(data);
}
In the end, I would like to transfer all candidate list data to my sheets. Therefore, I call on the API with Authorization key. After that, I will manipulate the data, but that's for later. The first problem I now encounter, is this fail code:
'Verzoek voor https://api.catsone.nl/v3/candidates is mislukt. Foutcode: 401. Ingekorte serverreactie: {"message":"Invalid credentials."} (Gebruik de optie muteHttpExceptions om de volledige reactie te onderzoeken.) (regel 6, bestand 'Code')'.
I expect to get a list of all data from CATSone into my sheets.
Does anyone know how I can accomplish this?
Two changes should fix the credentials error:
Authorization header should be Authorization: 'Token ' + yourApiKey instead of 'key ', see the v3 API documentation https://docs.catsone.com/api/v3/#authentication.
API key in your case is stored in a global variable API_KEY, you should reference it exactly like that, not as an apikey (unless there is a typo in your sample or some missing code): Authorization : 'Token ' + API_KEY.
Btw, it should probably set either a Content-Type header or a contentType parameter for UrlFetchApp.fetch() method call to application/json as UrlFetchApp.fetch() request content type defaults to application/x-www-form-urlencoded.
If you plan to continue working with APIs, it would be beneficial to read this MDN article.