Repeatedly send API request based on parameters in Postman - 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": []
}
]
}

Related

How to work with postman api collection data

I'm very new to Postman Api testing environment, here i got to use this one https://www.getpostman.com/collections/a0afd85b4642ab7251ba
Please how do i get to extract the collection and test it as REST API
I have tried extracted these data
"item": [
{
"name": "GetCustomerSalary_BVN",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"https://login.remita.net/remita/exapp/api/v1/send/api/loansvc/data/api/v2/payday/salary/history/ph"
]
}
},
{
"listen": "prerequest",
"script": {
"type": "text/javascript",
"exec": [
"var merchantId = \"27768931\";",
"var apiKey = \"Q1dHREVNTzEyMzR8Q1dHREVNTw==\";",
"var apiToken = \"SGlQekNzMEdMbjhlRUZsUzJCWk5saDB6SU14Zk15djR4WmkxaUpDTll6bGIxRCs4UkVvaGhnPT0=\";",
"var d = new Date();",
"var requestId = d.getTime();",
"var randomnumber = Math.floor(Math.random() * 1101233);",
"var authorisationCode = randomnumber;",
"var apiHash = CryptoJS.SHA512(apiKey + requestId + apiToken);",
"var authorization = \"remitaConsumerKey=\" + apiKey + \", remitaConsumerToken=\" + apiHash;",
"postman.setGlobalVariable('merchantId', merchantId);",
"postman.setGlobalVariable('apiKey', apiKey);",
"postman.setGlobalVariable('requestId', requestId);",
"postman.setGlobalVariable('authorisationCode', authorisationCode);",
"postman.setGlobalVariable('authorization', authorization);",
"",
"console.log(authorization)"
]
}
}
],
but not sure of what to do next
If you want to run this collection then you can simply import it in your postman and run all APIs at once by 'Run collection'. With this, you can the see response of all APIs (in your case 6 APIs).
If you want to execute all APIs individually and manually then select each API after importing the collection and run them to see the response.

Writing an if statement for the value in a dictionary

I'm taking an intro game design class and am writing a text adventure. I've set up a dictionary for the game map. For example:
"HALLWAY": {
"name": "HALLWAY",
"desc": "This is a hallway in a maze."
"exits": [{
"exit": "NORTH",
"target": "DEADEND"
}],
"items": []
Early on in the game you have the option to "TAKE" an item. IF the player has taken the item I want the target to be a different location (Not a dead end) ELSE the target is a dead end. How can I write the if/else statement into the value of the target? Or is there a more simple way of doing this?
<!DOCTYPE html>
<script>
'use strict';
let input_data = {
"HALLWAY":
{
"name": "HALLWAY"
, "desc": "This is a hallway in a maze."
, "exits": [{ "exit": "NORTH", "target": "DEADEND" }]
, "items": []
}};
//input_data["HALLWAY"]["exits"][0]["exit"] = "SOUTH";
// ABOVE STATEMENT CAN BE USED TO UPDATE THE VALUE
alert("Value of exit: " + input_data["HALLWAY"]["exits"][0]["exit"]);
alert("Value of target: " + input_data["HALLWAY"]["exits"][0]["target"]);
# Now assume that somehow the value of items has changed
# I am doing it manually
input_data["HALLWAY"]["exits"][0]["items"] = { "item1": "value1" };
alert("Value of items: " + input_data["HALLWAY"]["exits"][0]["items"]["item1"]);
# --One way is to ----- this is the condition that you check if the item has changed
if(input_data["HALLWAY"]["exits"][0]["items"] != null)
input_data["HALLWAY"]["exits"][0]["target"] = "target changed";
# ---- the other way --- would be to check the count of items list whether it has changed.
alert("Value of target: " + input_data["HALLWAY"]["exits"][0]["target"]);

jsonPath expression expected value but return list of values

I want to check response "class_type" value has "REGION".
I test springboot API using mockMvc.
the MockHttpServletResponse is like this.
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body =
{"result":true,
"code":200,
"desc":"OK",
"data":{"total_count":15567,
"items": ...
}}
this is whole response object.
Let's take a closer look, especially items.
"items": [
{
"id": ...,
"class_type": "REGION",
"region_type": "MULTI_CITY",
"class": "com.model.Region",
"code": "AE-65GQ6",
...
},
{
"id": "...",
"class_type": "REGION",
"region_type": "CITY",
"class": "com.model.Region",
"code": "AE-AAN",
...
},
I tried using jsonPath.
#When("User wants to get list of regions, query is {string} page is {int} pageSize is {int}")
public void userWantsToGetListOfRegionsQueryIsPageIsPageSizeIs(String query, int page, int pageSize) throws Exception {
mockMvc().perform(get("/api/v1/regions" ))
.andExpect(status().is2xxSuccessful())
.andDo(print())
.andExpect(jsonPath("$.data", is(notNullValue())))
.andExpect(jsonPath("$.data.total_count").isNumber())
.andExpect(jsonPath("$.data.items").isArray())
.andExpect(jsonPath("$.data.items[*].class_type").value("REGION"));
log.info("지역 목록");
}
but
jsonPath("$.data.items[*].class_type").value("REGION")
return
java.lang.AssertionError: Got a list of values ["REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION","REGION"] instead of the expected single value REGION
I want to just check "$.data.items[*].class_type" has "REGION".
How can I change this?
One option would be to check whether you have elements in your array which have the class_type equal to 'REGION':
public static final String REGION = "REGION";
mockMvc().perform(get("/api/v1/regions"))
.andExpect(jsonPath("$.data.items[?(#.class_type == '" + REGION + "')]").exists());

Elasticsearch _reindex fails

I am working on AWS Elasticsearch. It doesn't allow open/close index, so setting change can not be applied on the index.
In order to change the setting of a index, I have to create a new index with new setting and then move the data from the old index into new one.
So first I created a new index with
PUT new_index
{
"settings": {
"max_result_window":3000000,
"analysis": {
"filter": {
"german_stop": {
"type": "stop",
"stopwords": "_german_"
},
"german_keywords": {
"type": "keyword_marker",
"keywords": ["whatever"]
},
"german_stemmer": {
"type": "stemmer",
"language": "light_german"
}
},
"analyzer": {
"my_german_analyzer": {
"tokenizer": "standard",
"filter": [
"lowercase",
"german_stop",
"german_keywords",
"german_normalization",
"german_stemmer"
]
}
}
}
}
}
it succeeded. Then I try to move data from old index into new one with query:
POST _reindex
{
"source": {
"index": "old_index"
},
"dest": {
"index": "new_index"
}
}
It failed with
Request failed to get to the server (status code: 504)
I checked the indices with _cat api, it gives
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open old_index AGj8WN_RRvOwrajKhDrbPw 5 1 2256482 767034 7.8gb 7.8gb
yellow open new_index WnGZ3GsUSR-WLKggp7Brjg 5 1 52000 0 110.2mb 110.2mb
Seemingly some data are loaded into there, just wondering why the _reindex doesn't work.
You can check the status of reindex with api:
GET _tasks?detailed=true&actions=*reindex
There is a "status" object in response which has field "total":
total is the total number of operations that the reindex expects to perform. You can estimate the progress by adding the updated, created, and deleted fields. The request will finish when their sum is equal to the total field.
Link to ES Documentation: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html

YouTube API returns zero results

I'm using YouTube API to retrieve videos data. I have a list of videos IDs.
For some of the videos the results that returns are normal and for some of them the API returns zero results. Via my browser all the results are valid.
Here is my code:
def getVideoDuration(self,videoId):
try:
content = urllib2.urlopen("https://www.googleapis.com/youtube/v3/videos?part=statistics%2C+contentDetails&id=" + videoId +"&key=" + self.DEVELOPER_KEY).read()
jsonContent= json.loads(content)
duration = jsonContent['items'][0].values()[0]['duration']
if len(duration) == 7:
minutes = jsonContent['items'][0].values()[0]['duration'][2]
seconds = jsonContent['items'][0].values()[0]['duration'][4:6]
if len(duration) == 5:
minutes = 0
seconds = jsonContent['items'][0].values()[0]['duration'][2:4]
print minutes,seconds
totalTime = str(minutes) + "." + str(seconds)
return float(totalTime)
except:
return 0.0
For the ID: 'fu5K2cOeD4M' my code return zero results, but via my browser the results are normal (JSON response attached):
{
"kind": "youtube#videoListResponse",
"etag": "\"0KG1mRN7bm3nResDPKHQZpg5-do/wTtZkXqw81l7Hq6-GrLwJ3wRQ5w\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [
{
"kind": "youtube#video",
"etag": "\"0KG1mRN7bm3nResDPKHQZpg5-do/jrxp-dHXG3s3ujaIjyq15GWV7V8\"",
"id": "fu5K2cOeD4M",
"contentDetails": {
"duration": "PT8M15S",
"dimension": "2d",
"definition": "sd",
"caption": "false",
"licensedContent": false
},
"statistics": {
"viewCount": "18358",
"likeCount": "166",
"dislikeCount": "1",
"favoriteCount": "0",
"commentCount": "33"
}
}
]
}
I tried to delay between my requests using time.sleep(), but it didn't help me.
The problem was that i sent the request i added an extra character