### Install System Prerequisites (Ubuntu) Source: https://context7.com/garethbjohnson/gutendex/llms.txt Installs necessary system packages for Gutendex on Ubuntu 24.04. ```bash # 1. Install system prerequisites (Ubuntu 24) apt install python3-pip python3-venv postgresql ``` -------------------------------- ### Set Up Python Virtual Environment and Install Dependencies Source: https://context7.com/garethbjohnson/gutendex/llms.txt Creates a Python virtual environment and installs project dependencies from requirements.txt. ```bash # 3. Set up a Python virtual environment and install dependencies python3 -m venv venv source venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Install Python Requirements Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Installs all Python packages listed in the 'requirements.txt' file within the activated virtual environment. ```bash pip install -r requirements.txt ``` -------------------------------- ### Run Development Server Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Use this command to start the Django development server for local testing. ```bash ./manage.py runserver ``` -------------------------------- ### Install Apache and WSGI Module (Ubuntu) Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Installs Apache HTTP Server and the WSGI module required for serving Django applications in production on Ubuntu. ```bash apt install apache2 libapache2-mod-wsgi-py3 ``` -------------------------------- ### Book List Query Parameters Example Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Example of a URL query to filter books by author's birth year and publication language. Parameters are added in a typical URL format. ```http /books?author_year_start=1900&languages=en,fr ``` -------------------------------- ### Switch to Postgres User Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Use this command to switch to the user account for PostgreSQL. This may vary depending on your system setup. ```bash su postgres ``` -------------------------------- ### Gutendex Environment Variables Configuration Source: https://context7.com/garethbjohnson/gutendex/llms.txt Example configuration for environment variables in `gutendex/.env`. These control database connection, security settings, static file paths, and email configurations. ```bash # gutendex/.env — copy from gutendex/.env.template and fill in each value SECRET_KEY=your-long-random-secret-key-here DEBUG=false # true for development; NEVER true in production ALLOWED_HOSTS=127.0.0.1,localhost # comma-separated; prefix with . to allow subdomains # PostgreSQL connection DATABASE_NAME=gutendex DATABASE_USER=gutendex DATABASE_PASSWORD=your-db-password DATABASE_HOST=127.0.0.1 DATABASE_PORT=5432 # Directory for serving CSS/JS assets STATIC_ROOT=/var/www/gutendex/static MEDIA_ROOT=/var/www/gutendex/media # Email (used for catalog-update log emails; Mailgun recommended) EMAIL_HOST=smtp.mailgun.org EMAIL_HOST_ADDRESS=gutendex@yourdomain.com EMAIL_HOST_USER=postmaster@mg.yourdomain.com EMAIL_HOST_PASSWORD=your-mailgun-password # Admins receive catalog log emails and Django security warnings ADMIN_NAMES=Alice,Bob ADMIN_EMAILS=alice@example.com,bob@example.com MANAGER_NAMES=Carol MANAGER_EMAILS=carol@example.com ``` -------------------------------- ### Query Books by MIME Type Prefix Source: https://github.com/garethbjohnson/gutendex/blob/master/readme.md Find books with a MIME type starting with a given prefix. The prefix should be URL-encoded. ```url /books?mime_type=text%2F ``` -------------------------------- ### Get Book by ID Source: https://context7.com/garethbjohnson/gutendex/llms.txt Retrieves details for a specific book using its unique ID. Returns a 404 error if the book is not found. ```APIDOC ## GET /books/{id} ### Description Retrieves details for a specific book using its unique ID. ### Method GET ### Endpoint `/books/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the book. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the book. - **title** (string) - The title of the book. - **authors** (array) - List of authors with their birth and death years. - **summaries** (array) - A list of summaries for the book. - **editors** (array) - A list of editors. - **translators** (array) - A list of translators. - **languages** (array) - List of language codes. - **copyright** (boolean) - Indicates if the book is under copyright. - **media_type** (string) - The media type of the book (e.g., "Text"). - **formats** (object) - A map of MIME types to download URLs. - **download_count** (integer) - The number of times the book has been downloaded. - **bookshelves** (array) - List of bookshelves the book belongs to. #### Error Response (404) - **detail** (string) - "Not found." ``` -------------------------------- ### Filter by MIME Type Source: https://context7.com/garethbjohnson/gutendex/llms.txt Filters books that have at least one format whose MIME type starts with the given string. ```APIDOC ## GET /books ### Description Filters books that have at least one format whose MIME type starts with the given string. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **mime_type** (string) - Optional - A string prefix to match against the MIME types of available book formats. ### Request Example ```bash # Books with any text format (text/html, text/plain, etc.) curl "http://localhost:8000/books?mime_type=text%2F" # Books available as HTML specifically curl "http://localhost:8000/books?mime_type=text%2Fhtml" # Books available as EPUB curl "http://localhost:8000/books?mime_type=application%2Fepub%2Bzip" ``` ### Response #### Success Response (200) - **results** (array) - A list of book objects matching the MIME type criteria. #### Response Example ```json { "count": 75, "next": "http://localhost:8000/books?page=2&mime_type=text%2F", "previous": null, "results": [ { "id": 1, "title": "Book with HTML", "formats": { "text/html": "..." }, ... }, { "id": 2, "title": "Book with Plain Text", "formats": { "text/plain": "..." }, ... } ] } ``` ``` -------------------------------- ### Filter Books by MIME Type Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Use the `mime_type` parameter to find books with a specific MIME type. The API matches MIME types starting with the provided value. ```http /books?mime_type=text%2F ``` ```http /books?mime_type=text%2Fhtml ``` -------------------------------- ### Create PostgreSQL Database and User Source: https://context7.com/garethbjohnson/gutendex/llms.txt Sets up the PostgreSQL database and user required by Gutendex. Remember the password entered for the 'gutendex' user. ```bash # 2. Create the PostgreSQL database and user su postgres createdb gutendex createuser -P gutendex # remember the password you enter psql # Inside psql: GRANT ALL PRIVILEGES ON DATABASE gutendex TO gutendex; \c gutendex; GRANT ALL ON SCHEMA public TO gutendex; # Press ctrl+d twice to exit psql and return to root ``` -------------------------------- ### Migrate Gutendex Database Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Run this command to set up the database schema for storing catalog data. Ensure you are in the project's root directory and within the activated virtual environment. ```bash ./manage.py migrate ``` -------------------------------- ### Populate Gutendex Database Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Execute this command to download, decompress, and import Project Gutenberg's catalog data into the Gutendex database. This process can take several minutes. It also emails logs to administrators. ```bash ./manage.py updatecatalog ``` -------------------------------- ### Apache Production Deployment Source: https://context7.com/garethbjohnson/gutendex/llms.txt Instructions for setting up Apache 2 with mod_wsgi to serve Gutendex publicly in a production environment. ```bash # Install Apache and mod_wsgi apt install apache2 libapache2-mod-wsgi-py3 # Edit /etc/apache2/sites-available/000-default.conf # Add the following inside the block, ``` -------------------------------- ### Filter by Author's Lifespan Source: https://context7.com/garethbjohnson/gutendex/llms.txt Filter books based on the lifespan of their authors. You can specify start and end years for when the author was alive. ```APIDOC ## GET /books ### Description Filters books by the lifespan of their authors. You can specify start and end years for when the author was alive. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **author_year_start** (integer) - Optional - The starting year of the author's lifespan. - **author_year_end** (integer) - Optional - The ending year of the author's lifespan. ### Request Example ```bash # Books by authors alive in the 19th century curl "http://localhost:8000/books?author_year_start=1800&author_year_end=1899" # Books by authors alive before 500 BCE curl "http://localhost:8000/books?author_year_end=-499" # Books by 20th-century authors curl "http://localhost:8000/books?author_year_start=1900&author_year_end=1999" ``` ### Response #### Success Response (200) - **results** (array) - A list of book objects matching the criteria. #### Response Example ```json { "count": 100, "next": "http://localhost:8000/books?page=2&author_year_start=1800&author_year_end=1899", "previous": null, "results": [ { ... book object ... }, { ... book object ... } ] } ``` ``` -------------------------------- ### Connect to Gutendex Database Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Opens the PostgreSQL command-line interface. ```bash psql ``` -------------------------------- ### List Books (Default) Source: https://context7.com/garethbjohnson/gutendex/llms.txt Retrieves a paginated list of books, ordered by download popularity by default. Each page contains up to 32 results. ```bash # Default list — most popular books first curl "http://localhost:8000/books" # { # "count": 70893, # "next": "http://localhost:8000/books?page=2", # "previous": null, # "results": [ # { # "id": 1342, # "title": "Pride and Prejudice", # "authors": [{"name": "Austen, Jane", "birth_year": 1775, "death_year": 1817}], # "summaries": [], # "editors": [], # "translators": [], # "subjects": ["Courtship -- Fiction", "England -- Social life and customs -- 19th century -- Fiction"], # "bookshelves": ["Best Books Ever Listings"], # "languages": ["en"], # "copyright": false, # "media_type": "Text", # "formats": { # "text/html": "https://www.gutenberg.org/files/1342/1342-h/1342-h.htm", # "application/epub+zip": "https://www.gutenberg.org/ebooks/1342.epub3.images", # "text/plain; charset=utf-8": "https://www.gutenberg.org/files/1342/1342-0.txt" # }, # "download_count": 44739 # }, # ... # ] # } ``` -------------------------------- ### Fetch Books with Query Parameters Source: https://context7.com/garethbjohnson/gutendex/llms.txt Demonstrates fetching books with multiple query parameters for filtering and sorting. Handles potential HTTP errors and logs results. ```bash # English or French books by 20th-century authors, sorted by Gutenberg ID ascending curl "http://localhost:8000/books?languages=en,fr&author_year_start=1900&author_year_end=1999&sort=ascending" # Public-domain English fiction on a children's topic, available as EPUB curl "http://localhost:8000/books?copyright=false&languages=en&topic=children&mime_type=application%2Fepub%2Bzip" ``` ```javascript fetch('http://localhost:8000/books?search=shakespeare&languages=en&sort=popular') .then(response => { if (!response.ok) throw new Error(`HTTP error: ${response.status}`) return response.json() }) .then(data => { console.log(`Total results: ${data.count}`) console.log(`Next page: ${data.next}`) data.results.forEach(book => { console.log(`[${book.id}] ${book.title} — downloads: ${book.download_count}`) }) }) .catch(err => console.error('Request failed:', err)) ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/garethbjohnson/gutendex/llms.txt Copies the environment template and prompts to edit it with specific values for database connection, static/media roots, and email settings. ```bash # 4. Copy and fill in environment variables cp gutendex/.env.template gutendex/.env # Edit gutendex/.env with your values (see Environment Variables section below) ``` -------------------------------- ### Collect Static Files Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Run this command to gather all necessary static files for styled HTML pages. ```bash ./manage.py collectstatic ``` -------------------------------- ### Configure Apache for Gutendex Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Edit the default Apache site configuration to serve static files, robots.txt, media, and the Gutendex WSGI application. Replace `/path/to/gutendex` with the actual Gutendex path on your server. ```apache Alias /static /path/to/gutendex/static Require all granted Alias /robots.txt /path/to/gutendex/static/robots.txt Alias /media /path/to/gutendex/media Require all granted Require all granted WSGIDaemonProcess gutendex python-home=/path/to/gutendex/venv python-path=/path/to/gutendex WSGIProcessGroup gutendex WSGIScriptAlias / /path/to/gutendex/gutendex/wsgi.py ``` -------------------------------- ### Apache Configuration for Gutendex Source: https://context7.com/garethbjohnson/gutendex/llms.txt Configure Apache to serve Gutendex static files, media, and the WSGI application. Ensure correct paths and permissions are set. ```apacheconf Alias /static /path/to/gutendex/static Require all granted Alias /robots.txt /path/to/gutendex/static/robots.txt Alias /media /path/to/gutendex/media Require all granted Require all granted WSGIDaemonProcess gutendex python-home=/path/to/gutendex/venv python-path=/path/to/gutendex WSGIProcessGroup gutendex WSGIScriptAlias / /path/to/gutendex/gutendex/wsgi.py ``` -------------------------------- ### Switch to Gutendex Database Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Switches the current psql session to the 'gutendex' database. ```sql \c gutendex; ``` -------------------------------- ### Create Python Virtual Environment Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Creates a Python virtual environment named 'venv' and activates it. This isolates project dependencies. ```bash python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### System Commands for Gutendex Deployment Source: https://context7.com/garethbjohnson/gutendex/llms.txt Execute these commands to set file ownership for the Apache user and restart the Apache service. Run collectstatic and restart Apache after any file changes. ```bash # Grant Apache user access to Gutendex files chown :www-data /path/to/gutendex # Start serving service apache2 restart # After any file or static-asset changes: ./manage.py collectstatic service apache2 restart ``` -------------------------------- ### Run `updatecatalog` Management Command Source: https://context7.com/garethbjohnson/gutendex/llms.txt Manages the Project Gutenberg catalog by downloading, decompressing, and syncing data into the database. Can be run manually or scheduled via cron. ```bash # Run manually (takes several minutes on first run) ./manage.py updatecatalog # Schedule daily at 3 AM using cron crontab -e # Add this line: # 0 3 * * * /path/to/gutendex/venv/bin/python /path/to/gutendex/manage.py updatecatalog ``` -------------------------------- ### Populate Project Gutenberg Catalog Data Source: https://context7.com/garethbjohnson/gutendex/llms.txt Downloads, parses, and stores catalog data from Project Gutenberg into the PostgreSQL database. This command can take several minutes to complete. ```bash # 6. Populate the database with Project Gutenberg catalog data (takes several minutes) ./manage.py updatecatalog ``` -------------------------------- ### Retrieve a single book by ID Source: https://context7.com/garethbjohnson/gutendex/llms.txt Returns full details for a single book identified by its Project Gutenberg ID. Returns a `404` with an error object if the ID is not found. ```bash # Retrieve Moby Dick (Project Gutenberg ID 2701) curl "http://localhost:8000/books/2701" ``` -------------------------------- ### Restart Apache Service Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Restart the Apache service to apply the new configuration and serve Gutendex. ```bash service apache2 restart ``` -------------------------------- ### Apply Database Migrations Source: https://context7.com/garethbjohnson/gutendex/llms.txt Applies database schema changes defined in Django migrations. ```bash # 5. Apply database migrations ./manage.py migrate ``` -------------------------------- ### Retrieve specific books by Project Gutenberg IDs Source: https://context7.com/garethbjohnson/gutendex/llms.txt Retrieve a list of books by their Project Gutenberg ID numbers. IDs should be provided as a comma-separated list. ```bash # Fetch Alice's Adventures in Wonderland (11), Through the Looking-Glass (12), and Peter Pan (16) curl "http://localhost:8000/books?ids=11,12,16" ``` -------------------------------- ### Create Gutendex Database Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Command to create a new PostgreSQL database named 'gutendex'. The name can be customized by updating the DATABASE_NAME environment variable. ```bash createdb gutendex ``` -------------------------------- ### Collect Static Files Source: https://context7.com/garethbjohnson/gutendex/llms.txt Gathers all static files (CSS, JavaScript, images) into a single directory for serving. ```bash # 7. Collect static files ./manage.py collectstatic ``` -------------------------------- ### Search Books by Author and Title Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Use the `search` parameter to find books and authors by keywords. Keywords should be space-separated (URL-encoded as %20) and are case-insensitive. ```http /books?search=dickens%20great ``` -------------------------------- ### Set File Permissions for Apache Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Grant Apache's web server user permission to access Gutendex files. Replace `/path/to/gutendex` with the actual Gutendex path on your server. ```bash chown :www-data /path/to/gutendex ``` -------------------------------- ### Create Gutendex User Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Creates a new PostgreSQL user named 'gutendex' and prompts for a password. Remember this password for future use. The username can be changed by updating the DATABASE_USER environment variable. ```bash createuser -P gutendex ``` -------------------------------- ### updatecatalog Management Command Source: https://context7.com/garethbjohnson/gutendex/llms.txt Downloads, processes, and syncs the Project Gutenberg catalog into the database. Emails a log upon completion. ```APIDOC ## ./manage.py updatecatalog ### Description Downloads the full Project Gutenberg RDF catalog, processes it, and syncs the data into the PostgreSQL database. Sends an email with a log of the run to administrators. ### Method Command Line ### Endpoint N/A ### Usage ```bash # Run manually ./manage.py updatecatalog # Schedule daily using cron crontab -e # Add: 0 3 * * * /path/to/gutendex/venv/bin/python /path/to/gutendex/manage.py updatecatalog ``` ### Steps Performed Internally 1. Downloads `https://gutenberg.org/cache/epub/feeds/rdf-files.tar.bz2`. 2. Decompresses files to `catalog_files/tmp/`. 3. Detects and removes stale book entries. 4. Rsyncs updated RDF files into `catalog_files/rdf/`. 5. Parses each `pg.rdf` file and upserts records in the database (Book, Person, Format, Language, Subject, Bookshelf, Summary). 6. Removes temporary files. 7. Emails the run log to `ADMIN_EMAILS`. ``` -------------------------------- ### get_book(id, xml_file_path) Source: https://context7.com/garethbjohnson/gutendex/llms.txt Internal utility to parse a Project Gutenberg RDF XML file into a normalized Python dictionary. ```APIDOC ## get_book(id, xml_file_path) ### Description Parses a Project Gutenberg `.rdf` XML file and returns a normalized Python dictionary containing book data. This is an internal utility function. ### Method Python Function ### Signature `get_book(id: int, xml_file_path: str) -> dict` ### Parameters #### Arguments - **id** (int) - The unique identifier of the book. - **xml_file_path** (str) - The file path to the RDF XML file. ### Returns - A dictionary containing normalized book data, including `id`, `title`, `authors`, `summaries`, `languages`, `formats`, `downloads`, etc. ### Raises - `Exception` - If the XML file cannot be parsed (e.g., missing or malformed). ### Example ```python from books.utils import get_book # Parse a single RDF file for book ID 1342 book_data = get_book(1342, '/path/to/catalog_files/rdf/1342/pg1342.rdf') print(book_data) ``` ``` -------------------------------- ### Query Books by Exact MIME Type Source: https://github.com/garethbjohnson/gutendex/blob/master/readme.md Retrieve books with a specific MIME type. The type should be URL-encoded. ```url /books?mime_type=text%2Fhtml ``` -------------------------------- ### List Books Source: https://context7.com/garethbjohnson/gutendex/llms.txt Returns a paginated list of books ordered by download popularity by default. Each page contains up to 32 results. Supports multiple query parameters for filtering and sorting. ```APIDOC ## GET /books ### Description Returns a paginated list of books ordered by download popularity by default. Each page contains up to 32 results. Supports multiple query parameters for filtering and sorting. ### Method GET ### Endpoint /books ### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **author_year_start** (integer) - Optional - Filters books by authors alive during this year (inclusive). - **author_year_end** (integer) - Optional - Filters books by authors alive during this year (inclusive). ### Request Example ```bash curl "http://localhost:8000/books?page=3" ``` ### Response #### Success Response (200) - **count** (integer) - The total number of books available. - **next** (string) - URL for the next page of results, or null if none. - **previous** (string) - URL for the previous page of results, or null if none. - **results** (array) - An array of book objects. - **id** (integer) - The unique identifier for the book. - **title** (string) - The title of the book. - **authors** (array) - An array of author objects. - **name** (string) - The name of the author. - **birth_year** (integer) - The birth year of the author. - **death_year** (integer) - The death year of the author. - **summaries** (array) - An array of summaries for the book. - **editors** (array) - An array of editor objects. - **translators** (array) - An array of translator objects. - **subjects** (array) - An array of subject strings. - **bookshelves** (array) - An array of bookshelf strings. - **languages** (array) - An array of language codes. - **copyright** (boolean) - Indicates if the book is under copyright. - **media_type** (string) - The media type of the book (e.g., "Text"). - **formats** (object) - An object mapping format types to URLs. - **download_count** (integer) - The number of times the book has been downloaded. #### Response Example ```json { "count": 70893, "next": "http://localhost:8000/books?page=2", "previous": null, "results": [ { "id": 1342, "title": "Pride and Prejudice", "authors": [{"name": "Austen, Jane", "birth_year": 1775, "death_year": 1817}], "summaries": [], "editors": [], "translators": [], "subjects": ["Courtship -- Fiction", "England -- Social life and customs -- 19th century -- Fiction"], "bookshelves": ["Best Books Ever Listings"], "languages": ["en"], "copyright": false, "media_type": "Text", "formats": { "text/html": "https://www.gutenberg.org/files/1342/1342-h/1342-h.htm", "application/epub+zip": "https://www.gutenberg.org/ebooks/1342.epub3.images", "text/plain; charset=utf-8": "https://www.gutenberg.org/files/1342/1342-0.txt" }, "download_count": 44739 } ] } ``` ``` -------------------------------- ### Filter books by language Source: https://context7.com/garethbjohnson/gutendex/llms.txt Return books available in specified languages using two-character ISO 639-1 codes. Multiple codes can be comma-separated. ```bash # English books only curl "http://localhost:8000/books?languages=en" ``` ```bash # French or Finnish books curl "http://localhost:8000/books?languages=fr,fi" ``` ```bash # Books in English written by 20th-century authors curl "http://localhost:8000/books?languages=en&author_year_start=1900" ``` -------------------------------- ### List Books (Paginated) Source: https://context7.com/garethbjohnson/gutendex/llms.txt Retrieves the third page of book results from the API. ```bash # Paginate to page 3 curl "http://localhost:8000/books?page=3" ``` -------------------------------- ### Filter books by topic Source: https://context7.com/garethbjohnson/gutendex/llms.txt Search for a case-insensitive phrase within books' subject headings and bookshelf names. Results include books where the phrase matches. ```bash # Children's literature (matches bookshelf "Children's Literature" and related subjects) curl "http://localhost:8000/books?topic=children" ``` ```bash # Science fiction curl "http://localhost:8000/books?topic=science%20fiction" ``` ```bash # Adventure stories curl "http://localhost:8000/books?topic=adventure" ``` -------------------------------- ### Query Books by Multiple Languages Source: https://github.com/garethbjohnson/gutendex/blob/master/readme.md Retrieve books available in any of the specified languages. Language codes should be comma-separated. ```url /books?languages=fr,fi ``` -------------------------------- ### Retrieve a Single Book Source: https://context7.com/garethbjohnson/gutendex/llms.txt Returns full details for a single book identified by its Project Gutenberg ID. Returns a `404` with an error object if the ID is not found. ```APIDOC ## GET /books/{id} ### Description Returns full details for a single book identified by its Project Gutenberg ID. Returns a `404` with an error object if the ID is not found. ### Method GET ### Endpoint /books/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The Project Gutenberg ID of the book to retrieve. ### Request Example ```bash # Retrieve Moby Dick (Project Gutenberg ID 2701) curl "http://localhost:8000/books/2701" ``` ### Response #### Success Response (200) - **id** (integer) - The Project Gutenberg ID of the book. - **title** (string) - The title of the book. - **authors** (array) - A list of author objects, each containing `name`, `birth_year`, and `death_year`. #### Response Example ```json { "id": 2701, "title": "Moby Dick; Or, The Whale", "authors": [ { "name": "Melville, Herman", "birth_year": 1819, "death_year": 1891 } ], "translators": [], "subjects": [ "Whaling -- Fiction", "Sea stories", "Whales -- Fiction", "Monsters -- Fiction", "Ahab, Captain (Fictitious character) -- Fiction" ], "bookshelves": [ "Maritime Adventure", "Sagas and Epics" ], "languages": [ "en" ], "copyright": false, "media_type": "Text", "download_count": 15000, "formats": { "application/epub+zip": "https://www.gutenberg.org/files/2701/2701-h/2701-h.htm", "application/rdf+xml": "https://www.gutenberg.org/files/2701/2701-h/2701-h.htm", "application/x-mobipocket-ebook": "https://www.gutenberg.org/files/2701/2701-h/2701-h.htm", "text/html; charset=utf-8": "https://www.gutenberg.org/files/2701/2701-h/2701-h.htm", "text/plain; charset=utf-8": "https://www.gutenberg.org/files/2701/2701-h/2701-h.htm" } } ``` #### Error Response (404) - **error** (object) - An object containing error details. #### Error Response Example ```json { "error": { "code": 404, "message": "Book with ID 99999 not found." } } ``` ``` -------------------------------- ### Control book sort order Source: https://context7.com/garethbjohnson/gutendex/llms.txt Control the ordering of the result list. Defaults to `popular` (descending download count). Other options include `ascending` and `descending`. ```bash # Most popular books first (default) curl "http://localhost:8000/books?sort=popular" ``` ```bash # Books with lowest Gutenberg ID first (oldest entries) curl "http://localhost:8000/books?sort=ascending" ``` ```bash # Books with highest Gutenberg ID first (newest entries) curl "http://localhost:8000/books?sort=descending" ``` ```bash # Combine sort with other filters curl "http://localhost:8000/books?languages=en&sort=ascending" ``` -------------------------------- ### Full-text search for books Source: https://context7.com/garethbjohnson/gutendex/llms.txt Search book titles and author names using space-separated, case-insensitive terms. All terms must match (AND logic). Up to 32 terms are supported. ```bash # Search for Dickens books with "great" in the title curl "http://localhost:8000/books?search=dickens%20great" ``` ```bash # Search for Sherlock Holmes stories curl "http://localhost:8000/books?search=sherlock%20holmes" ``` ```bash # Search by author surname only curl "http://localhost:8000/books?search=tolstoy" ``` -------------------------------- ### Format Object Structure Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html The structure of the `formats` object within a book, mapping MIME types to their corresponding download URLs. ```json { : , ... } ``` -------------------------------- ### Sort Order Source: https://context7.com/garethbjohnson/gutendex/llms.txt Controls the ordering of the result list. Defaults to `popular` (descending download count). ```APIDOC ## GET /books ### Description Controls the ordering of the result list. Defaults to `popular` (descending download count). ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **sort** (string) - Optional - The field to sort by. Options include `popular`, `ascending` (by ID, ascending), and `descending` (by ID, descending). ### Request Example ```bash # Most popular books first (default) curl "http://localhost:8000/books?sort=popular" # Books with lowest Gutenberg ID first (oldest entries) curl "http://localhost:8000/books?sort=ascending" # Books with highest Gutenberg ID first (newest entries) curl "http://localhost:8000/books?sort=descending" # Combine sort with other filters curl "http://localhost:8000/books?languages=en&sort=ascending" ``` ### Response #### Success Response (200) - **results** (array) - A list of book objects sorted according to the specified order. #### Response Example ```json { "count": 100, "next": "http://localhost:8000/books?page=2&sort=ascending", "previous": null, "results": [ { "id": 1, "title": "Oldest Book", ... }, { "id": 2, "title": "Next Oldest Book", ... } ] } ``` ``` -------------------------------- ### Filter Books by Copyright Status Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Use the `copyright` parameter to filter books by their copyright status. Accepted values are `true`, `false`, or `null`. Multiple values can be combined with commas. ```http /books?copyright=true,false ``` -------------------------------- ### List Books Source: https://github.com/garethbjohnson/gutendex/blob/master/readme.md Retrieves a list of books from the Gutendex database. Supports filtering and pagination. ```APIDOC ## GET /books ### Description Retrieves a list of books from the Gutendex database. Supports filtering and pagination. ### Endpoint /books ### Parameters #### Query Parameters - **author_year_start** (integer) - Optional - Filters books by authors alive after this year. - **author_year_end** (integer) - Optional - Filters books by authors alive before this year. - **copyright** (boolean or null) - Optional - Filters books by copyright status (`true`, `false`, or `null`). Can be comma-separated. - **ids** (integer) - Optional - Filters books by Project Gutenberg ID numbers. Must be comma-separated positive integers. - **languages** (string) - Optional - Filters books by language codes. Must be comma-separated two-character codes (e.g., `en`, `fr`). - **mime_type** (string) - Optional - Filters books by MIME type. Matches types starting with the provided value. - **search** (string) - Optional - Searches author names and book titles. Words should be space-separated and are case-insensitive. ### Response #### Success Response (200) - **count** (number) - The total number of books matching the query. - **next** (string or null) - URL to the next page of results. - **previous** (string or null) - URL to the previous page of results. - **results** (array of Books) - An array of book objects, with 0-32 items per page. ### Response Example ```json { "count": 1000, "next": "http://example.com/books?page=2", "previous": null, "results": [ { "id": 11, "title": "The Adventures of Tom Sawyer", "authors": [ { "name": "Twain, Mark", "birth_year": 1835, "death_year": 1910 } ], "translators": [], "subjects": [ "Boys -- Juvenile fiction", "Friendship -- Juvenile fiction", "School stories", "Steamboats -- Juvenile fiction", "Tombstones -- Juvenile fiction", "Runaway teenagers -- Juvenile fiction", "Mississippi River Valley -- Juvenile fiction", "Historical fiction" ], "bookshelves": [ "Children's Literature", "Adventure" ], "languages": [ "en" ], "copyright": false, "media_type": "text/html", "formats": { "application/epub+zip": "http://www.gutenberg.org/ebooks/11.epubz", "application/x-mobipocket-ebook": "http://www.gutenberg.org/ebooks/11.mobi", "application/rdf+xml": "http://www.gutenberg.org/ebooks/11.rdf", "application/zip": "http://www.gutenberg.org/ebooks/11.zip", "text/html": "http://www.gutenberg.org/ebooks/11.html", "text/plain; charset=us-ascii": "http://www.gutenberg.org/ebooks/11.txt" }, "download_count": 12345 } ] } ``` ``` -------------------------------- ### Filter Books by Author Year Range Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Use `author_year_start` and `author_year_end` to find books with authors alive within a specific year range. Values can be positive or negative integers. ```http /books?author_year_end=-499 ``` ```http /books?author_year_start=1800&author_year_end=1899 ``` -------------------------------- ### Book Object Structure Source: https://github.com/garethbjohnson/gutendex/blob/master/readme.md Represents a book object returned by the API. Includes details like ID, title, authors, subjects, and download count. ```json { "id": , "title": , "authors": , "summaries": , "editors": , "translators": , "subjects": , "bookshelves": , "languages": , "copyright": , "media_type": , "formats": , "download_count": } ``` -------------------------------- ### Sort Books Results Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Use the `sort` parameter to order book results. Options include `ascending`, `descending` (by ID), or `popular` (default). ```http /books?sort=ascending ``` -------------------------------- ### Parse Book RDF Catalog File Source: https://context7.com/garethbjohnson/gutendex/llms.txt Utility function to parse a Project Gutenberg RDF XML file into a normalized Python dictionary. Raises an exception if the file is missing or malformed. ```python from books.utils import get_book # Parse a single RDF file for book ID 1342 (Pride and Prejudice) book_data = get_book(1342, '/path/to/catalog_files/rdf/1342/pg1342.rdf') print(book_data) # { # 'id': 1342, # 'title': 'Pride and Prejudice', # 'authors': [{'name': 'Austen, Jane', 'birth': 1775, 'death': 1817}], # 'summaries': ['A novel about the Bennet sisters...'], # 'editors': [], # 'translators': [], # 'type': 'Text', # 'subjects': ['Courtship -- Fiction', 'England -- Social life...'], # 'languages': ['en'], # 'formats': { # 'text/html': 'https://www.gutenberg.org/files/1342/1342-h/1342-h.htm', # 'application/epub+zip': 'https://www.gutenberg.org/ebooks/1342.epub3.images' # }, # 'downloads': 44739, # 'bookshelves': ['Best Books Ever Listings'], # 'copyright': False # } # Raises Exception('The XML file could not be parsed.') if the file is missing or malformed ``` -------------------------------- ### List of Books API Endpoint Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html The base URL for retrieving lists of books. Results are paginated and include count, next/previous page URLs, and an array of book objects. ```http /books ``` -------------------------------- ### Query Books by Language Source: https://github.com/garethbjohnson/gutendex/blob/master/readme.md Find books available in a specific language using the two-character language code. ```url /books?languages=en ``` -------------------------------- ### Filter Books by Topic Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Use the `topic` parameter to search for books based on keywords found in their bookshelves or subjects. The search is case-insensitive. ```http /books?topic=children ``` -------------------------------- ### Individual Book API Endpoint Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Retrieve information for a specific book using its Project Gutenberg ID in the URL. ```http /books/ ``` -------------------------------- ### Grant Database Privileges Source: https://github.com/garethbjohnson/gutendex/wiki/Installation-Guide Grants all privileges on the 'gutendex' database to the 'gutendex' user. Replace 'gutendex' with your custom database and user names if applicable. ```sql GRANT ALL PRIVILEGES ON DATABASE gutendex TO gutendex; ``` -------------------------------- ### List of Books Source: https://github.com/garethbjohnson/gutendex/blob/master/gutendex/templates/home.html Retrieve lists of book information from the database. Books are ordered by popularity by default. Query parameters can be added to filter and sort results. ```APIDOC ## GET /books ### Description Retrieves a paginated list of books with options to filter, sort, and search. ### Method GET ### Endpoint /books ### Query Parameters - **author_year_start** (integer) - Optional - Filters books by authors alive after this year. - **author_year_end** (integer) - Optional - Filters books by authors alive before this year. - **copyright** (boolean or null, comma-separated) - Optional - Filters books by copyright status (`true`, `false`, `null`). - **ids** (integer, comma-separated) - Optional - Filters books by their Project Gutenberg ID numbers. - **languages** (string, comma-separated) - Optional - Filters books by two-character language codes (e.g., `en`, `fr`). - **mime_type** (string) - Optional - Filters books by MIME type. Matches types starting with the provided value. - **search** (string) - Optional - Searches author names and book titles (case-insensitive, space-separated). - **sort** (string) - Optional - Sorts results by `ascending`, `descending`, or `popular` (default). - **topic** (string) - Optional - Searches for a case-insensitive key-phrase in book subjects or bookshelves. ### Response #### Success Response (200) - **count** (number) - The total number of books matching the query. - **next** (string or null) - URL to the next page of results. - **previous** (string or null) - URL to the previous page of results. - **results** (array of Books) - An array of book objects. ### Response Example ```json { "count": 100, "next": "/books?page=2", "previous": null, "results": [ { "id": 11, "title": "The Adventures of Sherlock Holmes", "subjects": [ "Detective and mystery stories, English", "Short stories, English" ], "authors": [ { "birth_year": 1859, "death_year": 1930, "name": "Doyle, Arthur Conan" } ], "summaries": [], "translators": [], "bookshelves": [ "Mystery Fiction", "Short Stories" ], "languages": [ "en" ], "copyright": false, "media_type": "Text", "formats": { "text/plain; charset=us-ascii": "http://www.gutenberg.org/files/11/11-h/11-h.htm", "application/rdf+xml": "http://www.gutenberg.org/files/11/11-rdf/11-rdf.xml" }, "download_count": 1500 } ] } ``` ``` -------------------------------- ### List Books Source: https://github.com/garethbjohnson/gutendex/blob/master/readme.md Retrieve a list of books with options to sort and filter by topic. ```APIDOC ## GET /books ### Description Retrieves a list of books. Supports sorting by ID (ascending/descending) or popularity, and filtering by topic. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **sort** (string) - Optional - Use `ascending` for Project Gutenberg ID numbers from lowest to highest, `descending` for IDs highest to lowest, or `popular` (the default) for most popular to least popular by number of downloads. - **topic** (string) - Optional - Use this to search for a case-insensitive key-phrase in books' bookshelves or subjects. For example, `/books?topic=children` gives books on the "Children's Literature" bookshelf, with the subject "Sick children -- Fiction", and so on. ``` -------------------------------- ### Filter books by author birth/death year Source: https://context7.com/garethbjohnson/gutendex/llms.txt Filter books based on the birth and death years of their authors. Use `author_year_start` and `author_year_end` for range queries. ```bash curl "http://localhost:8000/books?author_year_start=1800&author_year_end=1899" ``` ```bash curl "http://localhost:8000/books?author_year_end=-499" ``` ```bash curl "http://localhost:8000/books?author_year_start=1900&author_year_end=1999" ``` -------------------------------- ### Filter by Topic Source: https://context7.com/garethbjohnson/gutendex/llms.txt Searches for a case-insensitive phrase within books' subject headings and bookshelf names. ```APIDOC ## GET /books ### Description Searches for a case-insensitive phrase within books' subject headings and bookshelf names. ### Method GET ### Endpoint /books ### Parameters #### Query Parameters - **topic** (string) - Optional - A phrase to search for within the `subjects` and `bookshelves` fields of the book data. ### Request Example ```bash # Children's literature (matches bookshelf "Children's Literature" and related subjects) curl "http://localhost:8000/books?topic=children" # Science fiction curl "http://localhost:8000/books?topic=science%20fiction" # Adventure stories curl "http://localhost:8000/books?topic=adventure" ``` ### Response #### Success Response (200) - **results** (array) - A list of book objects matching the topic criteria. #### Response Example ```json { "count": 50, "next": "http://localhost:8000/books?page=2&topic=children", "previous": null, "results": [ { "id": 1, "title": "Children's Story", "bookshelves": ["Children's Literature"], ... }, { "id": 2, "title": "Another Kids Book", "subjects": ["Children's stories"], ... } ] } ``` ``` -------------------------------- ### Normalize Multi-Line Titles Source: https://context7.com/garethbjohnson/gutendex/llms.txt Converts newline-delimited subtitles in raw catalog title strings to a colon/semicolon-separated single-line format. Used automatically during catalog ingestion. ```python from books.utils import fix_subtitles # Raw titles from RDF files use newlines to separate subtitle parts raw = "First Across ...\r\nThe Story of ... \r\nBeing an investigation into ..." clean = fix_subtitles(raw) print(clean) # "First Across ...: The Story of ...; Being an investigation into ..." # Single title (no subtitle) — returned unchanged print(fix_subtitles("Moby Dick")) # "Moby Dick" # Used automatically during catalog ingestion in get_book() ```