# Sorting and paging

Source: https://help.ruuster.com/idx/guide-sorting-paging

> Sort results, page through them with page and limit, keep the order stable across pages, and page the feeds and lists that use a cursor.

## Sorting

`sort` picks the order of a search:

| Value | Order |
|---|---|
| `recommended` | The default: the order Ruuster's own search shows |
| `featured` | Featured listings first |
| `price_reduced` | Recent price changes first |
| `oldest` | Longest on the market first |
| `price_desc`, `price_asc` | Highest or lowest price first |
| `beds_desc`, `baths_desc` | Most bedrooms or bathrooms first |
| `sqft_desc`, `lot_desc` | Largest home or lot first |
| `close_date_desc` | Most recently sold first, for sold searches |
| `newest` | First on the market most recently first (a future date counts as today; listings without one come last) |

**Combining pages.** Listings change during the day, so when you combine pages from separate calls,
keep each listing once by its `id`.

## Paging a search

A search pages with `page` (from 1) and `limit` (results per page):

- `limit` is 1 to 50, and 10 when you leave it out. Map pins (`view=map`) come back up to 200 on one
  page.
- `page` goes up to 40, and `page` times `limit` can be at most 2,000. A deeper page answers 400
  `page_depth_exceeded`. Narrow the search instead: a visitor never needs result 2,001, and a sitemap
  uses the listing ids feed.
- `data.total` is the exact number of matches and `data.pages` is how many pages you can link to,
  already capped by those limits. Use `data.pages`, not `total / limit`, for your page links.

cURL:

```bash
curl -s -G "https://idx.ruuster.com/v1/listings" \
  --data-urlencode zip=30308 \
  --data-urlencode sort=price_desc \
  --data-urlencode page=2 \
  --data-urlencode limit=24 \
  -H "Authorization: Bearer $IDX_SECRET_KEY"
```

TypeScript:

```typescript
import { createClient } from "@ruuster/idx";

const idx = createClient({ secretKey: process.env.IDX_SECRET_KEY });

const r = await idx.search({
  zip: "30308",
  sort: "price_desc",
  page: 2,
  limit: 24,
});
if (!r.ok) throw new Error(`${r.error.code}: ${r.error.message}`);
console.log(r.data);
```

Python:

```python
import os

import requests

res = requests.get(
    "https://idx.ruuster.com/v1/listings",
    params={
        "zip": "30308",
        "sort": "price_desc",
        "page": "2",
        "limit": "24",
    },
    headers={"Authorization": "Bearer " + os.environ["IDX_SECRET_KEY"]},
    timeout=30,
)
body = res.json()
if not body["ok"]:
    raise RuntimeError(body["error"]["code"] + ": " + body["error"]["message"])
print(body["data"])
```

PHP:

```php
<?php

$query = http_build_query([
    'zip' => '30308',
    'sort' => 'price_desc',
    'page' => '2',
    'limit' => '24',
], '', '&', PHP_QUERY_RFC3986);
$ch = curl_init('https://idx.ruuster.com/v1/listings' . '?' . $query);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('IDX_SECRET_KEY')],
    CURLOPT_TIMEOUT => 30,
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body['ok']) {
    throw new RuntimeException($body['error']['code'] . ': ' . $body['error']['message']);
}
print_r($body['data']);
```

### Page links that search engines follow

Put the page number in the URL, as in `/neighborhoods/midtown?page=2`, and render each page link as a
plain `<a href>`. Send your page's own URL as `pageHref` (without the page number): the answer's
`head.canonical` is then that URL on page 1 and that URL with `?page=N` from page 2 on, so every page
canonicals to itself. The `Pagination` recipe component builds the links, keeps your other query
parameters, leaves `?page` off page 1 and marks the previous and next links.

<figure class="idx-shot"><img src="/idx-docs/screens/ours/pagination-1440.png" alt="Page links (page 2 of 7), on a desktop (1440 px wide)" width="1440" height="900" loading="lazy" decoding="async"><figcaption>The pagination from the search page recipe.</figcaption></figure>

<figure class="idx-shot"><img src="/idx-docs/screens/ours/pagination-375.png" alt="Page links (page 2 of 7), on a phone (375 px wide)" width="375" height="812" loading="lazy" decoding="async"><figcaption>The pagination from the search page recipe.</figcaption></figure>

The markup is `static/html/pagination.html` in `@ruuster/idx-recipes`. The [HTML and CSS recipe](https://help.ruuster.com/idx/recipe-html-css) shows how to fill it and which stylesheet and script to load.

### Don't fetch pages in parallel

Fetch one page at a time, when a visitor asks for it. Keep at most four calls in flight per key, and
never prefetch pages ahead of the visitor: it spends units and rate limit on pages nobody sees.

## Feeds and lists that use a cursor

Three endpoints page with a cursor instead of a page number. Each answer carries `nextCursor`; send it
back as `cursor` for the next page.

- `GET /v1/listings/ids` (secret key): every listing in your boards, for sitemaps. `nextCursor` is
  null at the end. A cursor is tied to your boards: when they change, the API refuses the cursor and you
  start the walk again.
- `GET /v1/changes` (secret key): what changed since a time. `nextCursor` is always set; call again at
  once while `hasMore` is true, and later when it is false. A cursor is valid for seven days.
- `GET /v1/collections`: your saved collections.

[Keeping pages fresh](https://help.ruuster.com/idx/guide-freshness) shows the feeds in use.
