# Pagination

> Page through jobs, candidates, applications and interviews with limit and offset.

Lists that can grow without bound (jobs, candidates, applications, interviews) come a page at a time. Small lists that belong to one thing, like a job's stages or a candidate's notes, come whole, as a plain array.

## Paging

Paged lists take two query parameters:

| Parameter | Default |                                   |
| --------- | ------- | --------------------------------- |
| `limit`   | `50`    | How many to return, from 1 to 100 |
| `offset`  | `0`     | How many to skip                  |

And return the page with the total count:

```json
{
  "items": [
    {
      "id": "7c2e4f1a-9b3d-4e6f-8a1c-2d3e4f5a6b7c",
      "title": "Backend Engineer"
    }
  ],
  "total": 132,
  "limit": 50,
  "offset": 0
}
```

There's more to fetch while `offset + limit < total`. A `limit` over 100 is refused with `422`, rather than quietly cut short.

## Fetching everything


```python
def paginate(client, path, **params):
    offset = 0
    while True:
        page = client.get(path, params={**params, "limit": 100, "offset": offset})
        page.raise_for_status()
        body = page.json()
        yield from body["items"]
        offset += body["limit"]
        if offset >= body["total"]:
            return

for application in paginate(client, "/applications", status="hired"):
    print(application["candidate"]["email"])
```

```js
async function* paginate(path, params = {}) {
  for (let offset = 0; ;) {
    const query = new URLSearchParams({
      ...params,
      limit: "100",
      offset: String(offset),
    });
    const response = await fetch(`https://api.hirehappy.io/v1${path}?${query}`, {
      headers: { Authorization: `Bearer ${process.env.HIREHAPPY_API_KEY}` },
    });
    if (!response.ok) throw new Error(`HireHappy API: ${response.status}`);
    const page = await response.json();
    yield* page.items;
    offset += page.limit;
    if (offset >= page.total) return;
  }
}

for await (const application of paginate("/applications", {
  status: "hired",
})) {
  console.log(application.candidate.email);
}
```


## Order

Each list has a fixed order, given in the [API reference](https://hirehappy.io/docs/api): newest first for jobs, candidates and applications (or best match first, for applications with `sort=score`), and soonest first for interviews.

Pages are counted from the top of the list each time. If items are added while you page through, one may show up twice, so key what you collect by `id`. For a list that changes often, filter it down (by job, status or time) rather than paging through all of it.
