npm.io
2.0.0 • Published 18h ago

apibooks

Licence
MIT
Version
2.0.0
Deps
3
Size
1.9 MB
Vulns
0
Weekly
0

Apibooks - Open Source Documentation for Everyone

npm version License Node.js Version

Apibooks is a lightweight and easy-to-use Express.js module that auto-generates API documentation by capturing route information and developer-submitted specs. It was built to simplify the UI/UX of open source backend projects by making documentation accessible and clear.

Current Version: 2.0.0


By the maintainer · Par le mainteneur

Hi, I'm Rayan Chattaoui — creator and active maintainer of apibooks. It's the documentation piece of a small open-source family I build and maintain, all designed to work together:

  • apibooks — auto-generate beautiful API docs
  • apiupbot — distributed uptime monitoring
  • apifacility — build real APIs from a JSON spec

Star it, install it, and tell me what you need next — issues and ideas are always welcome.

Bonjour, je suis Rayan Chattaoui — créateur et mainteneur actif d'apibooks. C'est la brique documentation d'une petite famille open-source que je développe et maintiens, pensée pour fonctionner ensemble (apibooks + apiupbot + apifacility). Mets une étoile, installe, et dis-moi ce qu'il te faut ensuite — vos retours et idées sont les bienvenus.


What's new · Nouveautés (v2.0)

What changed vs the previous versions:

  • New visual template system — 8 ready-to-use documentation themes: Dashboard, Minimal, Notion, Readme, Stripe, Swagger, Terminal, Books
  • Notion-style block editor for internal notes — drag-to-reorder blocks, slash commands, headings, callouts and code blocks
  • Ecosystem interop — apibooks now works out of the box alongside apiupbot and apifacility
  • Consistent syntax highlighting across every template
  • Free hosting via SlashCDN (see below)

Previous highlights (v1.7.x): 6 built-in themes, auto-detection of params/status codes, WebSocket docs, multi-language code samples, hot reload and OpenAPI 3.0 export — see the full Version History below.

Ce qui a changé par rapport aux versions précédentes :

  • Nouveau système de templates visuels — 8 thèmes de documentation prêts à l'emploi : Dashboard, Minimal, Notion, Readme, Stripe, Swagger, Terminal, Books
  • Éditeur de blocs façon Notion pour les notes internes — réorganisation par glisser-déposer, commandes slash, titres, encadrés et blocs de code
  • Interopérabilité — apibooks fonctionne désormais nativement avec apiupbot et apifacility
  • Coloration syntaxique cohérente sur tous les templates
  • Hébergement gratuit via SlashCDN (ci-dessous)

SlashCDN — Free hosting (Alpha)

I run a fleet of servers across several regions, and I'm opening them up as SlashCDN — free hosting & CDN for the whole API ecosystem. It's in early alpha, so I'm looking for a handful of people to push it in real-world conditions before the wider launch.

Pre-register now and you'll be able to host your Apibooks docs (and the APIs behind them) on it for free. Only the first 100 get in during the alpha — it takes 20 seconds, no card, no catch.

Tier Spots Access
Alpha first 100 early access + real-world testing
Beta up to 500 expanded rollout
Launch up to 1000 public availability

Claim your free spot: preregister.slashcdn.com


Installation

npm install apibooks

Update

npm install apibooks@latest

How It Works

Apibooks automatically scans your Express app routes and optionally loads an openapi.json file for more detailed documentation. You can also manually attach documentation to your endpoints using requireDocs().

The documentation will be served as an interactive web page at the endpoint of your choice (default is /docs).

Key Features:

  • Auto-detection of route parameters (path, query, body)
  • Multiple themes with dark mode support
  • Hot reload for development
  • Responsive design with mobile support
  • Multi-language code samples (Node.js, Python, PHP, cURL)
  • Auto-detection of HTTP status codes from your handlers
  • WebSocket support with custom method documentation

Basic Usage

const express = require("express");
const apiDoc = require("apibooks");

const app = express();

// --- ROUTES ---
app.get("/hello", (req, res) => {
  res.json({ message: "Hello, World!" });
});

app.post("/user", (req, res) => {
  const { name, email } = req.body;
  res.status(201).json({ message: "User created", name, email });
});

// --- DOC API (automatic generation accessible at /docs) ---
const doc = apiDoc(app, {
  name: "My API Documentation",
  endpoint: "/docs",
  baseUrl: "https://api.example.com",
  requireDocs: {
    hotReload: true, // 🚀 Reloads requireDocs when this file changes
    openapi: false   // ❌ Disable OpenAPI file loading
  }
});

// --- Add custom documentation ---
doc.requireDocs("/hello", {
  description: "Returns a welcome message.",
  responses: {
    "200": `{ "message": "Hello, World!" }`,
    "500": "Internal server error"
  }
});

doc.requireDocs("/user", {
  description: "Creates a new user.",
  parameters: [
    { name: "name", type: "string", in: "body", description: "User's name", required: true },
    { name: "email", type: "string", in: "body", description: "User's email", required: true }
  ],
  responses: {
    "201": `{ "message": "User created", "name": "John", "email": "john@example.com" }`,
    "400": "Bad request - missing required fields"
  }
});

// --- Start server ---
app.listen(3000, () => {
  console.log("✅ Server started: http://localhost:3000");
  console.log("📚 Documentation: http://localhost:3000/docs");
});

Features

Core Features
  • Auto-detect Express routes with all HTTP methods
  • Automatic parameter extraction from route handlers:
    • Path parameters (:id, :name, etc.)
    • Query parameters (req.query.*)
    • Body parameters (req.body.* and destructured)
  • Automatic status code detection from res.status() and res.sendStatus()
  • Support for custom methods (WS, WEBSOCKET, etc.)
  • OpenAPI 3.0 support with auto-generation
  • Hot reload support for requireDocs() with file watching
  • Responsive mobile-friendly UI
UI/UX Features
  • 6 built-in themes: default, ocean, forest, sunset, purple, rose
  • Dark mode toggle with persistent preference
  • Mobile responsive design with adaptive layouts
  • Syntax highlighting for code samples
  • Copy to clipboard for all code examples
  • Collapsible sidebar with endpoint navigation
  • Auto-generated API introduction with statistics
  • Custom logo support with configurable size
Documentation Features
  • Multi-language code samples (Node.js, Python, PHP, cURL)
  • Parameter documentation with location badges (path, query, body, header)
  • Response examples with HTTP status code colors
  • Required/Optional parameter indicators
  • Common parameters section in introduction
  • Authentication section with headers example

Complete Configuration Options

Option Type Default Description
endpoint string /docs URL path where the documentation is served
name string Documentation API Title displayed at the top of the documentation
openapi string openapi.json Path to OpenAPI file (if available)
baseUrl string https://api.example.com Base URL for API requests in code samples
showIntroduction boolean true Show/hide the auto-generated API introduction
logo string null URL of the logo image to display
logoSize number 32 Size of the logo in pixels
theme string | object default Theme name or custom theme object (see below)
fileWatch string | array null Files to watch for hot reload (default: main file)
requireDocs.hotReload boolean false Enable hot reload of requireDocs() blocks
requireDocs.openapi boolean true Load documentation from OpenAPI file

Themes

Apibooks includes 6 beautiful pre-built themes. You can use them by name or create your own custom theme.

Built-in Themes
const doc = apiDoc(app, {
  theme: "ocean" // Options: "default", "ocean", "forest", "sunset", "purple", "rose"
});

Available themes:

  • default - Indigo primary with neutral grays
  • ocean - Sky blue with oceanic tones
  • forest - Emerald green with nature-inspired colors
  • sunset - Warm amber and golden hues
  • purple - Vibrant purple with elegant accents
  • rose - Pink/rose with soft romantic colors
Custom Theme

Create your own theme by providing a theme object:

const doc = apiDoc(app, {
  theme: {
    primary: '#FF6B6B',              // Main accent color
    backgroundLight: '#F8F9FA',      // Light mode background
    backgroundDark: '#0D1117',       // Dark mode background
    surfaceLight: '#FFFFFF',         // Light mode surface/cards
    surfaceDark: '#161B22',          // Dark mode surface/cards
    textLight: '#1A1A1A',            // Light mode text
    textDark: '#E6EDF3',             // Dark mode text
    subtleLight: '#6B7280',          // Light mode subtle text
    subtleDark: '#9CA3AF',           // Dark mode subtle text
    borderLight: '#E5E7EB',          // Light mode borders
    borderDark: '#30363D',           // Dark mode borders
    codeBgDark: '#0D1117'            // Dark mode code background
  }
});

Hot Reload

Hot reload allows you to update your documentation without restarting your server. Perfect for development!

Basic Hot Reload
const doc = apiDoc(app, {
  requireDocs: {
    hotReload: true  // Watches the main file for changes
  }
});
Watch Multiple Files
const doc = apiDoc(app, {
  fileWatch: ['./server.js', './routes/api.js', './routes/users.js'],
  requireDocs: {
    hotReload: true
  }
});

Note: Hot reload detects changes to requireDocs() definitions and route structure, but does not reload route handlers. For handler changes, restart your server.


WebSocket Documentation

Document WebSocket endpoints with custom method types:

// Define a WebSocket route (for documentation purposes)
app.get("/chat", (req, res) => {
  res.json({ type: "websocket" });
});

// Document it as a WebSocket endpoint
doc.requireDocs("/chat", "WS", {
  description: "Real-time chat WebSocket connection. Connect using ws://localhost:3000/chat",
  parameters: [
    {
      name: "message",
      type: "string",
      in: "body",
      description: "Message to send via WebSocket",
      required: true
    }
  ],
  responses: {
    "101": "Switching Protocols - WebSocket connection established",
    "400": "Bad request"
  }
});

Advanced Parameter Documentation

Parameter Locations

Parameters support 4 locations:

doc.requireDocs("/users/:id", "GET", {
  description: "Get user by ID with optional filters",
  parameters: [
    // Path parameter
    {
      name: "id",
      type: "string",
      in: "path",
      description: "User ID",
      required: true
    },
    // Query parameter
    {
      name: "include",
      type: "string",
      in: "query",
      description: "Related resources to include",
      required: false
    },
    // Header parameter
    {
      name: "Authorization",
      type: "string",
      in: "header",
      description: "Bearer token",
      required: true
    },
    // Body parameter (for POST/PUT/PATCH)
    {
      name: "name",
      type: "string",
      in: "body",
      description: "User's full name",
      required: true
    }
  ]
});
Auto-Detection of Parameters

Apibooks automatically detects parameters from your route handlers:

// This route will auto-detect: id (path), limit (query), name and email (body)
app.post("/users/:id", (req, res) => {
  const { name, email } = req.body;
  const limit = req.query.limit;
  const userId = req.params.id;

  res.json({ userId, name, email, limit });
});

The documentation will automatically show:

  • id as a path parameter
  • limit as a query parameter
  • name and email as body parameters

OpenAPI Generation

Apibooks can generate an OpenAPI 3.0 specification dynamically:

Access Generated OpenAPI
GET /docs/openapi.json

This endpoint returns a complete OpenAPI 3.0 specification based on your routes and requireDocs() definitions.

Load from OpenAPI File
const doc = apiDoc(app, {
  openapi: "./my-openapi.json",
  requireDocs: {
    openapi: true  // Enable OpenAPI file loading
  }
});

Logo Configuration

Add your brand logo to the documentation:

const doc = apiDoc(app, {
  logo: "https://example.com/logo.png",
  logoSize: 48  // Size in pixels
});

Or use a local file:

const doc = apiDoc(app, {
  logo: "/images/logo.png",  // Served from your public folder
  logoSize: 40
});

Responsive Design

The documentation UI is fully responsive with:

  • Desktop: Full sidebar with table layouts
  • Tablet: Collapsible sidebar with optimized spacing
  • Mobile: Hidden sidebar (click to open) with card-based parameter display

No configuration needed - it just works!


Status Code Auto-Detection

Apibooks automatically detects HTTP status codes from your handlers:

app.post("/login", (req, res) => {
  const { email, password } = req.body;

  if (!email || !password) {
    return res.status(400).json({ error: "Missing credentials" });
  }

  if (!isValidUser(email, password)) {
    return res.status(401).json({ error: "Invalid credentials" });
  }

  res.status(200).json({ token: "abc123" });
});

The documentation will automatically show:

  • 200: Success response with token
  • 400: Bad Request - Missing credentials
  • 401: Unauthorized - Invalid credentials

Advanced Example

Complete example with all features:

const express = require("express");
const apiDoc = require("apibooks");

const app = express();
app.use(express.json());

// Routes
app.get("/api/users", (req, res) => {
  const { page, limit } = req.query;
  res.json({ users: [], page, limit });
});

app.post("/api/users", (req, res) => {
  const { name, email } = req.body;
  if (!name || !email) {
    return res.status(400).json({ error: "Missing required fields" });
  }
  res.status(201).json({ id: 1, name, email });
});

app.get("/api/users/:id", (req, res) => {
  const { id } = req.params;
  res.json({ id, name: "John Doe", email: "john@example.com" });
});

// Initialize documentation
const doc = apiDoc(app, {
  name: "My Awesome API",
  endpoint: "/documentation",
  baseUrl: "https://api.myapp.com",
  logo: "https://myapp.com/logo.png",
  logoSize: 48,
  theme: "ocean",
  showIntroduction: true,
  fileWatch: ['./server.js'],
  requireDocs: {
    hotReload: true,
    openapi: false
  }
});

// Document endpoints
doc.requireDocs("/api/users", "GET", {
  description: "Retrieve a paginated list of users",
  parameters: [
    { name: "page", type: "number", in: "query", description: "Page number", required: false },
    { name: "limit", type: "number", in: "query", description: "Items per page", required: false }
  ],
  responses: {
    "200": { users: [], page: 1, limit: 10 }
  }
});

doc.requireDocs("/api/users", "POST", {
  description: "Create a new user",
  parameters: [
    { name: "name", type: "string", in: "body", description: "User's full name", required: true },
    { name: "email", type: "string", in: "body", description: "User's email address", required: true }
  ],
  responses: {
    "201": { id: 1, name: "John Doe", email: "john@example.com" },
    "400": { error: "Missing required fields" }
  }
});

doc.requireDocs("/api/users/:id", "GET", {
  description: "Get a specific user by ID",
  parameters: [
    { name: "id", type: "string", in: "path", description: "User ID", required: true }
  ],
  responses: {
    "200": { id: "1", name: "John Doe", email: "john@example.com" },
    "404": { error: "User not found" }
  }
});

app.listen(3000, () => {
  console.log("Server: http://localhost:3000");
  console.log("Docs: http://localhost:3000/documentation");
});

Version History

Version 2.0.0 (Latest)

Visual templates, block editor & ecosystem release

Visual Template System:

  • 8 ready-to-use documentation themes: Dashboard, Minimal, Notion, Readme, Stripe, Swagger, Terminal, Books
  • Consistent syntax highlighting (highlight.js) applied across every template

Notion-style Block Editor (internal notes):

  • Drag-to-reorder blocks, slash commands, headings, callouts, quotes, lists and code blocks
  • Copy-to-clipboard on code blocks, inline formatting toolbar (bold, italic, inline code, link)

Ecosystem Interop:

  • Works out of the box alongside apiupbot (uptime monitoring) and apifacility (declarative API builder)

Free Hosting:


Version 1.7.3

Major Release - Comprehensive Documentation Overhaul

Theming System:

  • 6 Built-in Professional Themes (default, ocean, forest, sunset, purple, rose)
  • Custom Theme Support with full color customization
  • Enhanced Dark Mode with persistent preferences
  • Dynamic theme injection system

Auto-Detection Features:

  • Automatic Parameter Extraction from route handlers
    • Path parameters (:id, :name, etc.)
    • Query parameters (req.query.*)
    • Body parameters (req.body.* and destructured { name, email } = req.body)
  • Automatic Status Code Detection from res.status() and res.sendStatus()
  • Auto-generated API Introduction with statistics and common parameters
  • Auto-generated Authentication section with headers

WebSocket & Custom Methods:

  • Full WebSocket Documentation Support (WS, WEBSOCKET methods)
  • Custom HTTP Method Support
  • Visual method badges with custom colors

Code Samples & Examples:

  • Auto-generated Multi-language Code Samples
    • Node.js (axios)
    • Python (requests)
    • PHP (cURL)
    • cURL command-line
  • Copy to Clipboard for all code examples
  • Context-aware sample generation based on parameters

UI/UX Improvements:

  • Fully Responsive Mobile-Optimized Design
    • Desktop: Full sidebar with table layouts
    • Tablet: Collapsible sidebar
    • Mobile: Hidden sidebar with card-based displays
  • Custom Logo Support with configurable size
  • Enhanced Visual Design with gradients and animations
  • Parameter Location Badges (path, query, body, header)
  • Response Status Code Color Coding
  • Required/Optional Parameter Indicators
  • Collapsible Sidebar with smooth transitions

Hot Reload System:

  • Enhanced Hot Reload with intelligent file watching
  • Debouncing to prevent multiple reloads
  • Multi-file watching support
  • Selective documentation reload without server restart

OpenAPI Integration:

  • Dynamic OpenAPI 3.0 Specification Generation
  • /docs/openapi.json endpoint
  • OpenAPI file import support
  • Bidirectional sync between requireDocs and OpenAPI

New Configuration Options:

  • baseUrl - Base URL for API requests in code samples
  • showIntroduction - Toggle auto-generated API introduction
  • logo - Custom logo URL or path
  • logoSize - Logo size in pixels (default: 32)
  • theme - Theme selection (string or object)
  • fileWatch - Files to watch for hot reload (string or array)
  • requireDocs.openapi - Enable/disable OpenAPI file loading

Bug Fixes & Performance:

  • Fixed route detection for nested routers
  • Improved parameter merging logic (manual + auto-detected)
  • Enhanced HTML escaping for security
  • Optimized template generation
  • Better error handling for malformed responses
Previous Versions
  • 1.6.0 - Enhanced UI, basic theming, initial auto-detection
  • 1.5.0 - Hot reload support, improved route detection
  • 1.4.0 - OpenAPI file support, enhanced documentation
  • 1.3.0 - Dark mode toggle, sidebar navigation
  • 1.2.0 - Multi-method support, response documentation
  • 1.1.0 - Parameter documentation, basic UI
  • 1.0.0 - Initial release with basic route detection

Development Team

Apibooks is developed and maintained by passionate developers who believe in making API documentation accessible and beautiful for everyone.

Core Development
  • Built with dedication by the open-source community
  • Community-driven feature development
  • Continuous improvements based on real-world usage feedback
Contributing

We welcome contributions from developers of all skill levels! Whether it's:

  • Bug fixes and issue reports
  • New feature implementations
  • Documentation improvements
  • UI/UX enhancements
  • Translations and internationalization
  • Feature suggestions and discussions
  • Testing and quality assurance

Visit our GitHub repository to contribute!


Contribution Guidelines

This project is open-source and made for the community. Feel free to submit issues, pull requests, or ideas!

How to contribute:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Contribution areas:

  • Add new themes or improve existing ones
  • Enhance auto-detection algorithms
  • Add support for more languages in code samples
  • Improve mobile responsiveness
  • Add new configuration options
  • Write tutorials and examples

License

MIT License - feel free to use this in your personal and commercial projects!


Support the Project

Are you using Apibooks?

  • ️ Star the repo — it helps us grow!
  • Share it with your developer community
  • Report bugs and suggest features
  • Contribute to the codebase
  • Write about your experience using Apibooks

Show your support:

npm install apibooks@latest

Contact & Resources


Why Choose Apibooks?

Zero Configuration - Works out of the box Developer Friendly - Intuitive API and documentation Beautiful UI - Modern, responsive design with dark mode Smart Auto-Detection - Minimal manual documentation needed Highly Customizable - Themes, logos, and full configuration control Open Source - Free forever, community-driven Active Development - Regular updates and improvements


Made with

Apibooks v1.7.3 (correct Readme)- Making API documentation beautiful and effortless

Happy documenting!