> ## Documentation Index
> Fetch the complete documentation index at: https://galejames.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Migrate away from title sorting

> Update your code so it no longer uses title sorting in BookHub Publisher API v2.

The `GET /v2/books` endpoint no longer supports the `sort=title` parameter. Replace it with `sort=createdDate` or implement client-side sorting.

## Prerequisites

Before you begin, ensure you meet the following prerequisites:

* Familiarity with BookHub Publisher API v1.
* Access to your codebase that integrates with the BookHub Publisher API.
* A valid JWT for authentication.

## Step 1: Audit your codebase for `sort=title` parameters

```bash theme={null}
# Search your codebase
grep -r "sort=title" .
grep -r "sort.*title" .
```

You should see a list of all instances where `sort=title` or `sort.*title` appears.

## Step 2: Replace with `sort=createdDate` or client-side sorting

To update your code, replace any instances of `sort=title` with either `sort=createdDate` or client-side sorting. Option A uses the API's `sort=createdDate` parameter to return results pre-sorted. Option B fetches unsorted results and sorts them in your application code. Here are examples of both approaches:

### Before (v1)

```python theme={null}
response = requests.get(f"{BASE_URL}/v1/books", params={"sort": "title", "order": "asc"})
```

### After (v2) option A: `sort=createdDate` (recommended)

```python theme={null}
response = requests.get(f"{BASE_URL}/v2/books", params={"sort": "createdDate", "order": "desc"})
```

### After (v2) option B: client-side sorting

> [!WARNING]
>
> Client-side sorting requires fetching all books. For large catalogs, this may hit rate limits (150 requests per minute) or impact performance. Use `sort=createdDate` where possible.

When fetching books, you can sort them by title on the client side after retrieving the data. Here's an example of how to do this in Python:

> [!NOTE]
>
> This example fetches up to 100 books in a single request. For catalogs larger than 100 books, paginate through all pages before sorting. See [Handle pagination](/how-to-guides/how-to-guides-handle-pagination) for details.

```python theme={null}
import requests

def get_books_sorted_by_title(ascending=True):
    # Fetch all books (or paginate through all pages)
    response = requests.get(
        "https://api.bookhub.com/api/v2/books",
        params={"limit": 100},
        headers={"Authorization": f"Bearer {token}"}
    )
    response.raise_for_status()
    books = response.json()['data']['books']
    
    # Sort by title on client side
    return sorted(
        books,
        key=lambda x: x.get('title', '').lower(),
        reverse=not ascending
    )
```

## Response

A successful `GET /v2/books` request using `sort=createdDate` returns `200 OK`:

```json theme={null}
{
  "status": "success",
  "data": {
    "books": [
      {
        "bookId": "123e4567-e89b-41d4-a716-426614174000",
        "title": "The Great Adventure",
        "author": "Jane Smith",
        "status": "ACTIVE",
        "price": 24.99,
        "createdDate": "2024-12-25T10:30:00Z",
        "updatedDate": "2024-12-26T15:45:00Z"
      },
      {
        "bookId": "123e4567-e89b-41d4-a716-426614174001",
        "title": "Mystery at Midnight",
        "author": "Bob Johnson",
        "status": "ACTIVE",
        "price": 19.99,
        "createdDate": "2024-12-24T14:20:00Z",
        "updatedDate": "2024-12-24T14:20:00Z"
      }
    ],
    "pagination": {
      "currentPage": 1,
      "totalPages": 1,
      "totalItems": 87,
      "itemsPerPage": 100
    }
  }
}
```

Passing `order=desc` returns books newest first, `order=asc` for oldest first.

See [Get all books](/reference/reference-api-endpoints#get-all-books) for all available parameter values.

## Step 3: Verify your changes

Send a test request and confirm the response returns `200 OK` with books ordered by `createdDate`. For catalogs larger than 100 books, run the pagination test from [Handle pagination](/how-to-guides/how-to-guides-handle-pagination) to verify all pages return correctly.

```bash theme={null}
curl -X GET "https://api.bookhub.com/api/v2/books?sort=createdDate&order=desc" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"
```

Verify the first book in the response has the most recent `createdDate`.

If your code still passes `sort=title`, v2 returns a `400` error:

```json theme={null}
{
  "status": "error",
  "message": "Validation failed",
  "errors": [
    {
      "field": "sort",
      "error": "INVALID_VALUE",
      "description": "sort must be createdDate. Title sorting was removed in v2.",
      "validation_context": {
        "rule": "allowed_values",
        "constraint": {
          "allowed": [
            "createdDate"
          ]
        },
        "provided_value": "title"
      }
    }
  ]
}
```

Then handle it in your code:

```python theme={null}
import requests
BASE_URL = "https://api.bookhub.com/api"

def get_books(sort_by='createdDate', order='desc', retry=True):
    # retry=False prevents infinite loops if the fallback also fails 
    params = {'sort': sort_by, 'order': order}
    response = requests.get(f"{BASE_URL}/v2/books", params=params)
    
    if response.status_code == 400 and retry:
        error_data = response.json()
        errors = error_data.get('errors', [])
        for error in errors:
            if error.get('field') == 'sort':
                print(f"Invalid sort parameter: {error.get('description')}")
                return get_books(sort_by='createdDate', order=order, retry=False)
    
    return response.json()
```

### Error handling

| Code | Cause | Resolution |
| - | - | - |
| `400` | Bad request (for example, sorting by `title` is invalid) | Use `createdDate` for sorting instead. |
| `401` | Unauthorized (for example, a missing or invalid JWT) | If you receive a `401`, check your JWT and try again. |
| `429` | Rate limit exceeded (for example, 150 requests per minute) | Wait until the time in the `X-RateLimit-Reset` header, then retry. See [Monitor rate limits](/how-to-guides/how-to-guides-monitor-rate-limits). |

## Next steps

Explore related topics:

### How-to guides

* [Migrate to BookHub Publisher API v2](/how-to-guides/how-to-guides-migrate-bookhub) — Update your code to use BookHub Publisher API v2’s new features.

### Reference

* [Release notes](/reference/reference-release-notes) — Explore all changes in BookHub Publisher API v2.
* [Breaking changes in v2](/reference/reference-breaking-changes) — Details all breaking changes in v2 of the BookHub Publisher API.
* [API endpoints](/reference/reference-api-endpoints) — Provides additional information about the BookHub Publisher API v2 endpoints, including business rules.
* [Code examples](/reference/reference-code-examples) — Copy code samples for book creation, sorting by creation date, handling removed title sorting, and tracking performance with `hitCount`.

***


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.