How to pass dynamic json request body in postman - dynamic

I have a POST request where i need to pass some parameters dynamically since my code is checking for a duplicate entry. I tried writing a pre request script and then setting the global variables and tried to access it in my request. It is not working. PFB, the details
Pre-request Script
postman.setGlobalVariable("firstname", (text + parseInt(Math.random()*10000)).toString());
postman.setGlobalVariable("lastname", text + parseInt(Math.random()*10000));
Body
{
"request":
{
"firstName":"{{firstname}}",
"middleName":"mani",
"lastName":"{{lastname}}"
}
}
Here firstName is getting passed as {{firstname}} instead of random string.

You ca do it by adding
var rnd = Math.floor((Math.random() * 10000) + 1);
postman.setEnvironmentVariable("firstname", "fname"+rnd);
postman.setEnvironmentVariable("lastname", "lname"+rnd);
in the Pre-request Script section.
And then adding
{
"firstName":"{{firstname}}",
"middleName":"mani",
"lastName":"{{lastname}}"
}
in the body.
I tried it in both Postman and Newman and is working perfectly generating a random first name and last name.

{
"request": {
"firstName":"{{$randomInt}}",
"middleName":"mani",
"lastName":"{{$randomInt}}"
}
}
No need to add global variables.
Postman have dynamic variable {{$randomInt}} which Adds a random integer between 0 and 1000

Related

REST API - SOAPUI - POST script generates key ID at the end of the query

I have a bit of a problem here. I was making some API tests using the POST Method in SOAP UI. I put this script to generate a new entry
{
"title":"Mark",
"author":"Hampton",
"text":"TestRest",
"created":"${#Project#Timestamp}" - can be a fixed value
}
I got a proper response and an entry is created as following
{
"title":"Mark",
"author":"Hampton",
"text":"TestRest",
"created":"12/05/2022-15:40",
"id":6
}
The "id" property is generated automatically. I was wondering if there is a way to force the "id" property to be on top. When I did a PATCH method and added a new parameter. The "id" property was above the new parameter
{
"title":"Johan",
"author":"Dudes",
"text":"Dyke",
"created":"12/05/2022-15:40",
"id":6,
"updated":"12/06/2022-17:07"
}
So, how can I do a POST method where the ID is generated automatically at the top, and in the response script, the ID parameter is not at the bottom of a response

Testing Coinbase API with Postman : pagination gives me error

I am testing the Coinbase API endpoints with Postman and the challenge is when I need to paginate
In order to setup Postman, I have followed the guide available here and in summary:
added variables
coinbase-api-base
coinbase-api-key
coinbase-api-secret
coinbase-api-timestamp
coinbase-api-signature
Added pre-request script in order to generate the request signature
// 1. Import crypto-js library
var CryptoJS = require("crypto-js");
// 2. Create the JSON request object var req = { timestamp: Math.floor(Date.now() / 1000), // seconds since Unix epoch method:
pm.request.method, path: pm.request.url.getPath(), body: '', // empty
for GET requests message: undefined, secret:
pm.collectionVariables.get("coinbase-api-secret"), // read value from
collection variable hmac: undefined, signature: undefined, };
// 3. Create the message to be signed req.message = req.timestamp + req.method + req.path + req.body;
// 4. Create HMAC using message and API secret req.hmac = CryptoJS.HmacSHA256(req.message, req.secret);
// 5. Obtain signature by converting HMAC to hexadecimal String req.signature = req.hmac.toString(CryptoJS.enc.Hex);
// 6. Log the request console.info("request: ", req);
// 7. Set Postman request's authentication headers for Coinbase REST API call pm.collectionVariables.set("coinbase-api-timestamp",
req.timestamp); pm.collectionVariables.set("coinbase-api-signature",
req.signature);
all worked well for a simple request such as:
GET {{coinbase-api-base}}/v2/accounts
then, if I add in the body request parameter (as explained here):
limit=50
to change the default pagination, I get an authentication error....
"errors": [
{ "id": "authentication_error",
"message": "invalid signature"
}
questions:
how can I fix it?
how the body of the request can play with the request signature...
any help suggestion is much appreciated
Thank you
Edit: the below being said, I'm not sure the base accounts API supports paging I could be wrong though, the CB docs are inconsistent to say the least. It does seem that the account history (ledger) and holds do though.
https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccounts
get accounts function in Node.js API doesn't give an args param where the ledger does (see below):
getAccounts(callback) {
return this.get(['accounts'], callback);
}
Documentation for an api that does support paging, notice it gives you a query param section not available in the accounts documentation:
https://docs.cloud.coinbase.com/exchange/reference/exchangerestapi_getaccountledger
Looking at the node api, you still need to add the query string params to the body in order to sign:
calling function:
return this.get(
['accounts', accountID, 'ledger'],
{ qs: args },
callback
);
signing function:
let body = '';
if (options.body) {
body = JSON.stringify(options.body);
} else if (options.qs && Object.keys(options.qs).length !== 0) {
body = '?' + querystring.stringify(options.qs);
}
const what = timestamp + method.toUpperCase() + path + body;
const key = Buffer.from(auth.secret, 'base64');
const hmac = crypto.createHmac('sha256', key);
const signature = hmac.update(what).digest('base64');
return {
key: auth.key,
signature: signature,
timestamp: timestamp,
passphrase: auth.passphrase,
};
You can't add the limit to the body of the request, GET requests never includes any body.
You should add it as a query string parameter like (this is just an example):
GET {{coinbase-api-base}}/v2/accounts?limit=50

Passing multiple parameters using karate.call

I am trying to call an API in second feature file , passing arguments from first feature file . Say token and current page value which is returned from a first API response.These has to be passed as a param for second API
* def activeDetails =
"""
function(times){
for(i=0;i<=times;i++){
karate.log('Run test round: '+(i+1));
karate.call('getActiveRouteDetails.feature', { token: token, currentPage: i });
}
java.lang.Thread.sleep(1*1000);
}
"""
* call activeDetails totalPages
In my second feature , I am able to print the values passed , but unable to pass in params . Can you please help me
And print currentPage
And print token
And param pageNumber = '#currentPage'
And param token = token
There is a subtle difference when you are in a JavaScript block. Please read this: https://github.com/intuit/karate#karate-expressions
Make this change:
var result = karate.call('examples/getDetails.feature', { token: token, currentPage, i });
And please don't have variable names like current page, take the help of a JavaScript programmer friend if needed for help.
Also note that the best practice is to avoid JS code and loops as far as possible: https://github.com/intuit/karate#loops

How to pass xml as Json attribue in postman

I am trying to write a really simple test in Postman. I have two URL and first url get some XML file and then store this in Postman varible as a pre script section.
After that second URL uses this response and send a another request for Post.
but after getting result from xml successfully , somehow postman does not pass this request and gives 400.
pm.environment.set('RandomNumber', "cot"+Math.floor(Math.random() * 1000));
pm.sendRequest("https://test/metadata.xml", function (err, response) {
pm.environment.set('**RandomURLText**', response.text());
});
RandomURLText varible store the value of first request.
Second request body params looks like below code .
**{
"idPType": "Test",
"dontShowProgress": true,
"dontIncludeRequestedAuthnContext": true,
"nameIDFormat": "run:SAML:2.0:nameid-format:transient",
"sigAlg": "http://www.w3.org/2001/04/xmldsig-more#rsa-a",
"metadata": {
"idpXml": "{{RandomURLText}}"
}
}**
is there any function postman who can transform this xml response data. Because second request say 400 when it add xml type data. But when I just replaced this responsetext to hello then its works.
That's means something is wrong in xml type data , may be escape chars.
could someone help me on this?
Thanks
found answer myself, its working.
Just need to parse into string and need to removed quote from body.
pm.environment.set('RandomURLText', JSON.stringify(response.text()));
**{
"idPType": "Test",
"dontShowProgress": true,
"dontIncludeRequestedAuthnContext": true,
"nameIDFormat": "run:SAML:2.0:nameid-format:transient",
"sigAlg": "http://www.w3.org/2001/04/xmldsig-more#rsa-a",
"metadata": {
"idpXml": {{RandomURLText}}
}
}**
Thanks

how to evaluate java function using __groovy and assign it as part of Http Request

I have a http request with the following structure.
Http Request :-
"Accounts": [
{
"accountType": "SAVINGS",
"RefNumber": "${RefNumber}",
"accountNo": "${AccNumber}"
}
],
"encryptionKey": "${__groovy(new com.util.EncryptUtil().encrypt(), encryptedValue)}"
The value of encryptionKey is calculated using the mentioned groovy function. The encrypt function takes the Accounts object and calculates the encryptedValue based on the value of RefNumber and accountNo. The value of accountNo comes from the first Http Response API. The value of the RefNumber comes from the second Http Response API. How do I accept the dynamic Accounts object json and calculate the encrypted value in jmeter and how do I check if the function result is being assigned to encryptionKey using jmeter?
First of all you can check your function output using The Function Helper Dialog
Example class I use for demo looks like:
package com.util;
public class EncryptUtil {
public String encrypt() {
return "some encrypted value";
}
}
Second, you can check your request payload using View Results Tree listener
And finally you can check generated ${encryptedValue} variable using Debug Sampler