> ## 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.

# Code examples

> Copy code samples for book creation, sorting by creation date, handling removed title sorting, and tracking performance with `hitCount`.

The following Python example demonstrates how to create a new book, check the initial `hitCount`, finalize it, and poll the `hitCount` over time to observe buyer activity.

For production use, implement comprehensive error handling for `401`, `429`, and network timeout scenarios. See [Monitor rate limits](/how-to-guides/how-to-guides-monitor-rate-limits), [API endpoints error codes](/reference/reference-api-endpoints#error-codes), and [API endpoints parameters](/reference/reference-api-endpoints#get-all-books) for details.

## Create and track book views

The following Python example demonstrates how to create a new book, check the initial `hitCount`, finalize it, and track the `hitCount` as simulated views are made.

```python theme={null}
import requests
import time
import uuid

BASE_URL = "https://api.bookhub.com/api/v2"
TOKEN = "YOUR_JWT_TOKEN"

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Content-Type": "application/json"
}

# 1. Create a new book
book_data = {
    "title": "Data-Driven Publishing",
    "author": "Sarah Analytics",
    "description": "Understanding metrics in modern publishing",
    "language": "en-US",
    "publisher": "TechBooks Publishing",
    "publishedDate": "2026-01-15",
    "isbn": "978-0-9876-5432-1",
    "price": 29.99,
    "coverImages": ["https://example.com/cover.jpg"],
    "genres": ["Business", "Technology"],
    "bookFormat": "Paperback"
}

create_response = requests.post(
    f"{BASE_URL}/books",
    headers={**headers, "Idempotency-Key": str(uuid.uuid4())},
    json=book_data
)

if create_response.status_code == 201:
    book_id = create_response.json()['data']['bookId']
    print(f"✓ Book created: {book_id}")
    
    # 2. Check initial hit count
    detail_response = requests.get(
        f"{BASE_URL}/books/{book_id}",
        headers=headers
    )
    book = detail_response.json()['data']
    print(f"Initial hit count: {book['hitCount']}")  # Note: only buyer requests increment hitCount; authenticated publisher requests (like this one) do not
    
    # 3. Finalize the book
    finalize_response = requests.patch(
        f"{BASE_URL}/books/{book_id}/finalize",
        headers=headers,
        json={"notes": "Ready for publication."}
    )
    
    if finalize_response.status_code == 200:
        print("✓ Book finalized and now ACTIVE")
        
        # 4. Poll hitCount over time — the value reflects real buyer traffic,
        #    not these publisher requests, which don't increment it
        for i in range(5):
            time.sleep(1)
            view_response = requests.get(
                f"{BASE_URL}/books/{book_id}",
                headers=headers
            )
            hit_count = view_response.json()['data']['hitCount']
            print(f"Poll #{i+1}: hitCount is {hit_count}")

else:
    print(f"Error creating book: {create_response.status_code}")
    print(create_response.json())
```

## List books with client-side title sort

The following JavaScript example demonstrates how to retrieve a list of books sorted by creation date and then sort them by title on the client side.

```javascript theme={null}
const axios = require('axios');

const BASE_URL = 'https://api.bookhub.com/api/v2';
const TOKEN = 'YOUR_JWT_TOKEN';

const headers = {
  'Authorization': `Bearer ${TOKEN}`
};

async function getBooksWithTitleSort(ascending = true) {
  try {
    // Fetch books sorted by creation date (only option in v2)
    const response = await axios.get(`${BASE_URL}/books`, {
      params: {
        limit: 100,
        sort: 'createdDate',
        order: 'desc'
      },
      headers: headers
    });
    
    const books = response.data.data.books;
    console.log(`✓ Fetched ${books.length} books`);
    
    // Sort by title on client side
    const sortedBooks = books.sort((a, b) => {
      const titleA = a.title.toLowerCase();
      const titleB = b.title.toLowerCase();
      
      if (ascending) {
        return titleA.localeCompare(titleB);
      } else {
        return titleB.localeCompare(titleA);
      }
    });
    
    console.log('\nBooks sorted by title (client-side):');
    sortedBooks.slice(0, 10).forEach((book, index) => {
      console.log(`${index + 1}. ${book.title}`);
    });
    
    return sortedBooks;
    
  } catch (error) {
    if (error.response && error.response.status === 400) {
      console.error('❌ Invalid request:', error.response.data.message);
    } else {
      console.error('❌ Error:', error.message);
    }
  }
}

// Run the example
getBooksWithTitleSort(true);
```

## Handle removed title sorting

The following Java example demonstrates how to handle an error when attempting to use the removed `sort=title` parameter in the BookHub Publisher API v2. The API will return a `400 Bad Request` error with a message indicating that only `sort=createdDate` is supported.

```java theme={null}
import java.net.http.*;
import java.net.URI;
import com.google.gson.*;

public class BookHubV2Client {
    private static final String BASE_URL = "https://api.bookhub.com/api/v2";
    private static final String TOKEN = "YOUR_JWT_TOKEN";
    
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        
        // Build request with only a valid v2 sort parameter
        String url = BASE_URL + "/books?sort=createdDate&order=desc&limit=50";
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Authorization", "Bearer " + TOKEN)
            .GET()
            .build();
        
        HttpResponse<String> response = client.send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );
        
        if (response.statusCode() == 200) {
            Gson gson = new Gson();
            JsonObject jsonResponse = gson.fromJson(
                response.body(),
                JsonObject.class
            );
            
            JsonArray books = jsonResponse
                .getAsJsonObject("data")
                .getAsJsonArray("books");
            
            System.out.println("✓ Fetched " + books.size() + " books");
            System.out.println("Sorted by creation date (newest first):");
            
            for (int i = 0; i < Math.min(5, books.size()); i++) {
                JsonObject book = books.get(i).getAsJsonObject();
                System.out.printf(
                    "%d. %s - Created: %s%n",
                    i + 1,
                    book.get("title").getAsString(),
                    book.get("createdDate").getAsString()
                );
            }
        } else if (response.statusCode() == 400) {
            System.err.println("❌ Bad request - check sort parameter");
            System.err.println("v2 only supports sort=createdDate");
            System.err.println(response.body());
        }
    }
}
```

## Track high-performing books with `hitCount`

The following PHP example demonstrates how to retrieve a list of active books, check their `hitCount`, and identify high-performing books with more than 500 views.

```php theme={null}
<?php

$base_url = 'https://api.bookhub.com/api/v2';
$token = 'YOUR_JWT_TOKEN';

$headers = [
    'Authorization: Bearer ' . $token,
    'Content-Type: application/json'
];

function getBookDetails($book_id, $base_url, $headers) {
    $ch = curl_init("$base_url/books/$book_id");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        return null;
    }
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($status_code === 200) {
        return json_decode($response, true)['data'];
    }
    return null;
}

function getAllBooks($base_url, $headers, $status = 'ACTIVE') {
    $ch = curl_init("$base_url/books?status=$status&limit=100&sort=createdDate");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $response = curl_exec($ch);
    if ($response === false) {
        curl_close($ch);
        return [];
    }
    curl_close($ch);
    
    return json_decode($response, true)['data']['books'];
}

// Get all active books
$books = getAllBooks($base_url, $headers);

// Analyze hit counts
$high_performers = [];
foreach ($books as $book) {
    $details = getBookDetails($book['bookId'], $base_url, $headers);
    if ($details && $details['hitCount'] > 500) {
        $high_performers[] = [
            'title' => $details['title'],
            'hitCount' => $details['hitCount']
        ];
    }
}

// Sort by hit count
usort($high_performers, function($a, $b) {
    return $b['hitCount'] - $a['hitCount'];
});

echo "High-Performing Books (500+ views):\n";
foreach ($high_performers as $index => $book) {
    echo ($index + 1) . ". {$book['title']} - {$book['hitCount']} views\n";
}
?>
```

## Next steps

Explore related topics:

### Conceptual guides

* [Using the `hitCount` field for analytics](/conceptual-guides/conceptual-guides-hitcount-analytics) — Learn how `hitCount` tracks customer interest in specific titles.

### How-to guides

* [Rank books by hitCount to find top performers](/how-to-guides/how-to-guides-use-hitcount-to-track-book-performance) — Use the `hitCount` field to rank books by buyer interest and flag your top performers.

### Reference

* [Release notes](/reference/reference-release-notes) — Explore all changes in BookHub Publisher API v2.
* [API endpoints](/reference/reference-api-endpoints) — Explore all available API endpoints and their parameters for BookHub Publisher API v2.

***


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