How to extract values from JSON response in Postman? - postman

I have a JSON Response :
[{
"dateTime": 1603650600000,
"supplierName": "Mr Orange GP ",
"gender": "male",
"supplierId": "788",
"appointmentId": 454687,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603650600000,
"supplierName": "Mr Kennedy test ",
"gender": "male",
"supplierId": "600",
"appointmentId": 573993,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603651500000,
"supplierName": "Mr Orange GP ",
"gender": "male",
"supplierId": "788",
"appointmentId": 454688,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603651500000,
"supplierName": "Mr Kennedy test ",
"gender": "male",
"supplierId": "600",
"appointmentId": 573994,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}]
I need to extract the values of first occurrence of dateTime, AppointmentId and tentativeAppointmentCode.
Tried below mentioned code but didn't work in this case.
var jsonData=JSON.parse(responseBody);
postman.setEnvironmentVariable("dateTime",jsonData.dateTime);
How can I extract these values and store in a variable so that I can use it in other requests?

Assuming, by "reservation ID" you mean tentativeAppointmentCode (reservation ID doesn't occur in your response body), the following will do it:
let jsonData = pm.response.json();
pm.environment.set("dateTime",jsonData[0].dateTime);
pm.environment.set("appointmentId",jsonData[0].appointmentId);
pm.environment.set("tentativeAppointmentCode",jsonData[0].tentativeAppointmentCode);

I have done something like this for storing a token for later use
const jsonData = pm.response.json();
pm.environment.set("token", jsonData.access_token);

Related

How to add or remove rest api array list data

I wanna add some data or string to an array list strings in my rest api data, an it's not working.
I don't know why.
Here is my api data which i got from my api in my local server the json data is below here.
"hotels": [ {
"image": "http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg",
"bedPrice": "10",
"roomPrice": "30",
"rooms": "50",
"ac": "yes",
"address": "kaambo",
"latitude": "43.0890",
"laundry": "yes",
"name": "jaabir",
"location": "Bosaso",
"details": "Hosbitaalka Sixa Garoowe waxa ka howlgali doona 23/06/2022 Dr. Ahmed Bashe (abu-shafi) (FCPS MRCS-UK) oo ka socda Hosbitalka Shaafi Muqdisho kuna takhasusay qalliimada LAPAROSCOPY-ga sida Xameetida,Uur-kujirta,Eernada,Burooyinka IWM. Dr-ku wuxuu si joogta ah u imanayaa bil kasta insha allah. Wac: 7747373, 5065444, 5065333.Hosbitaalka Sixa Garoowe waxa ka howlgali doona 23/06/2022 Dr. Ahmed Bashe (abu-shafi) (FCPS MRCS-UK) oo ka socda Hosbitalka Shaafi Muqdisho kuna takhasusay qalliimada LAPAROSCOPY-ga sida Xameetida,Uur-kujirta,Eernada,Burooyinka IWM. Dr-ku wuxuu si joogta ah u imanayaa bil kasta insha allah. Wac: 7747373, 5065444, 5065333.Hosbitaalka Sixa Garoowe waxa ka howlgali doona 23/06/2022 Dr. Ahmed Bashe (abu-shafi) (FCPS MRCS-UK) oo ka socda Hosbitalka Shaafi Muqdisho kuna takhasusay qalliimada LAPAROSCOPY-ga sida Xameetida,Uur-kujirta,Eernada,Burooyinka IWM. Dr-ku wuxuu si joogta ah u imanayaa bil kasta insha allah. Wac: 7747373, 5065444, 5065333.",
"id": "456",
"beds": "100",
"internet": "yes",
"fastfood": "yes",
"longitude": "23.0890",
"images": [
"http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg",
"http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg",
"http://0.0.0.0:8080/uploads/users/IWpEqUWxUxbWsmIoYfUX/95024057775943965869.jpg"
],
"likedUsers": [
"HftAroebyiUhaKSmsyrc"
],
"adress": "laanta hawada"
}
]
And here is dart code.
_likeUser()async{
String api = "http://0.0.0.0:8080/path=hotels/456";
// this list from previous page _data['likedUsers'].toList();
List<String> likes = widget.likedUsers as List<String>;
if(widget.likedUser.contain(widget.currentUser){
setState((){ _isLiked = false;});
var likeRemoved = likes.remove(widget.currentUser);
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": [likeRemoved]
});
}else{
var likeAdded = likes.add(widget.currentUser);
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": [likeAdded]
});
setState((){
_isLiked = true;
});
}
}
The solution is here
_likeUser()async{
String api = "http://0.0.0.0:8080/path=hotels/456";
// this list from previous page _data['likedUsers'].toList();
var likes = widget.likedUsers;
if(widget.likedUser.contain(widget.currentUser){
// i removed item to list in this here
var remove = likes.remove(widget.currentUser);
setState((){ _isLiked = false;});
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": likes,
});
}else{
// i added item to list in this here
var add = likes.add(widget.currentUser);
await http.patch(Uri.parse(api), body: json.encode(<String, Object>{
"likedUsers": likes,
});
setState((){
_isLiked = true;
});
}
}

Postman: How to validate a response to have a correct date format

Just can´t find how to validate the response to be in a date format like: 2014-07-14T21:15:58+00:00
pm.test("Validate dateCreated", function () {
pm.expect(jsonData.data[0].dateCreated == ("YYYY-MM-DDTHH:mm:ss")); // timestamp
});
This is my awfull aproach, it validates the result even if I change operators or the date format in the assertion,I tried with $timestamp, and other examples here, but none seems to work please help, thx
The response body is like this
{
"current_page": 1,
"data": [
{
"rn": "1",
"id": 2,
"mxrId": null,
"dateCreated": "2014-07-14T21:15:58+00:00",
"dateModified": "2018-03-16T21:15:13+00:00",
"svsId": "1",
"token": "08A96E05",
"name": "Original Test",
"clientId": 1675,
"projectId": 1,
And this is what i came with, if you find a better way, please let me know.
let dateFormat = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/;
pm.test("Validate dateCreated", function () {
pm.expect(jsonData.data[0].dateCreated).to.match(dateFormat);
});

How can I convert json map to List String?

I need to get country name and country code into List as "Andorra (AD)". I can load json to a map but I cannot convert to List. How can I convert json map to List String?
"country": [
{
"countryCode": "AD",
"countryName": "Andorra",
"currencyCode": "EUR",
"isoNumeric": "020"
},
You can use the .map() function
var countryList = country.map((c) => '${c["countryName"]} (${c["countryCode"]})').toList()

Repeatedly send API request based on parameters in Postman

I have a database table with approx 4,000 records (currently). A response to an API call (POST, JSON) gives me data of this table for a maximum of 1,000 records per API call. A parameter ‘PageNo’ defines which of the 4,000 records are selected (e.g. PageNo = 1 gives me record 1-1000). The header data of the response includes a ‘PageCount’, in my example 4. I am able to retrieve that ‘PageCount’ and the test below loops through the PageNo (result in Postman Console = 1 2 3 4).
How I can call the same request repeatedly in a loop and use the values of the PageNo (i) as a parameter for that request like so:
{{baseUrl}}/v1/Units/Search?PageNo={{i}}
In my example I would expect the request to run 4 times with PageNo2 = 1, 2, 3, 4.
I am aware that I can use a CSV file and loop through the request in Collection Runner but PageCount changes (i.e. the number of records in the table change) and I need to run this loop frequently so creating a new CSV file for each loop is not really an option.
Postman Test:
pm.environment.set('Headers2', JSON.stringify(pm.response.headers));
var Headers2 = JSON.stringify(pm.response.headers);
pm.environment.set('PageCount2', JSON.parse(Headers2)[10].value);
var i;
for (i = 1; [i] <= pm.environment.get('PageCount2'); i++) {
console.log(i);
postman.setNextRequest('custom fields | json Copy');
}
Postman Request:
{
"Location":"{{TestingLocation}}",
"Fields":[
"StockNo",
"BrandDesc"
],
"Filters": {
"StatusCode":"{{TestingUnitSearchStatusCode}}"
},
"PageSize":1000,
"PageNo" : "{{i}}"
}
With postman.setNextRequest() you can set the calling request as the same request. But you need an exit strategy, otherwise that request would be called infinite times. This only works with the collection runner.
On your first(!) request, store the amount of pages and create a counter.
Increment the counter. If it is smaller than the amount of pages, set the current request as the next request.
Else, do not set a next request. The collection runner will continue with its normal flow. Optionally remove the pages and counter variables.
You can let the request detect that it is its first iteration by not having initialized the amount of pages and counter variables.
Performed a POC for your use-case using postman-echo API.
Pre-req script --> Takes care of the initial request to the endpoint to retrieve the PageSize and set it as an env var. Also initializes the iterationCount to 1 (as env var)
Test Script --> Checks for the current iteration number and performs tests.
Here's a working postman collection.
If you're familiar with newman, you can just run:
newman run <collection-name>
You can also import this collection in Postman app and use collection runner.
{
"info": {
"_postman_id": "1d7669a6-a1a1-4d01-a162-f8675e01d1c7",
"name": "Loop Req Collection",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
},
"item": [
{
"name": "Run_Req",
"event": [
{
"listen": "test",
"script": {
"id": "dac5e805-548b-4bdc-a26e-f56500414208",
"exec": [
"var iterationCount = pm.environment.get(\"iterationCount\");",
"if (pm.environment.get(\"iterationCount\") <= pm.environment.get(\"pageSize\")) {",
" console.log(\"Iteration Number: \" + iterationCount);",
"",
" pm.test(\"Status code is 200\", function() {",
" pm.response.to.have.status(200);",
" });",
"",
" pm.test(\"Check value of pageNo in body is equal to iterationCount\", function() {",
" var jsonData = pm.response.json();",
" return jsonData.json.PageNo == iterationCount;",
"",
" });",
" iterationCount++;",
" pm.environment.set(\"iterationCount\", iterationCount);",
" postman.setNextRequest('Run_Req');",
"}",
"if (pm.environment.get(\"iterationCount\") > pm.environment.get(\"pageSize\")) {",
" console.log(\"Cleanup\");",
" pm.environment.unset(\"pageSize\");",
" pm.environment.set(\"iterationCount\", 1);",
" postman.setNextRequest('');",
" pm.test(\"Cleanup Success\", function() {",
" if (pm.environment.get(\"pageSize\") == null && pm.environment.get(\"iterationCount\") == null) {",
" return true;",
" }",
" });",
"}"
],
"type": "text/javascript"
}
},
{
"listen": "prerequest",
"script": {
"id": "3d43c6c7-4a9b-46cf-bd86-c1823af5a68e",
"exec": [
"if (pm.environment.get(\"pageSize\") == null) {",
" pm.sendRequest(\"https://postman-echo.com/response-headers?pageSize=4\", function(err, response) {",
" var pageSize = response.headers.get('pageSize');",
" var iterationCount = 1;",
" console.log(\"pre-req:pageSize= \" + pageSize);",
" console.log(\"pre-req:iterationCount= \" + iterationCount);",
" pm.environment.set(\"pageSize\", pageSize);",
" pm.environment.set(\"iterationCount\", iterationCount);",
" });",
"",
"}"
],
"type": "text/javascript"
}
}
],
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"name": "Content-Type",
"value": "application/json",
"type": "text"
}
],
"body": {
"mode": "raw",
"raw": "{\n \"Location\":\"{{TestingLocation}}\",\n \"Fields\":[\n \"StockNo\",\n \"BrandDesc\"\n ],\n \"Filters\": {\n \"StatusCode\":\"{{TestingUnitSearchStatusCode}}\"\n },\n \"PageSize\":1000,\n \"PageNo\" : \"{{iterationCount}}\"\n}"
},
"url": {
"raw": "https://postman-echo.com/post",
"protocol": "https",
"host": [
"postman-echo",
"com"
],
"path": [
"post"
]
}
},
"response": []
}
]
}

Regex to find State and Zip from Address

Trying to make regex that can get state from address
1- 1234 Bellaire Blvd, Suite 123, Houston, TX 77036
2- 1234 BELLAIRE BL #123, HOUSTON, TX 77036
I have this for state
\w{2}(?=\s\d{1,5})
And this for Zip
(?<=\w{2}\s)\d{5}
FOR STATE
In 1st case above regex is returning "te" from "Suite" and TX for state which is correct
However, in 2nd case it is returning nothing
FOR ZIP
77036 is returned in 1st case and null is returned in 2nd case
I don't think regular expressions are the best way to do this. Rather I'd use an API to parse the address into it's components. You will need state_abbreviation and you're sorted. Example response:
[
{
"input_index": 0,
"candidate_index": 0,
"delivery_line_1": "1 Santa Claus Ln",
"last_line": "North Pole AK 99705-9901",
"delivery_point_barcode": "997059901010",
"components": {
"primary_number": "1",
"street_name": "Santa Claus",
"street_suffix": "Ln",
"city_name": "North Pole",
"state_abbreviation": "AK",
"zipcode": "99705",
"plus4_code": "9901",
"delivery_point": "01",
"delivery_point_check_digit": "0"
},
"metadata": {
"record_type": "S",
"zip_type": "Standard",
"county_fips": "02090",
"county_name": "Fairbanks North Star",
"carrier_route": "C004",
"congressional_district": "AL",
"rdi": "Commercial",
"elot_sequence": "0001",
"elot_sort": "A",
"latitude": 64.75233,
"longitude": -147.35297,
"precision": "Zip8",
"time_zone": "Alaska",
"utc_offset": -9,
"dst": true
},
"analysis": {
"dpv_match_code": "Y",
"dpv_footnotes": "AABB",
"dpv_cmra": "N",
"dpv_vacant": "N",
"active": "Y",
"footnotes": "L#"
}
},
{
"input_index": 1,
"candidate_index": 0,
"addressee": "Apple Inc",
"delivery_line_1": "1 Infinite Loop",
// truncated for brevity
}
]
Hope that helped.
You can match against ', ([A-Z]{2}) ' the state will then be the subpattern matched by the parentheses. In python it would look like this.
import re
s1 = "1- 1234 Bellaire Blvd, Suite 123, Houston, TX 77036"
s2 = "2- 1234 BELLAIRE BL #123, HOUSTON, TX 77036"
m = re.search(', ([A-Z]{2}) ', s1)
print(m.group(1))