API Versioning, Pagination, Filtering, Sorting, and Documentation

Define extensible list query rules and document a verifiable contract

🎯 Introduction

By the end of this article, you will be able to define pagination, filtering, and sorting parameters and write API documentation the frontend can use directly.

🏷 When is a new version needed?

Suppose the frontend reads name and you rename it to displayName. Existing pages can no longer display the name. Because this breaks existing callers, you can preserve /api/v1/users and return the new field from /api/v2/users.

Adding a field that does not affect existing pages usually needs no new version. Versions distinguish incompatible behavior. Before changing anything, check whether existing clients will still work.


📄 Pagination lets clients read a list in batches

Suppose the database contains five users ordered by ID. Request page two with two records per page:

GET /users?page=2&pageSize=2 HTTP/1.1

The server should skip the first two records and return users 3 and 4. The number skipped is called the offset:

const offset = (2 - 1) * 2;

The result is 2. The first value is the page number; the second is the page size. Validate both as positive integers and cap pageSize, for example at 100. Use the field validation approach from the parameter validation article.

Use pagination in a database query

This function accepts a mysql2 connection and validated numeric page and pageSize values:

user-page.mjs
export async function readUserPage(connection, page, pageSize) {
    const offset = (page - 1) * pageSize;
    const [rows] = await connection.query(
        'SELECT id, username FROM user ORDER BY id LIMIT ? OFFSET ?',
        [pageSize, offset]
    );
    return rows;
}

LIMIT controls the number returned, OFFSET controls the number skipped, and ORDER BY id makes the order explicit. Passing 2 and 2 reads the second pair of records. Do not load all users and slice a page in Node.js memory.


🔎 Filtering returns only matching records

Request users whose names contain “Ming”:

GET /users?name=Ming&page=1&pageSize=10 HTTP/1.1

Document whether name means an exact match or a substring match. Here it means contains. Filter first, then sort and paginate. Taking ten records before filtering can miss matches on other pages.

Pass the client-supplied name as a database parameter; never concatenate it into SQL. Use the parameterized query approach from the MySQL Integration course.


↕️ Expose only explicitly supported sorting options

For example, define two options:

ParameterServer-side ordering
sort=-createdAtNewest creation time first, then ID descending for ties
sort=nameName ascending, then ID ascending for ties

The leading minus sign means descending order in this API's contract. Return 400 for unsupported values rather than inserting arbitrary sort text into SQL.

The additional ID ordering resolves equal names or timestamps so their order does not vary unpredictably between requests. Sorting by creation time requires a corresponding database column.


📤 Return data and pagination metadata

For the second page of the five users above, define this response:

{
    "data": [{ "id": 3, "name": "Lin" }, { "id": 4, "name": "Yu" }],
    "meta": { "page": 2, "pageSize": 2, "total": 5 }
}

data contains the current page; meta describes the page number, page size, and total matching records. The frontend calculates the page count from total and pageSize: three pages here. Count total separately using the same filters; it is not the current array length.

When nothing matches, still return 200 with data set to [] and total to 0. An empty list is a normal result.


📝 Keep the API contract in one document

Include at least the information callers actually need:

ItemContract for this example
Method and pathGET /users
AuthenticationValid login credentials required
pageDefaults to 1; positive integer
pageSizeDefaults to 10; range 1–100
nameOptional; substring match on name
sortDefaults to -createdAt; also accepts name
Success200, body contains data and meta
Invalid parameters400, identifies the invalid parameter
Authentication or authorization error401 or 403

Update documented defaults, fields, and examples alongside the code. A success JSON example alone leaves the frontend guessing about required fields and failure behavior.


❓ Questions and Answers

Q1: Must every list return total?

No. For a “load more” interface, you can return whether another page exists, provided both sides agree on its use.

Q2: What happens if records are added or deleted between pages?

Record positions may shift, so page-based navigation can repeat or skip records. Continuously changing feeds need separately designed stable pagination rules.

Q3: Can the old version be deleted as soon as a new one launches?

First confirm that callers have migrated, then end support according to the agreed policy.


🧪 Practice

Document an avatar list endpoint. Include a page-two request, a success response, an empty result, and the result of an unsupported sort value.

// Record the API contract here