Jmeter Postprocessor Write To File

Apache JMeter is open-source software that is popular for performance testing. This tool is designed to load test functional behavior and measure performance.
Dec 05, 2016 vars props; Use for JMeter Variables: Use for JMeter Properties: Can read/write on single Thread Group: Can read/write on multi Thread Group Use getObject and putObject to get access to an Object, List, etc.: props is an object of type java.util.Properties, which is a subclass of Hashtable.Therefore you can use put and get to access Object, List, etc. 4.1 - Result File Location. This listener can record results to a file but not to the UI. It is meant to provide an efficient means of recording data by eliminating GUI overhead. When running in: GUI mode, use the listener Simple Data Writer. Non-GUI mode, the -l flag can be used to create a data file.
This article is about how to use JMeter for Performance Testing of a RESTful API. In this, we will learn how to configure JMeter and test a REST API to know how efficiently it works and how many concurrent users the server can handle.
For this, I created a RESTful API that lets you do the CRUD operation on a “Product.” A Product is a simple object that has a name, description, and price.
The API was created using three components of the MEAN stack – NodeJs, Express and MongoDB.
The API methods are as follows:
Using JMeter, we will design the test that will
- Use HTTP GET to retrieve a list of all items
- Use HTTP POST to add a new item
- Use HTTP PUT to update a newly added item
- Use HTTP DELETE to delete the item added
Steps for Scripting a REST API in JMeter
As soon as you launch JMeter, you will see 2 elements: Test Plan and Workbench.
1. This is the REST API. We will posting data as a JSON object, so we need to set a Content-Type header. For this, right click Test Plan and add Config Element → Http Header Manager and add “Content-Type.” Set value to “application/json.”
2. Right click Test Plan. Select Add → Threads (Users) → Thread Group. Add the thread group.
- Set the name to “Item API Perf Test”
- Set the number of threads (users) to 10
- Set the Ramp-Up period (in seconds) to 10
- Set the Loop count to 10
So we will have 10 users executing the test plan 100 times. The Ramp-Up Period tells JMeter how long to delay before starting the next user.
3. Right click Thread Group (Item API Perf Test) and add Config Elements → HTTP Request Defaults.
HTTP Request Defaults: This element lets you set default values that your HTTP Request controllers use. For example, if you are creating a Test Plan with 25 HTTP Request controllers and all of the requests are being sent to the same server, you could add a single HTTP Request Defaults element with the “Server Name or IP” field filled in.
So set the server name, port number, and the path to the resource.
- Server Name: hostingserver.com (Server address where the RESTFul API is running)
- Port Number: 8080
- Path: /items
4. Right click Thread Group (Item API Perf Test) and add Sampler → HTTP Request
Our first request will be to fetch all of the existing items. So set:
- Name: Fetch All items
- Method: GET
5. For the second request to POST an item (aka create), let’s add another sampler. Right click Thread Group (Item API Perf Test) and add Sampler → HTTP Request
- Name: Post an Item
- Method: POST
- Body Data: JSON Item Object
Once the item is posted successfully, the response return will have a unique ID of the item.
We need to extract that value so that we can use it in the subsequent requests to perform PUT (update) and DELETE operation.
For this, right click HTTP Request Sample (Post an Item) and add Post Processor → BSF PostProcessor. BSF PostProcessor provides read/write access to JMeter variables
Set the language to Javascript and add the following into the script:
What the above script is doing:
If you look into the “Script” section of the BSF Post Processor, you’ll see the following:
- Script (variables: ctx, vars, props, prev, sampler…)
- vars – stands for JMeterVariables. You can get or set variable values by using vars.
- prev – shorthand to previous SampleResult. In this scenario, it contains the response of the POST request.
- prev.getResponseDataAsString() will extract the response as a string.
Use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object.
For the subsequent requests we need an ID, so we will create a variable called itemId:
You can also use the BeanShell Post Processor to parse the JSON. We can easily invoke Java code in the Beanshell. For this scenario, here is simple way to extract the item ID.
6. Now we will verify the insertion by retrieving the inserted item. For that, again right click Thread Group (Item API Perf Test) and dd Sampler → HTTP Request
- Path: /items/${itenId}
- Method: GET
By adding ${itemId} to the path, the request will be retrieving the single item.
To verify the item inserted, add Response Assertion to the HTTP Request Sample (right click Assertions –> Response Assertion). Response Assertion lets you add pattern strings to be compared against various fields of the response.
For this, select the Text Response radio button for “Response Field to Test”. Set Pattern Matching Rules to “Contains” and add the item name in Patterns to Test.
Please note that if the assertion fails, the test will stop and subsequent requests will be executed.
7. The next step is to update the item added. To do this, add another HTTP Request Sampler. Set the method to PUT and add the item’s new detail as Body Data. Also set the path to /items/${itemId}
8. Now the last step is to delete the item added. For that, also add another HTTP Request Sampler. Set the method to Delete
9. At last we can add different listeners like “View Results Tree” to conclude. To add, right click and select Listeners → View Results Tree.
In the View Results Tree, you can see the request and response data for each sample request.
So the last step is to save and execute the test by pressing the green arrow on the top menu bar.
Here is how the results look in View Results in the Table, which shows a row for every sample request.
Jmeter Post Processor Write To File Format
In this way, we can do the performance as well as functional testing of a RESTful API.
Jmeter Post Processor Write To File Online
By increasing the number of threads and loop count, we can increase the load on the server and measure various vitals of the server and API, such as CPU Utilization and average response time.
- Reply
Hello,
I have captured the json response as a string using:var data = prev.getResponseDataAsString();
Now, I want to add some more items (hardcoded) to this response and send it back as a request. How could i do so.?
Regards,
AmarPlease let me know
- Reply
Hi Amar,
Once you have received the response, you can extract the desired field from the response and then you can use this extracted value along with the hardcoded values in your next request.
e.g.:
Lets assume you have Email id in your response and you have extracted it in variable ’email’.
Now in your next request you can use this variable alongwith other hardcoded values as below:NewEmail = ${email}+”AppendedValue”;
Hope i answered your query.
- Reply
Hi Sukhwinder,
Please share the address of the web service for the above test.
Regards,
Karan - Reply
For customer requirements, I will be following the steps mentioned in /performance-testing-of-a-restful-api-using-jmeter and I wil get back to you for more insights
- Reply
Helllo Sir,
While I am trying to run my jmeter script, I can not able to redirect on home page after login.
Facing below Error on response.
if(“undefined”typeof jQuery)throw new Error(“Bootstrap’s JavaScript requires jQuery”);+function(n){var t=n.fn.jquery.split(” “)[0].split(“.”);if(t[0]<2&&t[1]<9 1t[0]&&9t[1]&&t[2]<1)throw new Error('Bootstrap's JavaScript requires jQuery version 1.9.1 or
Please suggest.
- Reply
I am using JSR223 post processor to extract value from json and the value is stored in a jmeter variable,but I can’t access the jmeter value in http request path by using-${variable}.The value is not at all accesible from GUI mode,but in non gui(On running the script as maven)it is working sometimes
- Reply
Hello Sir, I am testing a website using jmeter. I recorded it using https script recorder.Many http request displayed and all parameters are displayed in the body data part instead of parameter part of http request. Why is that so? How to retrive them?why they are displayed in body data part? Please reply
- Reply
Any method to assert the data, when response is in XML?
- Reply
Hi there
I’ve been trying to send an HTTP request (JSON file) using Jmeter. But I am facing HTTP 400 error.
Tried using cache manager, cookie manager and provided a constant timer so that the requests can go periodically.
Still, I am facing that 400 error issue. There no problem with the URL or the JSON file.
Kindly help me in resolving the 400 Error. - Reply
I have created a test case for login & booking like ola/uber app. I need to pass a user authentication key for next call. For single thread it works. But if i increase thread count, authentication failed response showing. So i need to pass recently executed login authentication key for next call. How do i? Please help me out to execute the load test. I need a beanshell post procesor query to pass recently generated auth key.
Note: Auth key will be generated in first call. Need to save and pass in next call header
My beanshell script is.,
import org.json.JSONObject;
import org.json.JSONArray;
String Response1 = prev.getResponseDataAsString();
JSONObject StrResp1 = new JSONObject(Response1);
JSONObject loginUser = StrResp1.getJSONArray(“detail”).getJSONObject(0).getJSONObject(“auth_details”);
String authToken = loginUser.getString(“auth_key”);
String userId = loginUser.getString(“user_id”);
String userType = loginUser.getString(“user_type”);System.out.println(authToken);
System.out.println(userId);
System.out.println(userType);
vars.put(“accessToken”,authToken);
vars.put(“userid”,userId);
vars.put(“usertype”,userType); - Reply
Hi Sukhwinder,
I have to run an rest api service called “Create Order” i can execute this POST service by giving body with only one user…To execute this service i need to run other 3 service ..How to run all this service together.
- Reply
i need to run an rest api service called create order …to execute that service i need to run other 3 services …how to run this service all together in jmeter
- Reply
HI
I receive an encrypted response, now I want to decrypt it and use that response to be sent to next request. How will this be possible?
- Reply
can you please help to know how to generate performance graphs using jmeter
- Reply
Hello,
Please run the following command, it should generate the performance graph.
Command :
jmeter -g -oPre-Requisite: Generate the CSV file in jmeter
- Reply
I am getting “Too many open files” and “Socket closed” exceptions. How to fix it?
- Reply
Hi,
How will you get the report while running jmeter as non gui mode?No of API (test cases ) =350
- Reply
Hi,
I have to perform the load testing of 10 APIs and their is dependencies of First API to Second API(Token Passing) and so on. The script is running fine for one user when I increased the load of user. The script getting failed in response menu I am getting error “input required” but all the token as has been extracted to the second api from first. Can you help me out in this.
Thanks,
Karan - Reply
Hi Sir,
I have to load 50k users in mongo DB, while running the API using CSV with dynamic data i am getting “end point timeout” and script goes fail.
I am getting this error in login API in which i am getting token using json extractor.
Adding ramp up time resolve this issue ? or please suggest me the best way to deal with it.
- Reply
Hi
I receive an encrypted response, now I want to decrypt it and use that response to be sent to next request. How will this be possible? - Reply
I’m trying to run POST method api web service. I need to parameterise 2 fields from the request body. I’m not able to paramaterise the fields from request body using csv set config. When I enter values in the csv files, first parameter value is replaced with first row values. 2nd parameter field is not at all replaced with any value. Please can you parameterise values from “body data” instead from “parameters”?
Thank you
- Reply
How to handle POST request with both parameters and body.
Thanks in advance.
- Reply
Does JMeter 5.0 support PATCH rest call ?
I see it in the dropdown in HTTP Request , but getting error as below.
java.net.ProtocolException: Invalid HTTP method: PATCH
at java.net.HttpURLConnection.setRequestMethod(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.setRequestMethod(Unknown Source)
at org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.setupConnection(HTTPJavaImpl.java:193)
at org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.sample(HTTPJavaImpl.java:536)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerProxy.sample(HTTPSamplerProxy.java:67)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1231)
at org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase.sample(HTTPSamplerBase.java:1220)
at org.apache.jmeter.threads.JMeterThread.doSampling(JMeterThread.java:622)
at org.apache.jmeter.threads.JMeterThread.executeSamplePackage(JMeterThread.java:546)
at org.apache.jmeter.threads.JMeterThread.processSampler(JMeterThread.java:486)
at org.apache.jmeter.threads.JMeterThread.run(JMeterThread.java:253)
at java.lang.Thread.run(Unknown Source) - Reply
Hi Sukhwinder,
Thanks for sharing this post.
I have requirement where I want to run the multiple requests sequentially like one after another.
Could you please provide your inputs to achieve that.
Leave a Reply
- Learn More