Leanpub API Documentation
The Leanpub API allows authors to programmatically preview, publish, and manage their books and courses.
Prefer a terminal to writing requests? The Leanpub CLI does all of this for you.
Note: We recently had some authentication issues with the API, but these should now be fixed. If you are still experiencing authentication problems, please email hello@leanpub.com.
Quickstart
Replace YOUR_API_KEY with an API key from your API Keys page, YOUR_BOOK_SLUG with your book's slug, and YOUR_USERNAME with your username.
This is based on an API test script written in Ruby which is shown at the bottom of this page.
# ===========================================
# PART 1: Verify API Key
# ===========================================
# Verify your API key
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/current_user.json"
# ===========================================
# PART 2: Book Lifecycle
# ===========================================
# Check if book exists (before creating)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/exists.json"
# Create a new book (Browser mode)
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{"title":"My Book","slug":"YOUR_BOOK_SLUG","sync_mode":"monaco"}' \
"https://leanpub.com/books.json"
# Check if book exists (after creating)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/exists.json"
# Get book summary
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG.json"
# Preview book
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
"https://leanpub.com/YOUR_BOOK_SLUG/preview.json"
# Check job status (poll until empty {} response)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/job_status.json"
# Register interest in the unpublished book
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{"name":"Test User","email":"test@example.com","share_email_with_author":true}' \
"https://leanpub.com/YOUR_BOOK_SLUG/interested.json"
# Get interested readers (before publish)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/interested_readers.json"
# Publish book
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
-d "publish[email_readers]=false" \
-d "publish[release_notes]=Initial publish via API" \
"https://leanpub.com/YOUR_BOOK_SLUG/publish.json"
# Check job status (poll until empty {} response)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/job_status.json"
# Unpublish book
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
"https://leanpub.com/YOUR_BOOK_SLUG/unpublish.json"
# Check book state (should be unpublished)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/exists.json"
# Re-publish book (required before retire)
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
-d "publish[email_readers]=false" \
"https://leanpub.com/YOUR_BOOK_SLUG/publish.json"
# Check job status (poll until empty {} response)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/job_status.json"
# Retire book
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
"https://leanpub.com/YOUR_BOOK_SLUG/retire.json"
# Check book state (should be retired)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/exists.json"
# Close book
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
"https://leanpub.com/YOUR_BOOK_SLUG/close.json"
# Check book state (should be closed)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/exists.json"
# ===========================================
# PART 3: Existing Book Endpoints
# ===========================================
# Get royalties (JSON)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/royalties.json"
# Get royalties (XML)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/royalties.xml"
# Get book reader emails
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/reader_emails.json"
# Get individual purchases (JSON)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/individual_purchases.json"
# Get individual purchases (XML)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/individual_purchases.xml"
# List coupons (JSON)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/coupons.json"
# List coupons (XML)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/coupons.xml"
# Create coupon
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{"coupon":{"coupon_code":"TESTCODE","package_discounts_attributes":[{"package_slug":"book","discounted_price":4.99}],"start_date":"2026-01-01","end_date":"2026-12-31","max_uses":100,"note":"Test coupon"}}' \
"https://leanpub.com/YOUR_BOOK_SLUG/coupons.json"
# Get single coupon
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/coupons/TESTCODE.json"
# Update coupon (suspend it)
curl -H "Authorization: Bearer YOUR_API_KEY" -X PUT \
-d "suspended=true" \
-d "note=Suspended via API" \
"https://leanpub.com/YOUR_BOOK_SLUG/coupons/TESTCODE.json"
API keys
Every API request needs an API key. You can have several keys, each with a name, the access it needs and an expiry date, and you can revoke one without touching the others.
Getting an API key
- API access is included with the Pro, Max and Ultra author plans, and for members of a Pro or Max publisher.
- Go to your API Keys page and click Create an API key. Give it a name that says where it will be used, choose its access and its expiry.
- Copy the key when it is shown. Leanpub shows a key only once, and stores only a fingerprint of it: if you lose it, revoke it and create a new one.
A key looks like this: lpk_ followed by 12 characters, an underscore and 49 more characters (66 in all). The lpk_ and the next 12 characters identify the key on your API Keys page and in our logs; the rest is the secret. A legacy key (one you got before named keys existed) has no lpk_ prefix.
Sending your API key
Send the key in the Authorization header of every request. Every example on this page does:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG.json"
The key can also go in the api_key query parameter or form field, for callers that can't set a header, such as a GitHub webhook:
POST https://leanpub.com/{slug}/preview.json?api_key=YOUR_API_KEY
Warning: A key in a URL ends up in server logs, in browser history and in the settings of the service that calls the URL. So a key sent this way works only if its access is Preview and publish or less (Read your account, Read books, Preview books, Publish books). Any other key is refused with
403 API_KEY_TRANSPORT_NOT_ALLOWED: send it in the header instead. A legacy key keeps working in a URL until its cutoff.
Access
Each key has the access you choose when you create it, and it can't be changed afterwards: create a new key instead. The API Keys page offers three ready-made choices and Custom:
| Access | What it includes | Use it for |
|---|---|---|
| Read only | Read your account, Read books, Read coupons, Read sales | Reports and dashboards |
| Preview and publish | Read your account, Read books, Preview books, Publish books | GitHub webhooks, CI, leanpub preview and leanpub publish |
| Full access | Everything below | The Leanpub CLI on your own computer, or replacing a legacy key |
| Custom | The ones you tick | Anything else |
The kinds of access, and what each one lets a key do:
| Access | Lets the key |
|---|---|
| Read your account | Read your name, username and email (GET /current_user.json), and look up languages and publishers |
| Read books | Read your books and courses and their job status: GET /books.json, GET /{slug}.json, GET /{slug}/exists.json, GET /{slug}/job_status.json |
| Preview books | Preview books and courses: POST /{slug}/preview.json, /preview/subset.json, /preview/single.json, POST /c/{slug}/preview.json |
| Publish books | Publish books and courses, and upload book files: POST /{slug}/publish.json, POST /{slug}/upload.json, POST /c/{slug}/publish.json |
| Create and manage books | Create books, bundles, courses and tracks (POST /books.json, /bundles.json, /courses.json, /tracks.json), and unpublish, retire or close them |
| Read coupons | List and read coupons: GET /{slug}/coupons.json, GET /{slug}/coupons/{code}.json |
| Create and edit coupons | POST /{slug}/coupons.json, PUT /{slug}/coupons/{code}.json |
| Read sales | Royalties and sales totals: GET /{slug}/royalties.json, and total_copies_sold and total_revenue in GET /{slug}.json |
| Read readers' names and email addresses | Reader emails and interested readers: GET /{slug}/reader_emails.json, GET /u/{username}/reader_emails.json, GET /{slug}/interested_readers.json, and GET /{slug}/individual_purchases.json |
| Add interested readers | POST /{slug}/interested.json |
| Full access | Every kind of access above |
A request that names a book or course also needs Read books, and unpublish, retire and close also need Read your account; GET /u/{username}/reader_emails.json needs Read your account and Read readers' names and email addresses. A request a key's access doesn't cover is refused with 403 INSUFFICIENT_SCOPE, and the message names the access it needs. GET /{slug}.json is the exception: without Read sales it answers with total_copies_sold and total_revenue set to null.
The Leanpub CLI lists the access each of its commands needs. The MCP server's tools need the access of the endpoint they call: get_book needs Read books, preview_book needs Preview books, and so on.
Expiry and revocation
A key stops working at the end of its expiry: 30 days, 90 days or 1 year after you create it, or never, as you choose (1 year unless you change it). If the key has been used, we email you 14 days before it expires. A revoked key stops working at once. Each new key also sends you an email, so you know if someone else created one.
Your API Keys page shows when each key was last used, and from which IP address.
Moving from a legacy API key
If you got your API key before named keys existed, your API Keys page shows it as Legacy, with the date it stops working. It has full access and works in a URL until then. To replace it:
- On your API Keys page, click Replace this key and create the new key. Full access matches the old key; a narrower access is safer if you know what the key is for (Preview and publish for a GitHub webhook).
- Put the new key everywhere the old one is used: GitHub webhooks (your repository's Settings, then Webhooks), the Leanpub CLI (
leanpub login), CI secrets, scripts and AI assistants connected through MCP. - When the old key's "Last used" date stops changing, revoke it.
If you don't use the API, you don't need to do anything: the legacy key just stops on its date.
Book Information
List Your Books
Returns the books you are an author of, as your author dashboard lists them (so including co-author invitations you haven't answered yet): published, unpublished, stealthed and retired. Closed and suspended books are left out.
GET https://leanpub.com/books.json
Optional query parameters:
state: one ofpublished,unpublished,stealthedorretired, to list only books in that state
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/books.json"
Response:
[
{
"slug": "YOUR_BOOK_SLUG",
"title": "Your Book Title",
"subtitle": "An Optional Subtitle",
"state": "published",
"sync_mode": "github",
"url": "https://leanpub.com/YOUR_BOOK_SLUG",
"last_published_at": "2024-01-15T19:21:50Z"
}
]
Get Book Summary
Returns detailed information about a book.
GET https://leanpub.com/{slug}.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG.json"
Response:
{
"slug": "YOUR_BOOK_SLUG",
"title": "Your Book Title",
"subtitle": "An Optional Subtitle",
"about_the_book": "Description of the book...",
"author_string": "Author Name",
"url": "https://leanpub.com/YOUR_BOOK_SLUG",
"title_page_url": "https://...",
"image": "https://...",
"minimum_paid_price": "9.99",
"suggested_price": "19.99",
"page_count": 150,
"page_count_published": 148,
"word_count": 45000,
"word_count_published": 44500,
"total_copies_sold": 1234,
"total_revenue": "15000.00",
"last_published_at": "2024-01-15T19:21:50Z",
"meta_description": "SEO description",
"possible_reader_count": 50,
"pdf_preview_url": "https://leanpub.com/s/...",
"epub_preview_url": "https://leanpub.com/s/...",
"pdf_published_url": "https://leanpub.com/s/...",
"epub_published_url": "https://leanpub.com/s/...",
"last_job_error": null
}
The pdf_preview_url, epub_preview_url, pdf_published_url, and epub_published_url fields are secret URLs for downloading your book files. Keep them private.
total_copies_sold and total_revenue need a key with Read sales access: with any other key (Preview and publish, say) they are null and the rest of the book is there.
last_job_error says why the book's most recent preview or publish failed, or is null if it didn't. A preview or publish clears it when it starts, so check it once Get Job Status shows the job has finished: a manuscript that fails to build still ends its job normally.
Create Book
Creates a new book. Supports three writing modes: Browser (monaco), GitHub, and Upload.
POST https://leanpub.com/books.json
Parameters:
title(Required) - The book titleslug(Required) - URL-friendly identifier (must be unique)sync_mode(Optional) - Writing mode:monaco(default),github, oruploadlanguage_id(Optional) - Language ID (defaults to English)publisher_id(Optional) - Publisher ID for organization publishing. Omit this for self-publishing (most authors)github_path(Required for GitHub) - GitHub repo path (e.g.,username/repo)publish_branch(Optional) - Branch for publishing (default:main)preview_branch(Optional) - Branch for previews (default:main)
Example (Browser mode):
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{
"title": "My New Book",
"slug": "my-new-book",
"sync_mode": "monaco"
}' \
https://leanpub.com/books.json
Example (GitHub mode):
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{
"title": "My GitHub Book",
"slug": "my-github-book",
"sync_mode": "github",
"github_path": "myusername/my-book-repo",
"publish_branch": "main",
"preview_branch": "main"
}' \
https://leanpub.com/books.json
Example (Upload mode):
Upload mode lets you upload pre-made PDF and/or EPUB files directly, instead of writing in the browser or syncing from a repository.
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{
"title": "My Uploaded Book",
"slug": "my-uploaded-book",
"sync_mode": "upload"
}' \
https://leanpub.com/books.json
Response (success):
{
"success": true,
"book": {
"slug": "my-new-book",
"title": "My New Book",
"state": "unpublished",
"url": "https://leanpub.com/my-new-book"
}
}
Response (error):
{
"success": false,
"errors": ["Slug has already been taken"]
}
Upload Book Files
Uploads a PDF or EPUB file to an upload-mode book. The book must have been created with sync_mode: "upload". The file is processed asynchronously (virus scan, validation, S3 upload). Use Job Status to check progress.
POST https://leanpub.com/{slug}/upload.json
Content-Type: multipart/form-data
Parameters:
file(Required) - A PDF or EPUB fileedition_type(Optional) - Which edition to upload:full(default),sample, orcommunity
Example (upload a PDF):
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
-F "file=@/path/to/book.pdf" \
-F "edition_type=full" \
"https://leanpub.com/YOUR_BOOK_SLUG/upload.json"
Example (upload an EPUB):
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
-F "file=@/path/to/book.epub" \
-F "edition_type=full" \
"https://leanpub.com/YOUR_BOOK_SLUG/upload.json"
Response (success):
{
"success": true
}
Response (error):
{
"success": false,
"errors": ["Uploads are only available for upload-mode books"]
}
Create Bundle
Creates a new bundle. Bundles are collections of books sold together at a discount.
POST https://leanpub.com/bundles.json
Parameters:
title(Required) - The bundle titleslug(Required) - URL-friendly identifier (must be unique)publisher_id(Optional) - Publisher ID for organization publishing. Omit this for self-publishing (most authors)
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{
"title": "My Bundle",
"slug": "my-bundle"
}' \
https://leanpub.com/bundles.json
Response (success):
{
"success": true,
"bundle": {
"slug": "my-bundle",
"title": "My Bundle",
"state": "unpublished",
"url": "https://leanpub.com/b/my-bundle"
}
}
Response (error):
{
"success": false,
"errors": ["Slug has already been taken"]
}
Create Course
Creates a new course. Courses are interactive learning experiences with lessons and quizzes.
POST https://leanpub.com/courses.json
Parameters:
title(Required) - The course titleslug(Required) - URL-friendly identifier (must be unique)language_id(Required) - Language ID for the coursepublisher_id(Optional) - Publisher ID for organization publishing. Omit this for self-publishing (most authors)sync_mode(Optional) - Writing mode:monaco(default) orgithubgithub_path(Required for GitHub) - GitHub repo path (e.g.,username/repo)publish_branch(Optional) - Branch for publishing (default:main)preview_branch(Optional) - Branch for previews (default:main)
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{
"title": "My Course",
"slug": "my-course",
"language_id": "1",
"sync_mode": "monaco"
}' \
https://leanpub.com/courses.json
Response (success):
{
"success": true,
"course": {
"slug": "my-course",
"title": "My Course",
"state": "unpublished",
"url": "https://leanpub.com/c/my-course"
}
}
Response (error):
{
"success": false,
"errors": ["Slug has already been taken"]
}
Create Track
Creates a new track. Tracks are curated collections of courses that guide learners through a structured learning path.
POST https://leanpub.com/tracks.json
Parameters:
title(Required) - The track titleslug(Required) - URL-friendly identifier (must be unique)publisher_id(Optional) - Publisher ID for organization publishing. Omit this for self-publishing (most authors)
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{
"title": "My Track",
"slug": "my-track"
}' \
https://leanpub.com/tracks.json
Response (success):
{
"success": true,
"track": {
"slug": "my-track",
"title": "My Track",
"state": "unpublished",
"url": "https://leanpub.com/t/my-track"
}
}
Response (error):
{
"success": false,
"errors": ["Slug has already been taken"]
}
Check Book Exists
Checks if a book exists and you are an author of it. Returns book info if you have access, or 404 if the book doesn't exist or you're not an author.
GET https://leanpub.com/{slug}/exists.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/exists.json"
Response (success - you are an author):
{
"exists": true,
"book": {
"slug": "YOUR_BOOK_SLUG",
"title": "My Book",
"state": "published"
}
}
Response (not found or not an author):
{
"exists": false,
"error": "Book not found or you are not an author of this book"
}
Preview & Publish
Preview Book
Starts a full preview generation of your book.
POST https://leanpub.com/{slug}/preview.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST "https://leanpub.com/YOUR_BOOK_SLUG/preview.json"
Response:
{
"success": true
}
If the preview can't be started, the response is a 422 whose errors say why. The same applies to every preview and publish endpoint below, for books and courses:
{
"success": false,
"errors": ["You have used all 3 of your publishes for this month. Your publish count will reset on November 01, 2026."]
}
Preview Subset
Generates a preview using only the files listed in Subset.txt. This creates only a PDF for faster iteration.
POST https://leanpub.com/{slug}/preview/subset.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST "https://leanpub.com/YOUR_BOOK_SLUG/preview/subset.json"
Response:
{
"success": true
}
Preview Single File
Generates a preview from raw Markdown content. Useful for previewing a single chapter without modifying Subset.txt. The output is saved as {slug}-single-file.pdf in your Dropbox previews folder.
POST https://leanpub.com/{slug}/preview/single.json
Content-Type: text/plain
# Chapter Title
Your markdown content here...
Example with curl:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
-H "Content-Type: text/plain" \
--data-binary "# Test Chapter
This is a test chapter for the single file preview API.
## Section 1
Some content here." \
"https://leanpub.com/YOUR_BOOK_SLUG/preview/single.json"
Ruby Script Example:
#!/usr/bin/env ruby
require "httpclient"
slug = ARGV[0]
filename = ARGV[1]
api_key = ENV["LEANPUB_API_KEY"]
content = File.read(filename)
headers = { "Content-Type" => "text/plain", "Authorization" => "Bearer #{api_key}" }
url = "https://leanpub.com/#{slug}/preview/single.json"
HTTPClient.new.post(url, :body => content, :header => headers)
Response:
{
"success": true
}
Publish Book
Publishes your book, making the latest version available to readers.
POST https://leanpub.com/{slug}/publish.json
Parameters:
publish[email_readers](boolean): Send release notification to readers (default: true, so passfalseto publish quietly)publish[release_notes](string): Release notes included in the notification email (URL-encode if needed)enableHtmlVersion(boolean): Turn the book's online (HTML) version on or off. Leave it out to keep the book's current setting
The body must be form-encoded (-d in curl), not JSON.
Examples:
Publish without notifying readers:
curl -H "Authorization: Bearer YOUR_API_KEY" \
-d "publish[email_readers]=false" \
https://leanpub.com/YOUR_BOOK_SLUG/publish.json
Publish and notify readers:
curl -H "Authorization: Bearer YOUR_API_KEY" \
-d "publish[email_readers]=true" \
-d "publish[release_notes]=Fixed typos in chapter 3" \
https://leanpub.com/YOUR_BOOK_SLUG/publish.json
Publish with multi-line release notes (URL-encoded):
curl -H "Authorization: Bearer YOUR_API_KEY" \
-d "publish[email_readers]=true" \
-d "publish[release_notes]=New+in+this+release%3A%0A%0A-+Fixed+typos%0A-+Added+chapter+4" \
https://leanpub.com/YOUR_BOOK_SLUG/publish.json
Response:
{
"success": true
}
Unpublish Book
Unpublishes a book, making it no longer available for purchase. Only the primary author can unpublish a book.
POST https://leanpub.com/{slug}/unpublish.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
https://leanpub.com/YOUR_BOOK_SLUG/unpublish.json
Response (success):
{
"success": true,
"book": {
"slug": "YOUR_BOOK_SLUG",
"state": "unpublished"
}
}
Response (not primary author):
{
"success": false,
"error": "Only the primary author can unpublish a book"
}
Retire Book
Retires a published book. Retired books are no longer available for new purchases, but existing readers retain access. Only the primary author can retire a book.
POST https://leanpub.com/{slug}/retire.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
https://leanpub.com/YOUR_BOOK_SLUG/retire.json
Response (success):
{
"success": true,
"book": {
"slug": "YOUR_BOOK_SLUG",
"state": "retired"
}
}
Response (not primary author):
{
"success": false,
"error": "Only the primary author can retire a book"
}
Close Book
Closes a book completely. Closed books are hidden from the store and cannot be purchased. Only the primary author can close a book.
POST https://leanpub.com/{slug}/close.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST \
https://leanpub.com/YOUR_BOOK_SLUG/close.json
Response (success):
{
"success": true,
"book": {
"slug": "YOUR_BOOK_SLUG",
"state": "closed"
}
}
Response (not primary author):
{
"success": false,
"error": "Only the primary author can close a book"
}
Get Job Status
Check the status of a running preview or publish job.
GET https://leanpub.com/{slug}/job_status.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/job_status.json"
Response (job in progress):
{
"num": 8,
"total": 28,
"job_type": "GenerateBookJob#preview",
"message": "Generating PDF...",
"status": "working",
"name": "Preview YOUR_BOOK_SLUG",
"time": 1376073552,
"options": {
"requested_by": "you@example.com",
"slug": "YOUR_BOOK_SLUG",
"action": "preview"
}
}
Response fields:
num: Current step numbertotal: Total number of stepsjob_type: The type of job running (e.g.,GenerateBookJob#preview,GenerateBookJob#publish)message: Human-readable status messagestatus: Job status (working, etc.)time: Unix timestamp when the job started
The num and total fields can be used to display progress like "Step 8 of 28".
Response (job complete):
Returns an empty object {} when no job is running.
Poll this endpoint to track progress, but limit requests to once every 5 seconds.
Utility Script: Poll Until Complete
while true; do
status=$(curl -s -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/job_status.json")
echo "$status" | jq .
if [ "$status" = "{}" ]; then
echo "Job complete!"
break
fi
sleep 5
done
Sales & Royalties
Get Royalties Summary
Returns a summary of your book's sales and royalties. Available in both JSON and XML formats.
JSON:
GET https://leanpub.com/{slug}/royalties.json
XML:
GET https://leanpub.com/{slug}/royalties.xml
Here's an example with curl:
# JSON
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/royalties.json"
# XML
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/royalties.xml"
Response (JSON):
{
"total_royalties": 12500.0,
"royalties_bundled": 500.0,
"royalties_unbundled": 12000.0,
"last_week_royalties": 250.0,
"royalties_to_revenue_ratio": 0.8,
"total_revenue": 15625.0,
"revenue_bundled": 625.0,
"revenue_unbundled": 15000.0,
"total_copies_sold": 1234,
"num_copies_sold_bundled": 50,
"num_copies_sold_unbundled": 1184
}
Get Individual Purchases
Returns a paginated list of individual purchases for your book. Available in both JSON and XML formats.
JSON:
GET https://leanpub.com/{slug}/individual_purchases.json
XML:
GET https://leanpub.com/{slug}/individual_purchases.xml
Parameters:
-
page(integer): Page number (default: 1, 50 items per page) -
email(string, optional): Filter purchases by reader email address. Only returns results when the reader opted to share their email with the author at purchase time. The match is case-insensitive. The filter returns an empty list when:- No reader with that email has purchased the book
- The reader purchased the book but did not opt to share their email with the author
This means the
emailfilter cannot be used to determine whether someone purchased your book — it only finds purchases where the reader chose to share their contact information with you.
Examples:
# JSON
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/individual_purchases.json"
# XML
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/individual_purchases.xml"
# JSON with pagination
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/individual_purchases.json?page=2"
# XML with pagination
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/individual_purchases.xml?page=2"
# Filter by reader email (only returns results if the reader shared their email)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/individual_purchases.json?email=reader@example.com"
Response (JSON):
[
{
"id": "123",
"author_royalties": 8.0,
"state": "paid",
"payable_at": "2024-02-01T00:00:00Z",
"purchased_package_id": "456",
"free": false,
"user_email": "reader@example.com"
}
]
Coupons
List Coupons
Returns all coupons for a book. Available in both JSON and XML formats.
JSON:
GET https://leanpub.com/{slug}/coupons.json
XML:
GET https://leanpub.com/{slug}/coupons.xml
Examples:
# JSON
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/coupons.json"
# XML
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/coupons.xml"
Response (JSON):
[
{
"coupon_code": "LAUNCH50",
"created_at": "2024-01-01T00:00:00Z",
"package_discounts": [
{
"package_slug": "book",
"discounted_price": 4.99
}
],
"start_date": "2024-01-01",
"end_date": "2024-12-31",
"max_uses": 100,
"num_uses": 25,
"note": "Launch promotion",
"suspended": false,
"book_slug": "YOUR_BOOK_SLUG"
}
]
Get Single Coupon
Returns details for a specific coupon.
GET https://leanpub.com/{slug}/coupons/{coupon_code}.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/coupons/LAUNCH50.json"
Response:
{
"coupon_code": "LAUNCH50",
"created_at": "2024-01-01T00:00:00Z",
"package_discounts": [
{
"package_slug": "book",
"discounted_price": 4.99
}
],
"start_date": "2024-01-01",
"end_date": "2024-12-31",
"max_uses": 100,
"num_uses": 25,
"note": "Launch promotion",
"suspended": false,
"book_slug": "YOUR_BOOK_SLUG"
}
Create Coupon
Creates a new coupon for your book.
POST https://leanpub.com/{slug}/coupons.json
Parameters:
coupon_code(required): Unique code for this couponpackage_discounts_attributes(required): Array of package discountsstart_date(required): Start date (YYYY-MM-DD)end_date(optional): End date (YYYY-MM-DD)max_uses(optional): Maximum number of uses (null = unlimited)note(optional): Internal note about this couponsuspended(optional): Whether the coupon is suspended (default: false)
Example (JSON):
curl -H "Authorization: Bearer YOUR_API_KEY" -H "Content-Type: application/json" \
-d '{
"coupon": {
"coupon_code": "SAVE50",
"package_discounts_attributes": [
{"package_slug": "book", "discounted_price": 4.99}
],
"start_date": "2024-01-01",
"end_date": "2024-12-31",
"max_uses": 100,
"note": "Half price promotion"
}
}' \
https://leanpub.com/YOUR_BOOK_SLUG/coupons.json
Example (form data):
curl -H "Authorization: Bearer YOUR_API_KEY" \
-d "coupon[coupon_code]=SAVE50" \
-d "coupon[package_discounts_attributes][][package_slug]=book" \
-d "coupon[package_discounts_attributes][][discounted_price]=4.99" \
-d "coupon[start_date]=2024-01-01" \
-d "coupon[end_date]=2024-12-31" \
https://leanpub.com/YOUR_BOOK_SLUG/coupons.json
Response: Returns the created coupon (see Get Single Coupon).
Update Coupon
Updates an existing coupon. Only include fields you want to change.
PUT https://leanpub.com/{slug}/coupons/{coupon_code}.json
Example (JSON):
curl -H "Authorization: Bearer YOUR_API_KEY" -X PUT \
-H "Content-Type: application/json" \
-d '{"suspended": true, "note": "Updated via API"}' \
https://leanpub.com/YOUR_BOOK_SLUG/coupons/SAVE50.json
Example (form data):
curl -H "Authorization: Bearer YOUR_API_KEY" -X PUT \
-d "suspended=false" \
-d "max_uses=200" \
https://leanpub.com/YOUR_BOOK_SLUG/coupons/SAVE50.json
Response: Returns the updated coupon (see Get Single Coupon).
Account
Verify API Key
Validates your API key and returns information about the authenticated user. Useful for testing your integration.
GET https://leanpub.com/current_user.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/current_user.json"
Response:
{
"username": "YOUR_USERNAME",
"email": "you@example.com"
}
Get Reader Emails
Returns email addresses of readers who have opted to share their email with you.
GET https://leanpub.com/u/{username}/reader_emails.json
Parameters:
type(string): Filter by purchase type:all,book, orcourse(default:all)purchase_type(string): Alias fortype(for backwards compatibility)
Examples:
# All readers
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/u/YOUR_USERNAME/reader_emails.json"
# Books only (new parameter)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/u/YOUR_USERNAME/reader_emails.json?type=book"
# Courses only (new parameter)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/u/YOUR_USERNAME/reader_emails.json?type=course"
# Books only (legacy parameter - still works)
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/u/YOUR_USERNAME/reader_emails.json?purchase_type=book"
Response:
["reader1@example.com", "reader2@example.com"]
Get Book Reader Emails
Returns email addresses of readers who have purchased a specific book and opted to share their email with you.
GET https://leanpub.com/{slug}/reader_emails.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/reader_emails.json"
Response:
["reader1@example.com", "reader2@example.com"]
Register Interest
Registers an email address to be notified when a book is published. This is useful for unpublished books where readers want to know when it becomes available.
POST https://leanpub.com/{slug}/interested.json
Parameters:
name(required): The name of the interested readeremail(required): Email address to notifyshare_email_with_author(boolean): Whether to share the email with the author (default: false)
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" -X POST -H "Content-Type: application/json" \
-d '{
"name": "Test Reader",
"email": "reader@example.com",
"share_email_with_author": true
}' \
https://leanpub.com/YOUR_BOOK_SLUG/interested.json
Response (success):
{
"success": true,
"message": "You will be notified when this book is published"
}
Response (error):
{
"success": false,
"errors": ["Email has already registered interest"]
}
Get Interested Readers
Returns a list of people who registered interest in a book and opted to share their email with the author.
GET https://leanpub.com/{slug}/interested_readers.json
Example:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/interested_readers.json"
Response:
[
{
"name": "Test Reader",
"email": "reader@example.com"
}
]
Only readers who set share_email_with_author: true when registering interest will appear in this list.
Downloading Book Files
The book summary endpoint returns secret URLs for downloading your book files:
pdf_preview_url/epub_preview_url- Latest previewpdf_published_url/epub_published_url- Latest published version
Get the download URLs first:
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG.json" | \
jq '{pdf_preview_url, epub_preview_url, pdf_published_url, epub_published_url}'
Download using the secret URLs:
These URLs redirect to S3. Use the -L flag with curl to follow redirects:
# Download using the secret URLs (use actual URLs from above)
curl -L "https://leanpub.com/s/YOUR-SECRET-ID.pdf" > book.pdf
curl -L "https://leanpub.com/s/YOUR-SECRET-ID.epub" > book.epub
Error Handling
HTTP Status Codes:
- 200: Success
- 201: Created (for POST requests)
- 401: Unauthorized - Missing, unknown, expired or revoked API key
- 403: Forbidden - Your API key works but is not permitted: its access doesn't cover the request, your membership does not include API access, or you may not act on this resource (e.g., not the primary author)
- 404: Not found - Book or resource doesn't exist, or you're not an author
- 405: Method not allowed
- 422: Validation error - Check the error response for details
- 429: Too many requests - See Rate Limits
- 500: Internal server error
- 503: API keys are turned off for now - Your key is not at fault; try again later
Error codes:
A refused key or request also carries a code that says why, in the X-Leanpub-Error-Code response header (on every method) and in the code field of a POST/PUT error body:
| HTTP | Code | Meaning |
|---|---|---|
| 401 | INVALID_API_KEY | The key is unknown, or mistyped |
| 401 | API_KEY_EXPIRED | The key passed its expiry date. Create a new one |
| 401 | API_KEY_REVOKED | The key was revoked. Create a new one |
| 401 | LEGACY_API_KEY_RETIRED | A legacy key after its cutoff. Create a new one on your API Keys page |
| 403 | INSUFFICIENT_SCOPE | The key's access doesn't cover this request. The message names the access it needs |
| 403 | API_KEY_TRANSPORT_NOT_ALLOWED | The key came in a URL or a request body, and its access is wider than Preview and publish. Send it in the Authorization header |
| 403 | API_ACCESS_NOT_INCLUDED | Your membership does not include API access |
| 403 | ACCOUNT_NOT_ACTIVE | The account is suspended or closed |
| 503 | API_KEYS_UNAVAILABLE | API keys are turned off for now. Try again later |
Error Response Formats:
GET requests return null with the appropriate status code for backwards compatibility:
null
POST/PUT requests return a structured error response whose error says why - for example an unknown key:
{
"success": false,
"error": "Invalid API key.",
"code": "INVALID_API_KEY"
}
or a membership that does not include API access:
{
"success": false,
"error": "API access requires a Pro Author membership or above.",
"code": "API_ACCESS_NOT_INCLUDED"
}
For a refused key or a book that cannot be found, the .xml endpoints answer with the same status codes and an XML body under the endpoint's own root (<royalties nil="true"/> on a GET).
For validation errors with multiple messages:
{
"success": false,
"errors": ["Title is required", "Slug is required"]
}
Rate Limits
The API enforces per-key rate limits to ensure fair usage: each API key has its own limits, so two keys on one account don't share them. Both REST and MCP endpoints share the same rate limit pool.
| Tier | Limit | Endpoints | |------|-------|-----------| | READ | 30/min | Book summary, check exists, job status, royalties, get coupon | | LIST | 15/min | Coupons list, purchases, reader emails, interested readers | | WRITE | 15/min | Create/update coupon, register interest | | HEAVY | 3/min | Preview, publish (books & courses) | | STATE_CHANGE | 5/min | Unpublish, retire, close | | CREATE | 2/min | Create book, bundle, course, track |
These limits are designed so authors never hit them during regular use. If you exceed a limit, you'll receive a 429 Too Many Requests response with a Retry-After header indicating how many seconds to wait.
Example 429 response:
{
"error": "Rate limit exceeded for preview/publish operations. Limit: 3 requests per 1 minutes. Try again in 45 seconds."
}
Tips:
- Poll
job_statusno more than once every 5 seconds - Add small delays between calls if making many requests
- The
Retry-Afterheader tells you exactly how long to wait
MCP Server (AI Assistant Integration)
⚠️ Early Beta Warning: The Leanpub MCP Server is in very early beta. Expect things to not work. We are actively developing this feature and it may be unstable, have missing functionality, or behave unexpectedly. If you run into issues, please email hello@leanpub.com.
The Leanpub MCP Server lets AI assistants like Claude interact with your Leanpub account through the Model Context Protocol. This enables AI-powered book management, publishing automation, and more.
Endpoint
The MCP server is hosted at:
https://leanpub.com/api/mcp
No installation required—just configure your AI client to connect to this URL with your API key.
Claude Desktop Configuration
Add to your Claude Desktop config file:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
Windows:
%APPDATA%\Claude\claude_desktop_config.json
Linux:
~/.config/Claude/claude_desktop_config.json
{
"mcpServers": {
"leanpub": {
"url": "https://leanpub.com/api/mcp",
"headers": {
"Authorization": "Bearer YOUR_API_KEY"
}
}
}
}
Replace YOUR_API_KEY with a key from your API Keys page. The assistant can do only what the key's access allows: Read only for questions about your books and sales, Preview and publish to preview and publish as well, Full access for every tool. verify_api_key checks that the key works.
Available Tools
The MCP server provides 29 tools organized by function:
- Authentication:
verify_api_key - Book Information:
get_book,check_book_exists - Product Creation:
create_book,create_bundle,create_course,create_track(all work for regular self-publishing authors—no publisher ID needed) - Preview & Publish:
preview_book,preview_subset,preview_single,publish_book - Book State:
unpublish_book,retire_book,close_book - Job Status:
get_job_status - Interested Readers:
register_interest,get_interested_readers - Reader Emails:
get_user_reader_emails,get_book_reader_emails - Royalties:
get_royalties - Purchases:
get_individual_purchases - Coupons:
list_coupons,get_coupon,create_coupon,update_coupon - Courses:
preview_course,publish_course,preview_org_course,publish_org_course
Rate Limits
The MCP server enforces rate limits to ensure fair usage:
- READ (30/min): Book info, royalties, job status
- LIST (15/min): Coupons, purchases, reader emails
- WRITE (15/min): Create/update coupons, register interest
- HEAVY (3/min): Preview, publish (books & courses)
- STATE_CHANGE (5/min): Unpublish, retire, close
- CREATE (2/min): Create book, bundle, course, track
These limits are designed so authors never hit limits during regular use.
Example Conversation
Once configured, you can ask Claude to help with your Leanpub books:
You: Check the status of my book "lean-publishing"
Claude: uses get_book tool
Your book "Lean Publishing" has:
- 45,000 words across 150 pages
- 500 copies sold with $5,000 total revenue
- Last published on January 15, 2024
You: Create a 50% off coupon for the holidays
Claude: uses create_coupon tool
Done! I created coupon "HOLIDAY50" that gives 50% off ($9.99 instead of $19.99). It's valid through December 31st.
You: Create a new bundle called "The Complete Web Dev Collection" with slug "web-dev-collection"
Claude: uses create_bundle tool
Done! I created your bundle "The Complete Web Dev Collection" at https://leanpub.com/b/web-dev-collection. It's currently unpublished — you can add books to it and publish when ready.
You: Preview my latest changes and let me know when it's done
Claude: uses preview_book and get_job_status tools
Preview generation started. I'll check on the progress... The preview is complete! You can find the PDF in your Dropbox previews folder.
GraphQL
The REST endpoints above are the documented, supported API. The GraphQL API they are built on also accepts your API key directly, if you would rather write your own queries:
curl -H "Authorization: Bearer YOUR_API_KEY" https://leanpub.com/api/graphql \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"query":"{ identity { currentUser { username name } } }"}'
Only the public part of the schema is available to an API key: the fields and operations the REST endpoints use. Anything else answers that the field doesn't exist. The public schema is published at /help/api/schema.graphql, and it can change as we add to it. Each GraphQL request counts against a limit of 300 requests per minute per API key, and previews, publishes and uploads against a limit of 3 per minute, as they do through the REST endpoints. Over a limit, the response is a 429 with a Retry-After header giving the seconds to wait.
Your Book's Slug
Your book's slug is the URL-friendly identifier in your book's URL:
https://leanpub.com/YOUR_BOOK_SLUG
^^^^^^^^^^^^^^ this is the slug
Course API
Leanpub courses can be previewed and published via the API, similar to books.
Your Course's Slug
Courses have different URL patterns depending on how they're published:
- Self-published:
https://leanpub.com/c/YOUR_COURSE_SLUG— needsYOUR_COURSE_SLUGslug - Organization:
https://leanpub.com/courses/YOUR_ORG_SLUG/YOUR_COURSE_SLUG— needs bothYOUR_ORG_SLUGandYOUR_COURSE_SLUG - University:
https://leanpub.com/universities/courses/YOUR_UNIVERSITY_SLUG/YOUR_COURSE_SLUG— needs bothYOUR_UNIVERSITY_SLUGandYOUR_COURSE_SLUG
Preview Course
Starts a preview generation of your course.
Self-published course:
POST https://leanpub.com/c/{slug}/preview.json
Organization course:
POST https://leanpub.com/c/{organization_slug}/{slug}/preview.json
University course:
POST https://leanpub.com/c/{university_slug}/{slug}/preview.json
Examples:
# Self-published course
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" https://leanpub.com/c/YOUR_COURSE_SLUG/preview.json
# Organization course
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" https://leanpub.com/c/YOUR_ORG_SLUG/YOUR_COURSE_SLUG/preview.json
# University course
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" https://leanpub.com/c/YOUR_UNIVERSITY_SLUG/YOUR_COURSE_SLUG/preview.json
Response (success):
{
"success": true
}
Response (course not found):
{
"success": false
}
Publish Course
Publishes your course, making the latest version available to learners.
Self-published course:
POST https://leanpub.com/c/{slug}/publish.json
Organization course:
POST https://leanpub.com/c/{organization_slug}/{slug}/publish.json
University course:
POST https://leanpub.com/c/{university_slug}/{slug}/publish.json
Parameters:
publish[email_readers](Optional) - Whether to notify learners (default: true)publish[release_notes](Optional) - Release notes to include in notificationpublish[percent_complete](Optional) - Set course percent complete (integer)
Examples:
# Self-published course - publish without notifying learners
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" https://leanpub.com/c/YOUR_COURSE_SLUG/publish.json
# Self-published course - publish with release notes and notification
curl -H "Authorization: Bearer YOUR_API_KEY" \
-d "publish[email_readers]=true" \
-d "publish[release_notes]=Updated lesson content" \
https://leanpub.com/c/YOUR_COURSE_SLUG/publish.json
# Organization course
curl -H "Authorization: Bearer YOUR_API_KEY" \
-d "publish[email_readers]=true" \
-d "publish[release_notes]=New lessons added" \
https://leanpub.com/c/YOUR_ORG_SLUG/YOUR_COURSE_SLUG/publish.json
# University course
curl -X POST -H "Authorization: Bearer YOUR_API_KEY" https://leanpub.com/c/YOUR_UNIVERSITY_SLUG/YOUR_COURSE_SLUG/publish.json
Response (success):
{
"success": true
}
Response (course not found):
{
"success": false
}
XML Endpoints
XML endpoints are supported for backwards compatibility with the legacy API. The following endpoints support both JSON and XML formats:
/{slug}/royalties.xml- Royalties summary/{slug}/individual_purchases.xml- Individual purchases (supports pagination)/{slug}/coupons.xml- List coupons
Simply use the .xml extension instead of .json to get XML responses:
# JSON
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/royalties.json"
# XML
curl -H "Authorization: Bearer YOUR_API_KEY" "https://leanpub.com/YOUR_BOOK_SLUG/royalties.xml"
Migration Notes from Legacy API
If you have an existing integration with the Leanpub API, here's what you need to know:
What's the Same
- All JSON endpoints work identically
- All XML endpoints work identically (royalties, individual_purchases, coupons)
- Authentication via
api_keyquery param or POST body (a new key only with Preview and publish access or less; see API keys) - Request/response formats are compatible
- Both
typeandpurchase_typework for reader_emails - Course API (
/c/...) endpoints work identically
What's Different
Full compatibility has been achieved with the legacy API, but legacy API keys stop on a date shown on your API Keys page: see Moving from a legacy API key.
New endpoints added:
GET /books.json- List your booksPOST /books.json- Create a new book (Browser or GitHub mode)POST /bundles.json- Create a new bundlePOST /courses.json- Create a new coursePOST /tracks.json- Create a new trackPOST /{slug}/interested.json- Register interest in an unpublished bookGET /{slug}/interested_readers.json- Get list of interested readers (for authors)POST /api/mcp- MCP server endpoint for AI assistant integration
API Test Script
The following Ruby script demonstrates the complete API workflow, including creating a book, previewing, publishing, managing lifecycle states, and testing various endpoints. You can use this as a reference for your own integrations.
Usage:
./test_api.rb --api-key YOUR_API_KEY --user YOUR_USERNAME
# With existing book tests
./test_api.rb --api-key YOUR_API_KEY --user YOUR_USERNAME --existing-book YOUR_BOOK_SLUG
Script:
#!/usr/bin/env ruby
require "net/http"
require "uri"
require "json"
require "optparse"
require "securerandom"
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: #{$0} [options]"
opts.on("--api-key KEY", "Your Leanpub API key (required)") do |v|
options[:api_key] = v
end
opts.on("--user USERNAME", "Username for existing book tests (required)") do |v|
options[:user] = v
end
opts.on("--existing-book SLUG", "Test existing book endpoints with this slug (optional)") do |v|
options[:existing_book] = v
end
opts.on("-h", "--help", "Show this help") do
puts opts
puts
puts "Examples:"
puts " #{$0} --api-key YOUR_API_KEY --user YOUR_USERNAME"
puts " #{$0} --api-key YOUR_API_KEY --user YOUR_USERNAME --existing-book YOUR_BOOK_SLUG"
exit
end
end.parse!
if options[:api_key].nil? || options[:user].nil?
puts "Error: --api-key and --user are required."
puts
puts "Usage: #{$0} --api-key KEY --user USERNAME"
puts
puts "Examples:"
puts " #{$0} --api-key YOUR_API_KEY --user YOUR_USERNAME"
puts " #{$0} --api-key YOUR_API_KEY --user YOUR_USERNAME --existing-book YOUR_BOOK_SLUG"
exit 1
end
API_KEY = options[:api_key]
BASE_URL = "https://leanpub.com"
TEST_USER = options[:user]
EXISTING_BOOK = options[:existing_book]
# Generate a unique test book slug
TEST_BOOK_SLUG = "api-test-#{SecureRandom.uuid}"
TEST_BOOK_TITLE = "API Test Book #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}"
TEST_INTERESTED_EMAIL = "#{SecureRandom.uuid}@test.com"
def create_http(uri)
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"
http.use_ssl = true
end
http
end
def prompt_continue(step_name)
print "\n\033[33mPress Enter to continue to: #{step_name} (or 'q' to quit)\033[0m "
input = gets.chomp
exit(0) if input.downcase == "q"
end
def build_curl_command(method, path, body: nil, content_type: nil)
uri = URI("#{BASE_URL}#{path}")
auth = "-H \"Authorization: Bearer $LEANPUB_API_KEY\""
case method
when :get
"curl -s #{auth} \"#{uri}\""
when :post
if content_type == "application/json"
json_body = body.to_json
"curl -s -X POST #{auth} -H \"Content-Type: application/json\" \\\n -d '#{json_body}' \\\n \"#{uri}\""
else
data_args = (body || {}).map { |k, v| "-d \"#{k}=#{v}\"" }
["curl -s -X POST #{auth}", *data_args, "\"#{uri}\""].join(" \\\n ")
end
when :put
data_args = (body || {}).map { |k, v| "-d \"#{k}=#{v}\"" }
["curl -s -X PUT #{auth}", *data_args, "\"#{uri}\""].join(" \\\n ")
end
end
def run_request(method, path, body: nil, content_type: nil, format: :json)
# Show curl command
curl_cmd = build_curl_command(method, path, body: body, content_type: content_type)
puts "\033[90m$ #{curl_cmd}\033[0m"
puts
uri = URI("#{BASE_URL}#{path}")
http = create_http(uri)
case method
when :get
request = Net::HTTP::Get.new(uri)
when :post
request = Net::HTTP::Post.new(uri)
if content_type == "application/json"
request["Content-Type"] = "application/json"
request.body = body.to_json
else
request.set_form_data(body || {})
end
when :put
request = Net::HTTP::Put.new(uri)
request.set_form_data(body || {})
end
request["Authorization"] = "Bearer #{API_KEY}"
response = http.request(request)
puts "\033[36mStatus: #{response.code}\033[0m"
if format == :json && response.body && !response.body.empty?
begin
parsed = JSON.parse(response.body)
puts JSON.pretty_generate(parsed)
rescue JSON::ParserError
puts response.body
end
else
puts response.body
end
response
end
def test_step(number, name, &block)
puts "\n" + "=" * 60
puts "\033[32m#{number}. #{name}\033[0m"
puts "=" * 60
block.call
end
def wait_for_job(slug, max_wait: 120)
puts "\033[90mWaiting for job to complete (max #{max_wait}s)...\033[0m"
start_time = Time.now
loop do
uri = URI("#{BASE_URL}/#{slug}/job_status.json")
http = create_http(uri)
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer #{API_KEY}"
response = http.request(request)
if response.body == "{}" || response.body.nil? || response.body.empty?
puts "\033[32mJob complete!\033[0m"
return true
end
begin
status = JSON.parse(response.body)
if status["message"]
print "\r\033[90m #{status['message']} (#{status['num']}/#{status['total']})\033[0m"
print " " * 20 # Clear any remaining characters
end
rescue JSON::ParserError
# Ignore parse errors
end
if Time.now - start_time > max_wait
puts "\n\033[31mTimeout waiting for job!\033[0m"
return false
end
sleep 3
end
end
def fetch_book_info(slug)
uri = URI("#{BASE_URL}/#{slug}.json")
http = create_http(uri)
request = Net::HTTP::Get.new(uri)
request["Authorization"] = "Bearer #{API_KEY}"
response = http.request(request)
return nil unless response.code == "200"
JSON.parse(response.body)
rescue JSON::ParserError
nil
end
def prompt_open_url(url, description)
return unless url && !url.empty?
puts "\n\033[36m#{description}:\033[0m #{url}"
print "\033[33mPress Enter to open in browser (or 's' to skip)\033[0m "
input = gets.chomp
return if input.downcase == "s"
# Open URL in default browser (macOS)
system("open", url)
end
# Start testing
puts "\033[1m\033[35m"
puts "=" * 60
puts " LEANPUB API TEST SCRIPT"
puts "=" * 60
puts "\033[0m"
puts
puts "\033[1m\033[41m\033[37m WARNING \033[0m\033[1m\033[31m Job completion detection is not working correctly!\033[0m"
puts "\033[31m Please manually verify that preview/publish jobs complete before proceeding.\033[0m"
puts
puts "Base URL: #{BASE_URL}"
puts "API Key: #{API_KEY[0..10]}..."
puts "Test User: #{TEST_USER}"
puts
puts "\033[1mBook Lifecycle Test:\033[0m"
puts " Slug: #{TEST_BOOK_SLUG}"
puts " Title: #{TEST_BOOK_TITLE}"
puts " Interested Email: #{TEST_INTERESTED_EMAIL}"
step = 0
# ============================================================
# PART 1: Verify API Key
# ============================================================
prompt_continue("Verify API Key")
test_step(step += 1, "Verify API Key") do
run_request(:get, "/current_user.json")
end
# ============================================================
# PART 2: Book Lifecycle (Create -> Preview -> Publish -> Unpublish -> Retire -> Close)
# ============================================================
prompt_continue("Check if test book exists (should return exists: false)")
test_step(step += 1, "Check Book Exists (expect exists: false)") do
run_request(:get, "/#{TEST_BOOK_SLUG}/exists.json")
end
prompt_continue("Create Book (Browser mode)")
test_step(step += 1, "Create Book") do
response = run_request(:post, "/books.json",
body: {
title: TEST_BOOK_TITLE,
slug: TEST_BOOK_SLUG,
sync_mode: "monaco"
},
content_type: "application/json"
)
if response.code == "200" || response.code == "201"
prompt_open_url("#{BASE_URL}/#{TEST_BOOK_SLUG}", "Book Landing Page")
end
end
prompt_continue("Verify book now exists")
test_step(step += 1, "Check Book Exists (expect 200)") do
run_request(:get, "/#{TEST_BOOK_SLUG}/exists.json")
end
prompt_continue("Get Book Summary")
test_step(step += 1, "Get Book Summary") do
run_request(:get, "/#{TEST_BOOK_SLUG}.json")
end
prompt_continue("Preview Book")
test_step(step += 1, "Preview Book") do
response = run_request(:post, "/#{TEST_BOOK_SLUG}/preview.json")
if response.code == "200"
puts
if wait_for_job(TEST_BOOK_SLUG)
book_info = fetch_book_info(TEST_BOOK_SLUG)
if book_info
prompt_open_url(book_info["pdf_preview_url"], "PDF Preview")
prompt_open_url(book_info["epub_preview_url"], "EPUB Preview")
end
end
end
end
prompt_continue("Register interest in the unpublished book")
test_step(step += 1, "Register Interest (#{TEST_INTERESTED_EMAIL})") do
puts "\033[90mThis email will be notified when the book is published:\033[0m"
puts " #{TEST_INTERESTED_EMAIL}"
puts
run_request(:post, "/#{TEST_BOOK_SLUG}/interested.json",
body: {
name: "API Test User",
email: TEST_INTERESTED_EMAIL,
share_email_with_author: true
},
content_type: "application/json"
)
end
prompt_continue("Get Interested Readers (before publish)")
test_step(step += 1, "Get Interested Readers") do
puts "\033[90mChecking if #{TEST_INTERESTED_EMAIL} appears (they opted to share email):\033[0m"
puts
run_request(:get, "/#{TEST_BOOK_SLUG}/interested_readers.json")
end
prompt_continue("Publish Book")
test_step(step += 1, "Publish Book") do
response = run_request(:post, "/#{TEST_BOOK_SLUG}/publish.json",
body: {
"publish[email_readers]" => false,
"publish[release_notes]" => "Initial publish via API test"
}
)
if response.code == "200"
puts
if wait_for_job(TEST_BOOK_SLUG)
book_info = fetch_book_info(TEST_BOOK_SLUG)
if book_info
prompt_open_url(book_info["pdf_published_url"], "PDF Published")
prompt_open_url(book_info["epub_published_url"], "EPUB Published")
end
prompt_open_url("#{BASE_URL}/#{TEST_BOOK_SLUG}", "Book Landing Page (Published)")
end
end
end
prompt_continue("Unpublish Book")
test_step(step += 1, "Unpublish Book") do
response = run_request(:post, "/#{TEST_BOOK_SLUG}/unpublish.json")
if response.code == "200"
prompt_open_url("#{BASE_URL}/#{TEST_BOOK_SLUG}", "Book Landing Page (Unpublished)")
end
end
prompt_continue("Check book state after unpublish")
test_step(step += 1, "Check Book State (should be unpublished)") do
run_request(:get, "/#{TEST_BOOK_SLUG}/exists.json")
end
# Note: To retire, book must be published first. Let's re-publish then retire.
prompt_continue("Re-publish Book (required before retire)")
test_step(step += 1, "Re-publish Book") do
response = run_request(:post, "/#{TEST_BOOK_SLUG}/publish.json",
body: {
"publish[email_readers]" => false
}
)
if response.code == "200"
puts
if wait_for_job(TEST_BOOK_SLUG)
book_info = fetch_book_info(TEST_BOOK_SLUG)
if book_info
prompt_open_url(book_info["pdf_published_url"], "PDF Published")
end
prompt_open_url("#{BASE_URL}/#{TEST_BOOK_SLUG}", "Book Landing Page (Re-published)")
end
end
end
prompt_continue("Retire Book")
test_step(step += 1, "Retire Book") do
response = run_request(:post, "/#{TEST_BOOK_SLUG}/retire.json")
if response.code == "200"
prompt_open_url("#{BASE_URL}/#{TEST_BOOK_SLUG}", "Book Landing Page (Retired)")
end
end
prompt_continue("Check book state after retire")
test_step(step += 1, "Check Book State (should be retired)") do
run_request(:get, "/#{TEST_BOOK_SLUG}/exists.json")
end
prompt_continue("Close Book")
test_step(step += 1, "Close Book") do
response = run_request(:post, "/#{TEST_BOOK_SLUG}/close.json")
if response.code == "200"
prompt_open_url("#{BASE_URL}/#{TEST_BOOK_SLUG}", "Book Landing Page (Closed)")
end
end
prompt_continue("Check book state after close")
test_step(step += 1, "Check Book State (should be closed)") do
run_request(:get, "/#{TEST_BOOK_SLUG}/exists.json")
end
# ============================================================
# PART 3: Existing Book Tests (if --existing-book provided)
# ============================================================
if EXISTING_BOOK
puts "\n" + "=" * 60
puts "\033[1m\033[35m EXISTING BOOK TESTS (#{EXISTING_BOOK})\033[0m"
puts "=" * 60
prompt_continue("Royalties (JSON)")
test_step(step += 1, "Royalties (JSON)") do
run_request(:get, "/#{EXISTING_BOOK}/royalties.json")
end
prompt_continue("Royalties (XML)")
test_step(step += 1, "Royalties (XML)") do
run_request(:get, "/#{EXISTING_BOOK}/royalties.xml", format: :xml)
end
prompt_continue("Book Reader Emails")
test_step(step += 1, "Book Reader Emails") do
run_request(:get, "/#{EXISTING_BOOK}/reader_emails.json")
end
prompt_continue("Individual Purchases (JSON)")
test_step(step += 1, "Individual Purchases (JSON)") do
run_request(:get, "/#{EXISTING_BOOK}/individual_purchases.json")
end
prompt_continue("Individual Purchases (XML)")
test_step(step += 1, "Individual Purchases (XML)") do
run_request(:get, "/#{EXISTING_BOOK}/individual_purchases.xml", format: :xml)
end
prompt_continue("List Coupons (JSON)")
test_step(step += 1, "List Coupons (JSON)") do
run_request(:get, "/#{EXISTING_BOOK}/coupons.json")
end
prompt_continue("List Coupons (XML)")
test_step(step += 1, "List Coupons (XML)") do
run_request(:get, "/#{EXISTING_BOOK}/coupons.xml", format: :xml)
end
prompt_continue("Create Coupon")
coupon_code = "TEST#{Time.now.to_i}"
test_step(step += 1, "Create Coupon (#{coupon_code})") do
run_request(:post, "/#{EXISTING_BOOK}/coupons.json",
body: {
coupon: {
coupon_code: coupon_code,
package_discounts_attributes: [
{ package_slug: "book", discounted_price: 4.99 }
],
start_date: "2026-01-01",
end_date: "2026-12-31",
max_uses: 100,
note: "Test coupon from API script"
}
},
content_type: "application/json"
)
end
prompt_continue("Get Single Coupon")
test_step(step += 1, "Get Single Coupon (#{coupon_code})") do
run_request(:get, "/#{EXISTING_BOOK}/coupons/#{coupon_code}.json")
end
prompt_continue("Update Coupon")
test_step(step += 1, "Update Coupon (suspend #{coupon_code})") do
run_request(:put, "/#{EXISTING_BOOK}/coupons/#{coupon_code}.json",
body: { suspended: true, note: "Suspended via API test" }
)
end
end
# ============================================================
# Summary
# ============================================================
puts "\n" + "=" * 60
puts "\033[1m\033[32m ALL TESTS COMPLETE!\033[0m"
puts "=" * 60
puts
puts "Test book created: #{TEST_BOOK_SLUG}"
puts "Final state: closed"
puts
if EXISTING_BOOK
puts "Coupon '#{coupon_code}' was created and suspended on '#{EXISTING_BOOK}'."
end
puts