Api Guide
Api Guide
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
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
{ ... }
Initialize a client:
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.
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
The access token allows you to make requests to the API on a behalf of a user.
api := gitbook.NewAPI(gitbook.APIOptions{
Username: "username",
Password: "password",
})
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.
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
}
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:
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
}
Calling page.next() or page.prev() will fetch the next/previous page and return a promise
with a new Page object.
client.books()
.then(function(page) {
console.log('Total:', page.total);
console.log('In this page:', page.list.length);
Enterprise
All API endpoints are prefixed with the following URL: http(s)://hostname/api/ .
$ curl https://gitbook/myenterprise.com/api/books/all
api := gitbook.NewAPI(gitbook.APIOptions{
Host: "http://gitbook.mycompany.com/api/"
})
6
Introduction
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.
GET https://api.gitbook.com/oauth/authorize
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
8
OAuth
POST https://api.gitbook.com/oauth/access_token
Parameters
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
access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer
For example, in cUrl you can set the Authorization header like this:
9
Overview
Books
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
GET /authors/:username/books
Parameters
GET /books/all
Parameters
10
Overview
Create a book
Create a new book for the specified author.
POST /books
Parameters
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 /book/:author/:book/traffic/countries
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.
POST /book/:author/:book/keys
Parameters
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.
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.
Get contents
This method returns the contents of a page in a book. All pages are ending with a .json
extension.
GET /book/:author/:book/contents/:file
Parameters
It can be used to retrieve contents for a specific Git tag, branch or commit.
GET /book/:author/:book/contents/v/:version/:file
Parameters
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 :
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.
GET /book/:author/:book/discussions
Parameters
POST /book/:author/:book/discussions
Parameters
20
Discussions
POST /book/:author/:book/discussions/close
Parameters
POST /book/:author/:book/discussions/open
Parameters
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 /book/:author/:book/webhooks/:id/deliveries
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
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 /authors/:username
GET /authors/:username/orgs
25
Topics
Topics
List topics
List all topics in GitBook sorted by the count of books.
GET /topics
Parameters
Response
{
"list": [
{
"id": "programming",
"name": "Programming",
"books": 320
}
...
],
"total": 76,
"limit": 10,
"page": 0
}
GET /topic/:id
26