how to pass the body to a rest API - json

I can run the following GET
https://myapi/aaa/?a=270&b=dog&c=animal
But I wonder how to save the parameters to a json body and pass to API. That is, what I call is
https://myapi/aaa/ with body
{
"a": 270,
"b": "dog",
"c": "animal"
}
But the response say "Please provide value for a".
Also suppose parameter a and b have multiple values, how to write the request:
I tried https://myapi/aaa/?a=${270,271}&b=${dog,cat}&c=animal but with no luck.

I think you add an extra "/" after aaa. try this:
https://myapi/aaa?a=270&b=cat&c=animal
If you want to send multiple parameters you can do this:
https://myapi/aaa?a=270&a=271&b=cat&b=dog&c=animal

I would suggest to pass the JSON data in the body as a POST request.But if you still want to pass this as a parameter in URL,you will have to encode your URL like below just for example:-
for ex json is :->{"name":"ABC","id":"1"}
testurl:80/service?data=%7B%22name%22%3A%22ABC%22%2C%22id%22%3A%221%22%7D

Related

Azure Logic App - Parse JSON with dynamic key/name

just want to know if and how I can parse a HTTP response with a dynamic name in a JSON?
I used the Azure Management API to receive the managed identities (system- and user assigned managed identities) to receive all managed identities.
With a foreach I am iterating the results.
If a resource has a system assigned managed identity and user assigned managed identity, the response looks like this:
{
"principalId": "<principalId1>",
"tenantId": "<tenantId>",
"type": "SystemAssigned, UserAssigned",
"userAssignedIdentities": {
"/subscriptions/<subscriptionId>/resourcegroups/<resourceGroupName>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<userAssignedIdentitiesName>": {
"principalId": "<principalId2>",
"clientId": "<clientId>"
}
}
}
Now, I would like to get the <principalId2>.
Unfortunately, the Name of the object is dynamic related to the scope of the resource /subscriptions/<subscriptionId>/resourcegroups/<resourceGroupName>/providers/Microsoft.ManagedIdentity/userAssignedIdentities/<userAssignedIdentitiesName>.
How can I parse the JSON to receive the needed <principalId2>?
For all other responses I can easily use the Data operations Parse JSON with the payload I inserted from the HTTP response.
Is there a way to use a wildcard? Otherwise, could I somehow just select the first object of userAssignedIdentities to receive the needed value?
Ok, this should work for you. This is the flow I tested with ...
Initialise JSON
Your JSON as a string, how you do that in your solution may differ slightly.
Initialize XPath Result
Defined as an Array and the expression is ...
xpath(xml(json(concat('{ root: ', replace(variables('JSON'), 'PrincipalId', 'principalId'), '}'))), '(//principalId)[2]')
Initialize Result
A bit more work again but defined as a String and the expression is ...
array(xpath(xml(base64ToString(variables('XPath Result')[0]?['$content'])), '//text()'))[0]
The end result should be your value ...

How to parse dynamic json reponse and get specific value and pass it as an input to next request

I get .json file as a response from an API and from that file I should parse and fins specific parameter and pass it as an input to the next request, how do I do that using Katalon.
If I say
response = JSON.parse("response.json");
it says it is unable to identify JSON as valid. Can someone help me out with the solution?
Your JSON is invalid, maybe it is a copy-paste issue.
The valid JSON should be
{
"responseStatusCode": "OK",
"data": {
"screenName": "employeeTimeslip",
"screenType": "Redirect",
"searchResultCount": 0,
"rows": [],
"tabs": [],
"searchParams": {
"employeeID": "000092926",
"timeslipNumber": "201900019701"
}
}
}
So, you were missing a "," between "OK" and "data" and two closing curly braces at the end of the file.
You can check JSON files for validity yourself using online JSON validators, for example, this one.
i found a way to read specific parameter from the json response file like below:
val scn = scenario("ClaimSubmission")
.exec(http("request_2")
.post("URL")
.headers(headers_2)
.body(RawFileBody("json file path"))
.check(jsonPath("$..timeslipnumber").find.saveAs("timeslipnumber")))
Timeslip number would be retrieved using : .check(jsonPath("$..timeslipnumber").find.saveAs("timeslipnumber")))

How to store entire response and update it for next rest call using Jmeter

Question: How to extract entire restAPI response and modify it with some values and use the updated response for sub-sequent rest call. I am using Jmeter
Question Scenario:
I have one POST call ex: "/check1/id1/post"
POST body :
{
"test":"rest",
"check" :{
"id":1,
"name": "xyz"
}
}
POST call RESPONSE :
{
"test":"rest",
"check" :{
"id":1,
"name": "xyz"
"status":"updated"
}
}
=====================================================================
QUESTION: Now, I have to use entire above RESPONSE in next POST Call body as below, BUT, I wanted to update "id" value as 2 and then need to POST rest call.
REST CALL: ------ > "/check1/id2/post"
POST BODY as below : ------->
{
"test":"rest",
"check" :{
"id":2,
"name": "xyz"
"status":"updated"
}
}
=============================================================
Can anyone please guide on this? , I am clueless about how to solve this issue?, I need to solve this using Jmeter.
To store entire response:
add Regular Expression Extractor as a child of the request which response you want to capture
configure it as follows:
Reference name: anything meaningful, i.e. response
Regular Expression: (?s)(^.*)
Template: $1$
To replace 1 with 2 you can go for __strReplace() function like ${__strReplace(${response},1,2,)}. Note that you need to install Custom JMeter Functions bundle using JMeter Plugins Manager in order get it.
You can do this using beanshell or JSR223 PreProcessor
Assuming a valid JSON
{
"test":"rest",
"check" :{
"id":1,
"name": "xyz",
"status":"updated"
}
}
Here are the steps
Add a JSR223 preprocessor to the 2nd post request.
Add the following code to the preprocessor
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
def slurped = new JsonSlurper().parse(prev.getResponseData())
def builder = new JsonBuilder(slurped)
builder.content.check.id = '2'
vars.put("POSTDATA",builder.toPrettyString())
Above code will update ID value with 2 and stores the JSON in POSTDATA , you can use ${POSTDATA} to post the JSON FILE
In my pre processor i'm saving the response using prev.getResponseData() , that means this pre processor must included with the sampler right next to the first sampler.
For more information on beanshell Please follow this link

JMeter Variables in JSON request

When I pass an variable in JMeter HTTP request, I'm getting an exception
"Unexpected escape character after back slash"
The request body:
"Draft":{
"id": 123654656,
"draftdata":{\\\"accCat\\\":\\\"207\\\",\\\"accNumber\\\":\\\"656565
\\\",\\\"id\\\":${Var_ID},...}
}
When I send the request, one of the two back-slashes are omitted. I guess the variable ${Var_ID} should be passed in a way that does not conflict with the json body
I don't think you need these \\\ signs
I believe you need to surround ${Var_ID} with quotation marks
Something like:
{
"id": 123654656,
"draftdata": {
"accCat": "207",
"accNumber": "656565 ",
"id": "${Var_ID}"
}
}
You can use online JSON validation tools like Online JSON Viewer to test your JSON payload. Also check out Testing SOAP/REST Web Services Using JMeter article for some initial information on testing REST APIs using JMeter
Maybe making changes like:
{
"Draft": {
"id": 123654656,
"draftdata": {
\"accCat\":\"207\",
\"accNumber\":\"656565\",
\"id\":\"${Var_ID}\",...}
}
I don't see any need to have \ signs, just one will escape original " signs.
The variables, or the request to some function of JMeter, into json body must be passed without quotation marks, something like this:
"Draft":{
"id": 123654656,
"draftdata":{
"accCat":"207",
"accNumber":"656565",
"id":${Var_ID},...}
}
Also yout don't need the backslashes signs. Hope this help.

Is it possible to send an array with the Postman Chrome extension?

I've been using Postman Chrome extension to test out my API and would like to send an array of IDs via post. Is there a way to send something list this as a parameter in Postman?
{
user_ids: ["1234", "5678"]
}
You need to suffix your variable name with [] like this:
If that doesn't work, try not putting indexes in brackets:
my_array[] value1
my_array[] value2
Note:
If you are using the postman packaged app, you can send an array by selecting raw / json (instead of form-data). Also, make sure to set Content-Type as application/json in Headers tab.
Here is example for raw data {"user_ids": ["123" "233"]}, don't forget the quotes!
If you are using the postman REST client you have to use the method I described above because passing data as raw (json) won't work. There is a bug in the postman REST client (At least I get the bug when I use 0.8.4.6).
For me did not work with array[0], array1, .. or array[], array[], ... .
It works more simply:
If you want an array of dicts, try this:
Here is my solution:
use form-data and edit as below:
Key Value
box[] a
box[n1] b
box[n2][] c
box[n2][] d
and you will get an array like this:
{"box":{"0":"a","n1":"b","n2":["c","d"]}}
It is important to know, that the VALUE box is only allowed to contain a numeral value (no specifiers).
If you want to send e.g. an array of "messages" with Postman, each having a list of key/value pairs, enter e.g. messages[][reason] into the KEY box and the value of reason into the VALUE box:
The server will receive:
{"messages"=>[{"reason"=>"scrolled", "tabid"=>"2"}, {"reason"=>"reload", "tabid"=>"1"}], "endpoint"=>{}}
I also had that problem, and solved it by doing the following:
1 - Going to the request header configuration and added the following:
Accept : application/json, text/plain, */*
Content-Type : application/json;charset=UTF-8
2 - To send the json array, I went to raw json format and set the user_ids to array:
user_ids: ["bbbbbbbbbb","aaaaaaaaaa","987654321","123456789"]
Set Body as raw and form the array as follows:
As mentioned by #pinouchon you can pass it with the help of array index
my_array[0] value
my_array[1] value
In addition to this, to pass list of hashes, you can follow something like:
my_array[0][key1] value1
my_array[0][key2] value2
Example:
To pass param1=[{name:test_name, value:test_value}, {...}]
param1[0][name] test_name
param1[0][value] test_value
Go to Header and select Content-Type = application/json then go to body and select raw and then pass an array.
this worked for me. to pass an array of Item object {ItemID,ColorID,SizeID,Quntity}
in headers set
content-type : application/x-www-form-urlencoded
In body select option
x-www-form-urlencoded
and insert data as json array
user_ids : ["1234", "5678"]
This also works for lists within the object:
Id:37
IdParent:26
Name:Poplet
Values[0].Id:1349
Values[0].Name:SomeName
Values[1].Id:1350
Values[1].Name:AnotherName
the equivalent JSON would be:
{
"Id": 37,
"IdParent": 26,
"Name": "Poplet",
"Values": [
{
"Id": 1349,
"Name": "SomeName"
},
{
"Id": 1350,
"Name": "AnotherName"
}
]
}
{
"data" : [
{
"key1" : "value1",
"key2" : "value2"
},
{
"key01" : "value01",
"key02" : "value02"
},
{
"key10" : "value10",
"key20" : "value20"
}
]
}
You can pass like this.
In form-data you can pass a array like this
and in backend you will fetch it like a
"tags"=>["aaaa", "bbb"]
In my case I've to pass two values in a array so I write it two times
Choose either form-data or urlencoded and use the same key "user_ids". The server should receive it as an array.
In form-data,
key value
user_ids[] 1234
user_ids[] 5678
My back-end is written in Ruby on Rails. This is how I sent the array params using Postman. It worked for me.
UPDATE
I'm using x-www-form-urlencoded. I believe it will work too for form-data.
To send an array using form data there's no need to use brackets.
Just send that specific array using the same name in multiple fields.
Like:
my_array:value_1
my_array:value_2
Although this question has already accepted a solution still that solution has a drawback that is we have to repeat the key (Array name) again and again as one key is accepting only one value. Like this:
Imagine we have 10 values or more, should we repeat the same Array name each time? The programmatic answer is NO. Then we should do the following that is a better approach.
Select the form-data as usual
Type Array name in the Key field
Pass the Array in Value field
Like this:
Now, you should be able to send the Array, but wait, this won't be stored in Database like that in my case with MongoDB. So what you have to do is, use the following piece of code to send it like an Array in the Database:
First, we need to parse it using JSON, like this
let user_ids = JSON.parse(body.user_ids);
Now, you can send user_ids variable to database like an Array
That's All!
I tried all solution here and in other posts, but nothing helped.
The only answer helped me:
Adding [FromBody] attribute before decleration of parameter in function signature:
[Route("MyFunc")]
public string MyFunc([FromBody] string[] obj)
Supposing you have the array of object below,
features: [
{
title: { type: String },
type: { type: String },
},
],
To add the values on the form data on the postman, add it this way
features[title]
features[type]
Check also the image below
Here is something that worked for me
{
"user_ids":["[1234, 5678]"]
}
I believe it depends on how the backend is setup most of the time.
N.B Now we are in 2022 if All of the above solutions didn't, just don't panic. pass array name with is value without a bracket and the add it multiple time, just link how the image below is showing. it should work just fine. If It does work, buy me some coffee, hhh
In my case I need to send array of objects, I sent it like this
Request header configuration and added the following
Accept: application/json
You need to suffix your key variable name with []
like key[0][name]
You can insert it in "bulk-edit" mode
Body section in form-data on right side click Bulk Edit and added the following
items[0][prod_id]:174336
items[0][item_weight]:3.400
items[0][item_qty]:1
items[0][item_selected_melting]:92
items[0][item_remarks]:
items[1][prod_id]:12345