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

Via Username and Password To use Basic Authentication with the GitBook API.) Alternatively.APIOptions{}) } Authentication While the API provides multiple methods for authentication. (cURL will prompt you to enter the password. Third party applications that rely on GitBook for authentication should not ask for or collect GitBook credentials. Calls made over plain HTTP will fail. we strongly recommend using OAuth for production applications. This is to prevent the accidental leakage of private books to unauthorized users. 3 . simply send the username and password associated with the account.Introduction $ go get github. the following command would authenticate you if you replace with your GitBook username. if you’re accessing the API via cURL. All API requests must be made over HTTPS. The API supports Basic Authentication as defined in RFC2617 with a few slight differences. The other methods provided are intended to be used for scripts or testing (i. cases where full OAuth would be overkill).NewAPI(gitbook. Requests that require authentication will return 404 Not Found . in some places. Instead. For example.e. you can use personal access tokens or OAuth tokens instead of your password. instead of 403 Forbidden ..com/GitbookIO/go-gitbook-api" ) func main() { api := gitbook.com/GitbookIO/go-gitbook-api Initialize a client: package main import ( "fmt" "github. they should use the OAuth web flow.

gitbook. $ curl -H "Authorization: token OAUTH-TOKEN" https://api.NewAPI(gitbook. Via OAuth Tokens const client = new GitBook({ token: 'oauth token' }). Via Username and Password api := gitbook. }) Via OAuth Tokens api := gitbook.NewAPI(gitbook. 4 .APIOptions{ Username: "username".com/account Via OAuth Tokens The access token allows you to make requests to the API on a behalf of a user.APIOptions{ Token: "token" }) Errors GitBook uses conventional HTTP response codes to indicate the success or failure of an API request.com/account Via Username and Password const client = new GitBook({ username: 'MyUsername'.gitbook. token: 'password' }). Password: "password".Introduction $ curl -u <username>:<password or token> https://api.

). err := api.g. Example Response { "error": "A human-readable message providing more details about the error. a required parameter was omitted.Introduction In general. Not all errors map cleanly onto HTTP response codes. For some resources. 400 - Bad The request was unacceptable.then(function(result) { }. and codes in the 5xx range indicate an error with Stripe's servers (these are rare).Get("gitbookio/javascript") Pagination Requests that return multiple items will be paginated to 50 items by default. The status code can be access using the code property of the error: err. HTTP status code summary Status Description 200 - OK Everything worked as expected.books() . you can also set a custom page size up to 100 with the ?limit . All API calls return both the result and the error: book.code .Book. often due to missing a required Request parameter. a charge failed. function(err) { }). codes in the 2xx range indicate success. however. codes in the 4xx range indicate an error that failed given the information provided (e. client. 404 - Not Found The requested resource doesn't exist. etc. You can specify further pages with the ?page parameter. 5 ..". "code": 400 } All API calls return promises.

total: 0 } Paginated methods return a Page object. page. // Fetch next page return page. }.Introduction Paginated results will be returned with information about the page context.NewAPI(gitbook.total: Number is count of all elements. function(err) { // Error occured }).log('Total:'.. Most methods require an authentication when using an enterprise instance.com/api/books/all const client = new GitBook({ host: 'http://gitbook.total).list: Array<Mixed> contains the items of current page.length).next(). page. $ curl https://gitbook/myenterprise. Calling page..APIOptions{ Host: "http://gitbook.list. api := gitbook. client.com/api/" }) 6 . page.mycompany. console.log('In this page:'. limit: 50.mycompany. page. ].prev() will fetch the next/previous page and return a promise with a new Page object.books() .then(function(page) { console.com' }). { list: [ . page: 0. Enterprise All API endpoints are prefixed with the following URL: http(s)://hostname/api/ .next() or page.

7 .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.

gitbook. If the states don't match. Web Application Flow This is a description of the OAuth2 flow from 3rd party web sites. currently only valid value is code 2. 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. the request has been created by a third party and the 8 . this dialog will ask user to grant access to your application. GitBook redirects back to your site If the user accepts your request. All developers need to register their application before getting started.com/oauth/authorize Parameter Type Description client_id string Required. 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. Redirect users to request GitBook access The first step is to redirect the user to the authorization dialog. A registered OAuth application is assigned a unique Client ID and Client Secret.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. response_type string Required. GET https://api. redirect_uri string Required. and can be revoked by users at any time. The Client Secret should not be shared. 1. This is preferred over Basic Authentication because tokens can be limited to specific types of data. Type of response expected. The URL in your application where users will be sent after authorization. The client ID you received from GitBook when you registered.

client_secret string Required. The client ID you received from GitBook when you registered.com/oauth/access_token Parameters Name Type Description client_id string Required. The code you received as a response to Step 1. code string Required.OAuth process should be aborted. the response will take the following form: access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer access_token can also be returned as JSON. The client secret you received from GitBook when you registered. You can exchange this code for an access token. POST https://api. 3.gitbook.gitbook.com/account 9 . grant_type string Required. 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. in cUrl you can set the Authorization header like this: $ curl -H "Authorization: Bearer OAUTH-TOKEN" https://api. authorization_code to exchange an oauth code Response By default. Include it in the Authorization header Authorization: Bearer OAUTH-TOKEN For example.

This includes books owned by the authenticated user. 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.Overview Books List your books List books that are accessible to the authenticated user. GET /books Parameters Name Type Description page number Index of current page List author books List public books for the specified user/organization. and books that the authenticated user has access to through an organization membership. books where the authenticated user is a collaborator. in the order that they were created. GET /books/all Parameters 10 .

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.Overview Name Type Description page number Index of current page Create a book Create a new book for the specified author. "title": "My Book" } 11 . GET /book/:username/:name Example Response { "id": "johndoe/mybook".

unique: 10. 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 . GET /book/:author/:book/traffic Response { views: 100. mobi: 1 } } Get visits per countries This method returns the count of visits per countries. Get summary This methods returns a summary of traffic statistics.Traffic Traffic The Traffic API lets you fetch statistics about views and downloads. downloads: { pdf: 3. epub: 3.

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 . Each access key can be converted to an unique read-only access url.Access Keys Access Keys Access keys allow non-collaborator to access a private book. 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.

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

List branches This method returns the list of active branches in the book's git repository. GET /book/:author/:book/versions/tags List languages For multilingual book. etc). The Versions plugins can be enabled to list versions of the book in the sidebar. See Format for details about the version object format. this method returns the list of languages. The current is set to true when its represent the main version (current branch. current language. GET /book/:author/:book/versions/languages Version Format Each version (Tag. Branch or Language) is represented by a version object. 15 .Versions Versions The versions API can be used to list available versions of a book (branches. GET /book/:author/:book/versions/branches List tags This method returns the list of Git tags in the book's git repository. tags or commits). The Contents API can then be used to fetch files for a specific version.

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

See the Versions API for details on how to list versions. Branch name or Tag file string Required: Path of the file to retrieve (with . It can be used to retrieve contents for a specific Git tag. Get contents This method returns the contents of a page in a book.json extension) Get contents for a specific version The Contents API can also serve other versions than the main one. 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 . branch or commit. It can be used to programmatically integrate your documentation content into your application. All pages are ending with a .json extension) 17 .json extension.Contents Contents These API methods let you retrieve the contents of pages within a book. GET /book/:author/:book/contents/v/:version/:file Parameters Name Type Description version string Required: SHA.

gitbook.application/vnd.json" Example 18 . }..v3 : curl -H "Accept: application/json.Contents File format The GitBook Contents API serve content of JSON build from the GitBook Toolchain. Example { "progress": { .format.0. "sections": [ { "type": "normal". Contents API can output all books with this format when the client accepts application/vnd. The format may vary between GitBook version being used to generate your book.format.0 .v3" \ "https://api. It is a modern and easier format to work with.. but soon to be deprecated.gitbook. "langs": [] } Version 3 This format is generated since GitBook >=3.com/book/you/your-book/contents/README. "content": "<h1>My Awesome book</h1>" } ].gitbook. Version 2 Currently the default version.

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

Discussions Discussions The Discussion API lets you create. List discussions for a book List all opened discussions in a book. default is open filename string Optional file to filter discussions Create a new discussion Any user with read access can create a discussion. closed or all ). list and comment discussions in books. all or closed discussions can be listed using the state parameter. Title of the discussion. GET /book/:author/:book/discussions Parameters Name Type Description state string State of the discussions ( open . body string The contents of the discussion. Close a list of discussions Mark a list of discussions as closed for a book. POST /book/:author/:book/discussions Parameters Name Type Description title string Required. 20 . This method is paginated.

An array containing the threads numbers to mark as open. An array containing the threads numbers to mark as list array closed. 21 . 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.Discussions POST /book/:author/:book/discussions/close Parameters Name Type Description Required.

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. Example of Integrations Slack Notifications List webhooks List webhooks in a book requires admin" permission.Webhooks Webhooks Webhooks allow you to build or set up integrations which subscribe to certain events on GitBook. 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 .com. When one of those events is triggered. we’ll send a HTTP POST payload to the webhook’s configured URL.

Example delivery 23 . X-GitBook- Delivery Unique ID for this delivery. By default. webhooks are only subscribed to all events. You can even opt-in to all current and future events. the User-Agent for the requests will have the prefix GitBook/ . thread_comment Any time a Discussion or Pull Request is commented on. The available events are: Name Description all Any time any event is triggered (Wildcard Event). or reopened. HMAC hex digest of the payload. Also. you can choose which events you would like to receive payloads for. using the hook’s secret as the key Signature (if configured). closed. Only subscribing to the specific events you plan on handling is useful for limiting the number of HTTP requests to your server. publish Content of the book has been updated. 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. You can change the list of subscribed events through the UI anytime.Webhooks Events When configuring a webhook. thread Any time a Discussion is opened. X-GitBook.

Webhooks POST /payload HTTP/1. } } 24 .0 Content-Type: application/json Content-Length: 6615 { "payload": { .1 Host: localhost:4567 X-GitBook-Delivery: 72d3162e81ab4c9367dc0958 X-GitBook-Event: publish X-GitBook-Signature: sha1=6adfb183a4a2c94a2f92dab5ade762a47889a5a1 User-Agent: GitBook/10..2..

Overview Authors The Authors API let you access details of users and organizations. GET /authors/:username/orgs 25 . 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.

Response { "list": [ { "id": "programming".. "limit": 10. "books": 320 } . "total": 76.Topics Topics List topics List all topics in GitBook sorted by the count of books. ]. as well as any qualifiers. "name": "Programming". "page": 0 } Get a single topic GET /topic/:id 26 . GET /topics Parameters Name Type Description q string The search keywords..