Start learning free

LESSON 11 OF 173 · BACKEND: HOW THE WEB WORKS

Follow the Pages in C#

Practice

A long list is rarely sent in one answer. APIs split it into pages: each answer holds a few items and says which page comes next. You keep asking until there is no next page.

You don't know in advance how many pages there are, so use a while loop that stops when the next page is null. Read next_page with Deserialize<int?>(): an int? is a whole number that can also be null, which is what JSON's null becomes. Here is the same idea on a plain dictionary, following a chain of bus stops:

var nextStop = new Dictionary<string, string?> { ["Home"] = "Park", ["Park"] = "School", ["School"] = null };
string? stop = "Home";
while (stop != null) {
    Console.WriteLine(stop);
    stop = nextStop[stop];
}

The supplier's /catalog has 5 products, 2 per page:

GET /catalog?page=1  →  {"page": 1, "items": ["Mug", "Notebook"], "next_page": 2}
GET /catalog?page=2  →  {"page": 2, "items": ["Lamp", "Pen"], "next_page": 3}
GET /catalog?page=3  →  {"page": 3, "items": ["Plant"], "next_page": null}

Your script must print:

Page 1
Mug
Notebook
Page 2
Lamp
Pen
Page 3
Plant

Your task: start at page 1 and keep asking /catalog for the page that next_page names, until it is null. For each page, print Page and its number, then every product name on it.


Assignment
Follow the Coding Tutorial to read every page of the catalog and print all its products.


Hint
Put the page number at the end of the URL: SUPPLIER + "/catalog?page=" + page. Declare page as an int? so it can hold null, and set it from next_page as the last line of the loop, or the script will ask for page 1 forever.


STEP 1 OF 8
    Ctrl + Enter to check

    Web Pagination in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free