Postman - use CSV as input - csv

I am using Postman to test a microservice and I was wondering if you can do something like this.
have a collection with 2 GET request (request1, request2) that have
as one of the headers - userId
have a CSV file with two values for userId: test1, test2
run the collection using the CSV file like this: request1 uses the userId= test1 and request2 uses the parameter userId=test2
I know you can run the collection so that it iterates for each value in the CSV file through each request, but I would like to to map each request to a value in the CSV file. is this possible? If yes, how can you do that?

CSV files are only accepted as a iteration data files, so
is this possible to map each request to a value in the CSV file.
answer is: No, you can't.
You should give us more detailed question, but I feel that this link
will be helpful.
Also you can use JSON as datafile instead of CSV and make such construction:
Firstly, set environment variable "count" to 0.
JSON:
[
{
"UserIdHeadersValue":
[
"firstvalue",
"secondValue",
"thirdValue"
]
}
]
And in Scripts:
pre-request:
var count = parseInt(pm.variables.get("count"));
pm.variables.set("headerValue", data.UserIdHeaderValue[count]);
//you can put now that header value using {{headerValue}};
pm.environment.set("count", count+1);

Related

How do I extract JSON data from a raw.github URL and store it in a variable?

Let's say that I have a JSON file called data.json in Github. I can view it in raw in a Github URL like this: https://raw.githubusercontent.com/data.json (This is a hypothetical URL. It's not real)
And let's say that URL contains JSON data like this:
"users_1": [
{
"id": 1234,
"name": "Bob"
},
{
"id": 5678,
"name": "Alice"
}
]
How do I extract the whole JSON data from that URL and store it in a variable in a Cypress test? I know that Cypress doesn't really use Promises, so I'm finding it difficult to implement this. So far I got this in Typescript:
let users; // I want this variable to store JSON data from the URL
const dataUrl = "https://raw.githubusercontent.com/data.json";
cy.request(dataUrl).then((response) => {
users = JSON.parse(response); // This errors out because response is type Cypress.Response<any>
})
I'm planning to do something like this in the future for my project when migrating from Protractor to Cypress. I have a Protractor test that extracts JSON data from a Github file and stores it a variable by using a Promise. I want to do the same kind of task with Cypress.
I think you should use response.body, and it should have been serialized.
A request body to be sent in the request. Cypress sets the Accepts request header and serializes the response body by the encoding option. (https://docs.cypress.io/api/commands/request#Usage)

Append to CSV file with header in Apache Camel

I need to build a csv file based on incoming messages. I do this by appending to the file with:
.toD("file://" + OUTPUT_PATH + "?FileName=${exchangeProperty.OUTPUT_FILENAME}" + "&FileExist=Append")
While this works fine I've run into one problem. I also need to include a header row in the CSV file. Right now I'm marshalling into CSV format with .mashall().csv() but that omits the header.
While I can create a CSV format with header with:
CsvDataFormat csvFormatWithHeader = new CsvDataFormat();
csvFormatWithHeader.setHeader(Arrays.asList(new String[] { "A", "B", "C", "D" }.clone()));
.marshall(csvFormatWithHeader)
That will add the header row for each row I add.
So what I want to achieve is to add the header only when a new file is created.
I've been trying two approaches but haven't gotten any to work:
Check if the file exists in the route and apply the csv format accordingly
Set the marshall dataformat with a bean or method
As a final option I could add the header when the file is closed but that feels inefficient as I don't know how big that file might become.
How can I achieve either of these approaches with Apache Camel 2.23.2.
Ok, ultimately using a header I was able to get option 1 to work. This is what my route looks like now:
.setProperty("OUTPUT_FILENAME",method(this, "determineOutputFilename()"))
.setHeader("fileExists", method(this, "outputFileExists"))
.choice()
.when(header("fileExists"))
.marshal().csv()
.endChoice()
.otherwise()
.marshal(csvFormatWithHeader)
.endChoice()
.end()
The file check logic is (implemented within the route class):
public boolean outputFileExists(#ExchangeProperty("OUTPUT_FILENAME") String fileName){
boolean fileExists = new File(PROCESSING_PATH + "/" + fileName).exists();
return fileExists;
}

How to find and replace data from one JSON file to another using Python?

JSON file contains below data and structure is same across all files, but data under profile will be changing quite frequently.
So, am trying for Python script which will copy and replace entire data under "Profile" node to another JSON files (As Config data is static as each machine has diff static values).
Algo:
Pharse JSON file
Read and extract Profile data
Pharse and replace Entire Profile data to another JSON file
{
"config":
[
{
"Name":"FW",
"MLC":"anotoly",
"Frame":"True",
"ImageUpload":"False"
}
],
"Profile":
[
{
"Title":"CLI",
"File":"",
"Profile":"H",
"App":"AI.exe",
"Location":"\\common\\Isolation",
"sensitivity":20
}
]
}
import json,os,sys
def testDataTransform():
source = 'C:/Users/WS/Downloads/Profile.json'
Destination = 'D:/OL/SV/4.json'
datastore= None
with open(source, 'r') as content_file:
content = content_file.read()
datastore = json.load(content)
This code is not working, any help would be great. Thanks.

How to do simulation of the json file ( Body data) in the jmeter using Http- POST method

My test objective:
Using POST method I have to send the json data but there is an ex.
A, b, c property in that Json file that need to be updated, so It should consider the different request at application end.
To prepare lot .Json file and provide input to j meter is not a feasible solution. How to simulate the data in the.Json file .
I have tried .config csv method but my packet is not formed by appending csv file values . Kindly help me. How to use the variable method to achieve this
Note : This is not the full .json file . Just part of the body . "Properties": { "AccessToken": "111111111-11111-11111-1111111111", "InstallationId": "E1", "AgentType": "xxx", "AgentId": "Vxxx", "SentDateTime": "2018-07-19-13-50-24-5916045", "SourceDateTimeOfEvent": "2018-07-19T13:50:24.5916045+05:30Z", "DateTimeOfEvent": "2018-07-19T08:06:24.5786045Z" "MachineName": "AS-72" } This three parameter need to be updated with every new POST request SourceDateTimeOfEvent,DateTimeOfEvent,SentDateTime and rest of whole body should remains

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