bookstack

package module
v0.0.0-...-abcbc6a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 30, 2026 License: MIT Imports: 12 Imported by: 0

README

bookstack-api

Mirror on GitHub Go Reference Go Report Card

A Go client library for the BookStack REST API. Zero external dependencies.

Installation

go get code.beautifulmachines.dev/jakoubek/bookstack-api

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    bookstack "code.beautifulmachines.dev/jakoubek/bookstack-api"
)

func main() {
    client, err := bookstack.NewClient(bookstack.Config{
        BaseURL:     "https://docs.example.com",
        TokenID:     os.Getenv("BOOKSTACK_TOKEN_ID"),
        TokenSecret: os.Getenv("BOOKSTACK_TOKEN_SECRET"),
    })
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    // List all books
    books, err := client.Books.List(ctx, nil)
    if err != nil {
        log.Fatal(err)
    }
    for _, book := range books {
        fmt.Printf("%d: %s\n", book.ID, book.Name)
    }
}

Authentication

BookStack uses token-based authentication. Create an API token in your BookStack user profile under API Tokens.

Set the token ID and secret as environment variables:

export BOOKSTACK_TOKEN_ID="your-token-id"
export BOOKSTACK_TOKEN_SECRET="your-token-secret"

Usage

results, err := client.Search.Search(ctx, "deployment guide", nil)
for _, r := range results {
    fmt.Printf("[%s] %s (score: %.1f)\n", r.Type, r.Name, r.Score)
}
Get a Page
page, err := client.Pages.Get(ctx, 42)
fmt.Println(page.HTML)
Export Page as Markdown
md, err := client.Pages.ExportMarkdown(ctx, 42)
fmt.Println(string(md))
Iterate All Books

Uses Go 1.23+ iterators for memory-efficient pagination:

for book, err := range client.Books.ListAll(ctx) {
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(book.Name)
}
Pagination and Filtering
pages, err := client.Pages.List(ctx, &bookstack.ListOptions{
    Count:  10,
    Offset: 0,
    Sort:   "-updated_at",
    Filter: map[string]string{"book_id": "1"},
})
Create and Update Pages
page, err := client.Pages.Create(ctx, &bookstack.PageCreateRequest{
    BookID:   1,
    Name:     "New Page",
    Markdown: "# Hello\n\nPage content here.",
})

page, err = client.Pages.Update(ctx, page.ID, &bookstack.PageUpdateRequest{
    Markdown: "# Updated\n\nNew content.",
})
Error Handling
page, err := client.Pages.Get(ctx, 999)
if errors.Is(err, bookstack.ErrNotFound) {
    fmt.Println("Page not found")
} else if errors.Is(err, bookstack.ErrUnauthorized) {
    fmt.Println("Invalid credentials")
}

Available Services

Service Operations
Books List, ListAll, Get
Pages List, ListAll, Get, Create, Update, Delete, ExportMarkdown, ExportPDF
Chapters List, ListAll, Get
Shelves List, ListAll, Get
Search Search
Attachments List, Get, Create, Update, Delete
Comments List, Get, Create, Update, Delete

Requirements

  • Go 1.23+
  • BookStack instance with API enabled

License

See LICENSE file.

Documentation

Overview

Package bookstack provides a Go client for the BookStack REST API.

Create a client with NewClient and use the service fields (Books, Pages, etc.) to interact with the API:

client, err := bookstack.NewClient(bookstack.Config{
    BaseURL:     "https://docs.example.com",
    TokenID:     os.Getenv("BOOKSTACK_TOKEN_ID"),
    TokenSecret: os.Getenv("BOOKSTACK_TOKEN_SECRET"),
})
if err != nil {
    log.Fatal(err)
}

books, err := client.Books.List(ctx, nil)

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound     = errors.New("resource not found")
	ErrUnauthorized = errors.New("unauthorized")
	ErrForbidden    = errors.New("forbidden")
	ErrRateLimited  = errors.New("rate limited")
	ErrBadRequest   = errors.New("bad request")
)

Sentinel errors for common API error conditions.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int    // HTTP status code
	Code       string // Error code from API response
	Message    string // Error message from API response
	Body       string // Raw response body
}

APIError represents an error returned by the Bookstack API.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is implements error matching for sentinel errors.

type Attachment

type Attachment struct {
	ID         int       `json:"id"`
	Name       string    `json:"name"`
	Extension  string    `json:"extension"`
	UploadedTo int       `json:"uploaded_to"`
	External   bool      `json:"external"`
	Order      int       `json:"order"`
	CreatedAt  time.Time `json:"created_at"`
	UpdatedAt  time.Time `json:"updated_at"`
	CreatedBy  int       `json:"created_by"`
	UpdatedBy  int       `json:"updated_by"`
	Content    string    `json:"content,omitempty"`
}

Attachment represents a Bookstack attachment.

type AttachmentCreateRequest

type AttachmentCreateRequest struct {
	Name       string `json:"name"`
	UploadedTo int    `json:"uploaded_to"`
	Link       string `json:"link,omitempty"`
}

AttachmentCreateRequest contains fields for creating an attachment.

type AttachmentUpdateRequest

type AttachmentUpdateRequest struct {
	Name string `json:"name,omitempty"`
	Link string `json:"link,omitempty"`
}

AttachmentUpdateRequest contains fields for updating an attachment.

type AttachmentsService

type AttachmentsService struct {
	// contains filtered or unexported fields
}

AttachmentsService handles operations on attachments.

func (*AttachmentsService) Create

Create creates a new link attachment.

func (*AttachmentsService) Delete

func (s *AttachmentsService) Delete(ctx context.Context, id int) error

Delete deletes an attachment by ID.

func (*AttachmentsService) Get

func (s *AttachmentsService) Get(ctx context.Context, id int) (*Attachment, error)

Get retrieves a single attachment by ID.

func (*AttachmentsService) List

func (s *AttachmentsService) List(ctx context.Context, opts *ListOptions) ([]Attachment, error)

List returns a list of attachments with optional filtering.

func (*AttachmentsService) Update

Update updates an existing attachment.

type Book

type Book struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Slug        string    `json:"slug"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	CreatedBy   int       `json:"created_by"`
	UpdatedBy   int       `json:"updated_by"`
	OwnedBy     int       `json:"owned_by"`
}

Book represents a Bookstack book.

type BooksService

type BooksService struct {
	// contains filtered or unexported fields
}

BooksService handles operations on books.

func (*BooksService) Get

func (s *BooksService) Get(ctx context.Context, id int) (*Book, error)

Get retrieves a single book by ID.

func (*BooksService) List

func (s *BooksService) List(ctx context.Context, opts *ListOptions) ([]Book, error)

List returns a list of books with optional filtering.

func (*BooksService) ListAll

func (s *BooksService) ListAll(ctx context.Context) iter.Seq2[Book, error]

ListAll returns an iterator over all books, handling pagination automatically.

type Chapter

type Chapter struct {
	ID          int       `json:"id"`
	BookID      int       `json:"book_id"`
	Name        string    `json:"name"`
	Slug        string    `json:"slug"`
	Description string    `json:"description"`
	Priority    int       `json:"priority"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	CreatedBy   int       `json:"created_by"`
	UpdatedBy   int       `json:"updated_by"`
	OwnedBy     int       `json:"owned_by"`
}

Chapter represents a Bookstack chapter.

type ChaptersService

type ChaptersService struct {
	// contains filtered or unexported fields
}

ChaptersService handles operations on chapters.

func (*ChaptersService) Get

func (s *ChaptersService) Get(ctx context.Context, id int) (*Chapter, error)

Get retrieves a single chapter by ID.

func (*ChaptersService) List

func (s *ChaptersService) List(ctx context.Context, opts *ListOptions) ([]Chapter, error)

List returns a list of chapters with optional filtering.

func (*ChaptersService) ListAll

func (s *ChaptersService) ListAll(ctx context.Context) iter.Seq2[Chapter, error]

ListAll returns an iterator over all chapters, handling pagination automatically.

type Client

type Client struct {

	// Service instances
	Attachments *AttachmentsService
	Books       *BooksService
	Chapters    *ChaptersService
	Comments    *CommentsService
	Pages       *PagesService
	Search      *SearchService
	Shelves     *ShelvesService
	// contains filtered or unexported fields
}

Client is the main Bookstack API client.

func NewClient

func NewClient(cfg Config) (*Client, error)

NewClient creates a new Bookstack API client. Returns an error if BaseURL, TokenID, or TokenSecret are empty.

type Comment

type Comment struct {
	ID        int       `json:"id"`
	PageID    int       `json:"page_id"`
	ParentID  int       `json:"parent_id,omitempty"`
	HTML      string    `json:"html"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedBy int       `json:"created_by"`
	UpdatedBy int       `json:"updated_by"`
}

Comment represents a Bookstack comment on a page.

type CommentCreateRequest

type CommentCreateRequest struct {
	PageID   int    `json:"page_id"`
	ParentID int    `json:"parent_id,omitempty"`
	HTML     string `json:"html"`
}

CommentCreateRequest contains fields for creating a comment.

type CommentUpdateRequest

type CommentUpdateRequest struct {
	HTML string `json:"html"`
}

CommentUpdateRequest contains fields for updating a comment.

type CommentsService

type CommentsService struct {
	// contains filtered or unexported fields
}

CommentsService handles operations on comments.

func (*CommentsService) Create

Create creates a new comment on a page.

func (*CommentsService) Delete

func (s *CommentsService) Delete(ctx context.Context, id int) error

Delete deletes a comment by ID.

func (*CommentsService) Get

func (s *CommentsService) Get(ctx context.Context, id int) (*Comment, error)

Get retrieves a single comment by ID.

func (*CommentsService) List

func (s *CommentsService) List(ctx context.Context, opts *ListOptions) ([]Comment, error)

List returns a list of comments with optional filtering.

func (*CommentsService) Update

func (s *CommentsService) Update(ctx context.Context, id int, req *CommentUpdateRequest) (*Comment, error)

Update updates an existing comment.

type Config

type Config struct {
	// BaseURL is the base URL of the Bookstack instance (e.g., "https://docs.example.com")
	BaseURL string

	// TokenID is the Bookstack API token ID
	TokenID string

	// TokenSecret is the Bookstack API token secret
	TokenSecret string

	// HTTPClient is the HTTP client to use for requests.
	// If nil, a default client with 30s timeout will be used.
	HTTPClient *http.Client
}

Config holds configuration for the Bookstack API client.

type ListOptions

type ListOptions struct {
	Count  int               // Max items per page (default 100, max 500)
	Offset int               // Offset for pagination
	Sort   string            // Sort field (e.g., "name", "-created_at")
	Filter map[string]string // Filters (e.g., {"name": "value"})
}

ListOptions contains common options for list operations.

type Page

type Page struct {
	ID        int       `json:"id"`
	BookID    int       `json:"book_id"`
	ChapterID int       `json:"chapter_id"`
	Name      string    `json:"name"`
	Slug      string    `json:"slug"`
	HTML      string    `json:"html"`
	Markdown  string    `json:"markdown"`
	Priority  int       `json:"priority"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	CreatedBy int       `json:"created_by"`
	UpdatedBy int       `json:"updated_by"`
	Draft     bool      `json:"draft"`
	Revision  int       `json:"revision_count"`
	Template  bool      `json:"template"`
	OwnedBy   int       `json:"owned_by"`
}

Page represents a Bookstack page.

type PageCreateRequest

type PageCreateRequest struct {
	BookID    int    `json:"book_id"`
	ChapterID int    `json:"chapter_id,omitempty"`
	Name      string `json:"name"`
	HTML      string `json:"html,omitempty"`
	Markdown  string `json:"markdown,omitempty"`
}

PageCreateRequest contains fields for creating a new page.

type PageUpdateRequest

type PageUpdateRequest struct {
	Name     string `json:"name,omitempty"`
	HTML     string `json:"html,omitempty"`
	Markdown string `json:"markdown,omitempty"`
}

PageUpdateRequest contains fields for updating an existing page.

type PagesService

type PagesService struct {
	// contains filtered or unexported fields
}

PagesService handles operations on pages.

func (*PagesService) Create

func (s *PagesService) Create(ctx context.Context, req *PageCreateRequest) (*Page, error)

Create creates a new page.

func (*PagesService) Delete

func (s *PagesService) Delete(ctx context.Context, id int) error

Delete deletes a page by ID.

func (*PagesService) ExportMarkdown

func (s *PagesService) ExportMarkdown(ctx context.Context, id int) ([]byte, error)

ExportMarkdown exports a page as markdown.

func (*PagesService) ExportPDF

func (s *PagesService) ExportPDF(ctx context.Context, id int) ([]byte, error)

ExportPDF exports a page as PDF.

func (*PagesService) Get

func (s *PagesService) Get(ctx context.Context, id int) (*Page, error)

Get retrieves a single page by ID, including its content.

func (*PagesService) List

func (s *PagesService) List(ctx context.Context, opts *ListOptions) ([]Page, error)

List returns a list of pages with optional filtering.

func (*PagesService) ListAll

func (s *PagesService) ListAll(ctx context.Context) iter.Seq2[Page, error]

ListAll returns an iterator over all pages, handling pagination automatically.

func (*PagesService) Update

func (s *PagesService) Update(ctx context.Context, id int, req *PageUpdateRequest) (*Page, error)

Update updates an existing page.

type SearchResult

type SearchResult struct {
	Type      string  `json:"type"` // "page", "chapter", "book", or "shelf"
	ID        int     `json:"id"`
	Name      string  `json:"name"`
	Slug      string  `json:"slug"`
	BookID    int     `json:"book_id"`    // For pages and chapters
	ChapterID int     `json:"chapter_id"` // For pages
	Preview   string  `json:"preview"`
	Score     float64 `json:"score"`
}

SearchResult represents a search result from Bookstack.

type SearchService

type SearchService struct {
	// contains filtered or unexported fields
}

SearchService handles search operations.

func (*SearchService) Search

func (s *SearchService) Search(ctx context.Context, query string, opts *ListOptions) ([]SearchResult, error)

Search performs a full-text search query across all content types. The query parameter uses Bookstack's search syntax.

type Shelf

type Shelf struct {
	ID          int       `json:"id"`
	Name        string    `json:"name"`
	Slug        string    `json:"slug"`
	Description string    `json:"description"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	CreatedBy   int       `json:"created_by"`
	UpdatedBy   int       `json:"updated_by"`
	OwnedBy     int       `json:"owned_by"`
}

Shelf represents a Bookstack shelf.

type ShelvesService

type ShelvesService struct {
	// contains filtered or unexported fields
}

ShelvesService handles operations on shelves.

func (*ShelvesService) Get

func (s *ShelvesService) Get(ctx context.Context, id int) (*Shelf, error)

Get retrieves a single shelf by ID.

func (*ShelvesService) List

func (s *ShelvesService) List(ctx context.Context, opts *ListOptions) ([]Shelf, error)

List returns a list of shelves with optional filtering.

func (*ShelvesService) ListAll

func (s *ShelvesService) ListAll(ctx context.Context) iter.Seq2[Shelf, error]

ListAll returns an iterator over all shelves, handling pagination automatically.

Directories

Path Synopsis
examples
basic command
Basic example: set up client, list books, get a page.
Basic example: set up client, list books, get a page.
export command
Export example: export a page to markdown or PDF.
Export example: export a page to markdown or PDF.
search command
Search example: search for content and display results.
Search example: search for content and display results.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL