You are on page 1of 26

Table

of Contents

Overview
Introduction 1.1
OAuth 1.2

Books
Overview 2.1
Traffic 2.2
Access Keys 2.3
Versions 2.4
Contents 2.5
Discussions 2.6
Webhooks 2.7

Authors
Overview 3.1

Miscellaneous
Search 4.1
Topics 4.2

1
Introduction

GitBook API Reference


This documentation is intended to get you up-and-running with the GitBook APIs. We’ll cover
everything you need to know, from authentication, to manipulating results, to combining
results with other services.

The REST APIs provide programmatic access to read and write GitBook data. List books,
edit content, proofread text, and more. The REST API identifies users using basic auth;
responses are available in JSON.

Schema
All API access is over HTTPS, and accessed through https://api.gitbook.com . All data is
sent and received as JSON.

$ curl -i https://api.gitbook.com/author/gitbookio

HTTP/1.1 200 OK
Server: GitBook.com
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Content-Length: 275
Etag: W/"113-25d22777"
Date: Thu, 11 Jun 2015 14:49:26 GMT
Via: 1.1 vegur

{ ... }

Install the GitBook API client from NPM:

$ npm install gitbook-api

Initialize a client:

const GitBook = require('gitbook-api');

const client = new GitBook();

Install the GitBook API client using go get :

2
Introduction

$ go get github.com/GitbookIO/go-gitbook-api

Initialize a client:

package main

import (
"fmt"
"github.com/GitbookIO/go-gitbook-api"
)

func main() {
api := gitbook.NewAPI(gitbook.APIOptions{})
}

Authentication
While the API provides multiple methods for authentication, we strongly recommend using
OAuth for production applications. The other methods provided are intended to be used for
scripts or testing (i.e., cases where full OAuth would be overkill).

Third party applications that rely on GitBook for authentication should not ask for or collect
GitBook credentials. Instead, they should use the OAuth web flow.

All API requests must be made over HTTPS. Calls made over plain HTTP will fail.

The API supports Basic Authentication as defined in RFC2617 with a few slight differences.

Requests that require authentication will return 404 Not Found , instead of 403 Forbidden , in
some places. This is to prevent the accidental leakage of private books to unauthorized
users.

Via Username and Password

To use Basic Authentication with the GitBook API, simply send the username and password
associated with the account.

For example, if you’re accessing the API via cURL, the following command would
authenticate you if you replace with your GitBook username. (cURL will prompt you to enter
the password.)

Alternatively, you can use personal access tokens or OAuth tokens instead of your
password.

3
Introduction

$ curl -u <username>:<password or token> https://api.gitbook.com/account

Via OAuth Tokens

The access token allows you to make requests to the API on a behalf of a user.

$ curl -H "Authorization: token OAUTH-TOKEN" https://api.gitbook.com/account

Via Username and Password

const client = new GitBook({


username: 'MyUsername',
token: 'password'
});

Via OAuth Tokens

const client = new GitBook({


token: 'oauth token'
});

Via Username and Password

api := gitbook.NewAPI(gitbook.APIOptions{
Username: "username",
Password: "password",
})

Via OAuth Tokens

api := gitbook.NewAPI(gitbook.APIOptions{
Token: "token"
})

Errors
GitBook uses conventional HTTP response codes to indicate the success or failure of an
API request.

4
Introduction

In general, codes in the 2xx range indicate success, codes in the 4xx range indicate an
error that failed given the information provided (e.g., a required parameter was omitted, a
charge failed, etc.), and codes in the 5xx range indicate an error with Stripe's servers
(these are rare).

Not all errors map cleanly onto HTTP response codes, however.

HTTP status code summary

Status Description
200 - OK Everything worked as expected.
400 - Bad The request was unacceptable, often due to missing a required
Request parameter.
404 - Not Found The requested resource doesn't exist.

Example Response

{
"error": "A human-readable message providing more details about the error.",
"code": 400
}

All API calls return promises.

client.books()
.then(function(result) {

}, function(err) {

});

The status code can be access using the code property of the error: err.code .

All API calls return both the result and the error:

book, err := api.Book.Get("gitbookio/javascript")

Pagination
Requests that return multiple items will be paginated to 50 items by default.

You can specify further pages with the ?page parameter. For some resources, you can also
set a custom page size up to 100 with the ?limit .

5
Introduction

Paginated results will be returned with information about the page context.

{
list: [ ... ],
page: 0,
limit: 50,
total: 0
}

Paginated methods return a Page object.

Calling page.next() or page.prev() will fetch the next/previous page and return a promise
with a new Page object.

page.list: Array<Mixed> contains the items of current page.

page.total: Number is count of all elements.

client.books()
.then(function(page) {
console.log('Total:', page.total);
console.log('In this page:', page.list.length);

// Fetch next page


return page.next();
}, function(err) {
// Error occured
});

Enterprise
All API endpoints are prefixed with the following URL: http(s)://hostname/api/ .

Most methods require an authentication when using an enterprise instance.

$ curl https://gitbook/myenterprise.com/api/books/all

const client = new GitBook({


host: 'http://gitbook.mycompany.com'
});

api := gitbook.NewAPI(gitbook.APIOptions{
Host: "http://gitbook.mycompany.com/api/"
})

6
Introduction

Help and Support


We're always happy to help out with your applications or any other questions you might
have. You can ask a question or signal an issue using inline comments.

7
OAuth

OAuth
OAuth2 is a protocol that lets external applications request authorization to private details in
a user's GitBook account without getting their password. This is preferred over Basic
Authentication because tokens can be limited to specific types of data, and can be revoked
by users at any time.

All developers need to register their application before getting started. A registered OAuth
application is assigned a unique Client ID and Client Secret. The Client Secret should not be
shared.

You may create a personal access token for your own use or implement the web flow below
to allow other users to authorize your application.

Web Application Flow


This is a description of the OAuth2 flow from 3rd party web sites.

1. Redirect users to request GitBook access


The first step is to redirect the user to the authorization dialog, this dialog will ask user to
grant access to your application.

GET https://api.gitbook.com/oauth/authorize

Parameter Type Description

client_id string
Required. The client ID you received from GitBook when
you registered.

redirect_uri string
Required. The URL in your application where users will
be sent after authorization.

response_type string
Required. Type of response expected, currently only
valid value is code

2. GitBook redirects back to your site


If the user accepts your request, GitBook redirects back to your site with a temporary code
in a code parameter as well as the state you provided in the previous step in a state
parameter. If the states don't match, the request has been created by a third party and the

8
OAuth

process should be aborted.

You can exchange this code for an access token.

POST https://api.gitbook.com/oauth/access_token

Parameters

Name Type Description

client_id string
Required. The client ID you received from GitBook when
you registered.

client_secret string
Required. The client secret you received from GitBook
when you registered.

code string
Required. The code you received as a response to Step
1.

grant_type string
Required. authorization_code to exchange an oauth
code

Response

By default, the response will take the following form:

access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer

access_token can also be returned as JSON.

3. Use the access token to access the API


The access token allows you to make requests to the API on a behalf of a user.

Include it in the Authorization header

Authorization: Bearer OAUTH-TOKEN

For example, in cUrl you can set the Authorization header like this:

$ curl -H "Authorization: Bearer OAUTH-TOKEN" https://api.gitbook.com/account

9
Overview

Books

List your books


List books that are accessible to the authenticated user.

This includes books owned by the authenticated user, books where the authenticated user is
a collaborator, and books that the authenticated user has access to through an organization
membership.

GET /books

Parameters

Name Type Description


page number Index of current page

List author books


List public books for the specified user/organization.

GET /authors/:username/books

Parameters

Name Type Description

page number Index of current page

List all public books


This provides a dump of every public repository, in the order that they were created.

GET /books/all

Parameters

10
Overview

Name Type Description

page number Index of current page

Create a book
Create a new book for the specified author.

POST /books

Parameters

Name Type Description


author string Required: Username of the owner
title string Required: The title of the book
description string The description of the book

Get a book
Get details about a book.

GET /book/:username/:name

Example Response

{
"id": "johndoe/mybook",
"title": "My Book"
}

11
Traffic

Traffic
The Traffic API lets you fetch statistics about views and downloads.

Get summary
This methods returns a summary of traffic statistics.

GET /book/:author/:book/traffic

Response

{
views: 100,
unique: 10,
downloads: {
pdf: 3,
epub: 3,
mobi: 1
}
}

Get visits per countries


This method returns the count of visits per countries.

GET /book/:author/:book/traffic/countries

Get visits per platforms


This method returns the count of visits per platforms.

GET /book/:author/:book/traffic/platforms

12
Access Keys

Access Keys
Access keys allow non-collaborator to access a private book. Each access key can be
converted to an unique read-only access url.

Create an access key


Create a new book for the specified author.

POST /book/:author/:book/keys

Parameters

Name Type Description


label string Required: Label to identify the key
Optional value of the key, if not provided it'll be set as a random
key string
string

List access keys for a book


GET /book/:author/:book/keys/

Example Response

13
Access Keys

{
"list": [
{
"id": "564c97a917c24e09ddd8b765",
"label": "For Aaron",
"key": "aaron_private_key",
"active": true,
"dates": {
"created": "2015-11-19T12:22:27.765Z",
"updated": "2015-11-19T12:22:27.765Z"
}
}
...
],
"total": 15,
"limit": 10,
"page": 0
}

14
Versions

Versions
The versions API can be used to list available versions of a book (branches, tags or
commits). The Contents API can then be used to fetch files for a specific version.

See Format for details about the version object format.

The Versions plugins can be enabled to list versions of the book in the sidebar.

List branches
This method returns the list of active branches in the book's git repository.

GET /book/:author/:book/versions/branches

List tags
This method returns the list of Git tags in the book's git repository.

GET /book/:author/:book/versions/tags

List languages
For multilingual book, this method returns the list of languages.

GET /book/:author/:book/versions/languages

Version Format
Each version (Tag, Branch or Language) is represented by a version object.

The current is set to true when its represent the main version (current branch, current
language, etc).

15
Versions

{
"name": "master",
"urls": {
"website": "https://samypesse.gitbooks.io/how-to-create-an-operating-system/co
ntent/",
"epub": "https://www.gitbook.com/download/epub/book/samypesse/how-to-create
-an-operating-system/",
"pdf": "https://www.gitbook.com/download/pdf/book/samypesse/how-to-create-
an-operating-system/",
"mobi": "https://www.gitbook.com/download/mobi/book/samypesse/how-to-create
-an-operating-system/"
},
"current": true
}

16
Contents

Contents
These API methods let you retrieve the contents of pages within a book.

It can be used to programmatically integrate your documentation content into your


application.

Get contents
This method returns the contents of a page in a book. All pages are ending with a .json
extension.

See Format for details about the output.

GET /book/:author/:book/contents/:file

Parameters

Name Type Description


file string Required: Path of the file to retrieve (with .json extension)

Get contents for a specific version


The Contents API can also serve other versions than the main one.

It can be used to retrieve contents for a specific Git tag, branch or commit.

See the Versions API for details on how to list versions.

GET /book/:author/:book/contents/v/:version/:file

Parameters

Name Type Description


version string Required: SHA, Branch name or Tag
file string Required: Path of the file to retrieve (with .json extension)

17
Contents

File format
The GitBook Contents API serve content of JSON build from the GitBook Toolchain. The
format may vary between GitBook version being used to generate your book.

Version 2
Currently the default version, but soon to be deprecated.

Example

{
"progress": {
...
},
"sections": [
{
"type": "normal",
"content": "<h1>My Awesome book</h1>"
}
],
"langs": []
}

Version 3
This format is generated since GitBook >=3.0.0 . It is a modern and easier format to work
with.

Contents API can output all books with this format when the client accepts
application/vnd.gitbook.format.v3 :

curl -H "Accept: application/json;application/vnd.gitbook.format.v3" \


"https://api.gitbook.com/book/you/your-book/contents/README.json"

Example

18
Contents

{
"page": {
"title": "Introduction",
"level": "1.1",
"depth": 1,
"next": {
"title": "OAuth",
"level": "1.2",
"depth": 1,
"path": "overview/oauth.md",
"ref": "overview/oauth.md",
"articles": []
},
"content": "<h1>....</h1> ..."
},
"file": {
"path": "README.md",
"mtime": "2016-08-22T21:58:34.000Z",
"type": "markdown"
},
"version": "3"
}

19
Discussions

Discussions
The Discussion API lets you create, list and comment discussions in books.

List discussions for a book


List all opened discussions in a book, all or closed discussions can be listed using the
state parameter.

This method is paginated.

GET /book/:author/:book/discussions

Parameters

Name Type Description

state string State of the discussions ( open , closed or all ), default is


open

filename string Optional file to filter discussions

Create a new discussion


Any user with read access can create a discussion.

POST /book/:author/:book/discussions

Parameters

Name Type Description


title string Required. Title of the discussion.
body string The contents of the discussion.

Close a list of discussions


Mark a list of discussions as closed for a book.

20
Discussions

POST /book/:author/:book/discussions/close

Parameters

Name Type Description


Required. An array containing the threads numbers to mark as
list array
closed.

Open a list of discussions


Mark a list of discussions as open for a book.

POST /book/:author/:book/discussions/open

Parameters

Name Type Description


list array Required. An array containing the threads numbers to mark as open.

21
Webhooks

Webhooks
Webhooks allow you to build or set up integrations which subscribe to certain events on
GitBook.com. When one of those events is triggered, we’ll send a HTTP POST payload to
the webhook’s configured URL.

Example of Integrations
Slack Notifications

List webhooks
List webhooks in a book requires admin" permission.

GET /book/:author/:book/webhooks/

Get single hook


GET /book/:author/:book/webhooks/:id

Get deliveries for a hook


GitBook stores deliveries for a period of 30days.

GET /book/:author/:book/webhooks/:id/deliveries

Get single delivery


Use this method to inspect payload and result of a webhook delivery.

GET /book/:author/:book/webhooks/:id/deliveries/:delivery

Receiving webhooks
22
Webhooks

Events

When configuring a webhook, you can choose which events you would like to receive
payloads for. You can even opt-in to all current and future events. Only subscribing to the
specific events you plan on handling is useful for limiting the number of HTTP requests to
your server. You can change the list of subscribed events through the UI anytime.

By default, webhooks are only subscribed to all events. The available events are:

Name Description
all Any time any event is triggered (Wildcard Event).
publish Content of the book has been updated.
thread Any time a Discussion is opened, closed, or reopened.
thread_comment Any time a Discussion or Pull Request is commented on.

Delivery headers

HTTP requests made to your webhook’s configured URL endpoint will contain several
special headers:

Header Description
X-GitBook-Event Name of the event that triggered this delivery.
X-GitBook- HMAC hex digest of the payload, using the hook’s secret as the key
Signature (if configured).
X-GitBook-
Delivery Unique ID for this delivery.

Also, the User-Agent for the requests will have the prefix GitBook/ .

Example delivery

23
Webhooks

POST /payload HTTP/1.1

Host: localhost:4567
X-GitBook-Delivery: 72d3162e81ab4c9367dc0958
X-GitBook-Event: publish
X-GitBook-Signature: sha1=6adfb183a4a2c94a2f92dab5ade762a47889a5a1
User-Agent: GitBook/10.2.0
Content-Type: application/json
Content-Length: 6615

{
"payload": {
...
}
}

24
Overview

Authors
The Authors API let you access details of users and organizations.

Get a single author


This method returns the details about a specific author.

See Format for details about the output.

GET /authors/:username

List user organizations


This paginated method list public organization memberships for the specified user.

GET /authors/:username/orgs

25
Topics

Topics

List topics
List all topics in GitBook sorted by the count of books.

GET /topics

Parameters

Name Type Description


q string The search keywords, as well as any qualifiers.

Response

{
"list": [
{
"id": "programming",
"name": "Programming",
"books": 320
}
...
],
"total": 76,
"limit": 10,
"page": 0
}

Get a single topic

GET /topic/:id

26

You might also like