I am working on a scenario where I'm calling a Web API and doing a computation based on the results in the data
section of the JSON. However, the response of API is paginated, like so:
{
"page": 1,
"per_page": 5,
"total": 500,
"total_pages": 100,
"data": [
{
"competition": "UEFA Champions League",
"year": 2011,
"round": "GroupH",
"team1": "Barcelona",
"team2": "AC Milan",
"team1goals": "2",
"team2goals": "2"
},
{
"competition": "UEFA Champions League",
"year": 2011,
"round": "GroupG",
"team1": "APOEL Nikosia",
"team2": "Zenit St. Petersburg",
"team1goals": "2",
"team2goals": "1"
},
{
"competition": "UEFA Champions League",
"year": 2011,
"round": "GroupF",
"team1": "Borussia Dortmund",
"team2": "Arsenal",
"team1goals": "1",
"team2goals": "1"
}
}
For me to get to the next page to get more data, I have to pass the page
number in the QueryString like so:
https://jsonmock.hackerrank.com/api/football_matches?year=2011&page=2
So I have put this in a for loop to iterate thru those 100 pages to compute the result. And as I am iterating thru the 100 pages, I get an execution Time Limit Exceeded (TLE) error before the code could get to the 7th page in the loop. Here is my code:
public class Program
{
public static void Main()
{
int year = 2011;
var result = Result.getNumDraws(year);
Console.WriteLine("Match drawn = " + result);
}
}
class Result
{
public static int getNumDraws(int year)
{
var totalDrawn = 0;
HttpClient client = new HttpClient();
var baseURL = "https://jsonmock.hackerrank.com/api/football_matches?year=" + year.ToString();
var current = client.GetAsync(baseURL).Result;
var result = JsonConvert.DeserializeObject<ApiResponse>(current.Content.ReadAsStringAsync().Result);
for (int i = 1; i <= result.TotalPages; i++)
{
Console.WriteLine("iterating thru pages = " + i);
var response = GetMatchInfo(year, i);
foreach (var match in response.data)
{
if (match.team1goals == match.team2goals)
totalDrawn++;
}
}
return totalDrawn;
}
public static ApiData GetMatchInfo(int year, int page)
{
var url = "https://jsonmock.hackerrank.com/api/football_matches?year=" + year.ToString() + "&page=" + page;
using (HttpClient client = new HttpClient())
{
var currentData = client.GetAsync(url).Result;
var response = JsonConvert.DeserializeObject<ApiData>(currentData.Content.ReadAsStringAsync().Result);
return response;
}
}
}
public class ApiResponse
{
public string Page { get; set; }
public int Total { get; set; }
[JsonProperty("total_pages")]
public int TotalPages { get; set; }
}
public class ApiData
{
public List<Goal> data { get; set; }
}
public class Goal
{
public int team1goals { get; set; }
public int team2goals { get; set; }
}
Could you please guide me on what tweak or update I need to make in my code to address the Execution Time Limit error?
Thank you.