How to Loop HTTP Client HTTP request

Category: azure functions

Question

NicoTing on Fri, 01 Mar 2019 01:31:51


Good Day,

On my function v1 app I wrote a framework to handle HTTPCLIENT request/response and connect to our api service, I have a method to get all transactions(with parameters: pageNumber, pageSize), after calling the meththod with pageSize=100, Iam able to get the first 100 elements, but the total elements is lets say 1000, how can I loop my request to call the getTransaction again, if the response has more items or elements

example response:

{  
   "_embedded":{  
      "testTransactions":[  ]
   },
   "_links":{  },
   "page":{  
      "size":100,
      "totalElements":1000,
      "totalPages":10,
      "number":0
   }
} 

Thanks





Replies

DixitArora-MSFT on Mon, 04 Mar 2019 06:17:03


In a loop, you can set the index or flag which will track the row number/rows returned by calling the API.

Again request for the API again, passing the current row index( that will be rows returned from the previous call ) to fetch another batch.

So that it should not start at index = 0 again.

Also follow some best practice for using HTTP Client in Azure Functions.

https://github.com/Azure/azure-functions-host/wiki/Managing-Connections

NicoTing on Mon, 04 Mar 2019 07:32:40


int _pageNumber = 0;
do {
                _response = await _client.TransactionAsync(_pageNumber, 100);
                if(_response != null && _response.saleTransactions != null && _response.page != null) {
                    _pageNumber = _response.page.number + 1;

                    foreach (var item in _response.saleTransactions) {
                        transactions.Add(item);
                    }
                }
                
            } while (_pageNumber <= _response.page.totalPages && transactions.Count() < _response.page.totalElements);