Introduction

Obsolete documentation

For the latest Couchbase Mobile documentation, visit the Couchbase Mobile developer portal.

This reference manual provides information for developers who want to use the Couchbase Lite REST API to develop apps for mobile devices. To get an overview of Couchbase Lite, read the Couchbase Lite Concepts Guide.

Work In Progress

The Couchbase Lite REST API Reference is a work in progress. All the APIs that Couchbase Lite supports are listed in this document, but some of them are not documented yet.

If you want to help fill in the gaps, please feel free to fork the official Couchbase documentation repository on GitHub, make documentation updates in your fork, and then send a pull request.

If you have questions about the REST API, please ask them on the Couchbase Mobile mailing list.

Resource Groups

The REST API enables you to interact with all of your database resources. The Couchbase Lite REST API is divided into the following logical groups of resources:

Resource Group Description
Database APIs that operate on the whole database
Document APIs that operate on individual documents
Local Document APIs that operate on local documents that are not replicated
Design Document APIs that operate on design documents (for views)
Server APIs that operate on the database host server
Authentication APIs that operate on session and authentication data

HTTP requests and responses

The Couchbase Lite REST API uses the Hypertext Transfer Protocol (HTTP). Each API is an HTTP request. For each HTTP request that you send, you receive an HTTP response. HTTP requests consist of a request line, header lines, and a message body. HTTP responses consist of a status line, header lines, and a message body.

The message body for both the HTTP requests and HTTP responses is formatted as a JSON document. To learn more about JSON, check out JSON.org or the W3Schools JSON Tutorial.

The examples in this document are shown in the basic HTTP format.

The following table lists some of the status codes returned by Couchbase Lite:

HTTP Status Code Returned String
200 OK
201 Created
202 Accepted
400 Bad data encoding
400 bad_request
400 Invalid attachment
400 Invalid database/document/revision ID
400 Invalid JSON
400 Invalid parameter in HTTP query or JSON body
401 unauthorized
403 forbidden
404 Attachment not found
404 deleted
404 not_found
406 not_acceptable
409 conflict
412 file_exists
415 bad_content_type
500 Application callback block failed
500 Attachment store error
500 Database error!
500 Database locked
500 Internal error
500 Invalid data in database
502 Invalid response from remote replication server

Notation Conventions

Within the paths of the URIs presented in this reference manual:

  • Path segments that start with an underscore character are static components of the URI that you use exactly as given. For example: _replicate.

  • Path segments that are not preceded by an underscore character represent variables that you replace with your own value. These variables are usually enclosed in brackets as a reminder. For example: {db} or <db>.

For example, suppose you have a database named cookbook. In the database, the IDs for recipes start with the string “recipe” and IDs for design documents start with the string “ddoc”. The following table shows examples of values you might use for the URI path in the request that you send to the database:

Path Sample value
/<db> /cookbook
/<db>/_changes /cookbook/_changes
/<db>/<doc> /cookbook/recipe123
/<db>/_design/<design-doc> /cookbook/_design/ddoc456
/_replicate /_replicate

Database Resources

Database resources provide an interface to an entire database. The following table lists the database resources:

HTTP Method URI pattern Description
PUT /{db} Creates a new database
GET /{db} Retrieves information about a database
DELETE /{db} Deletes a database
GET /{db}/_all_docs Retrieve the built-in view of all documents in the database
POST /{db}/_all_docs Retrieves specified documents from the built-in view of all documents in the database
POST /{db}/_bulk_docs Inserts multiple documents into the database in a single request
GET /{db}/_changes Returns changes for the database
POST /{db}/_compact Starts a compaction for the database
POST /{db}/_purge Purges some historical documents from the database history
POST /{db}/_temp_view Executes a given view function for all documents and returns the result

In the URI patterns, {db} represents the name of the database on which you want to operate.

PUT /{db}

This request creates a new database. The database name must begin with a lowercase letter. The legal characters for the database name are: lowercase letters [a-z], digits [0-9], and special characters [$_()+-/].

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

  • 201 Created – Database created successfully
  • 400 Bad Request – Invalid database name
  • 401 Unauthorized – Administrator privileges required
  • 412 Precondition Failed – Database already exists

Response headers

  • Content-Type—The value can be:
    • application/json
    • multipart/mixed
    • text/plain; charset=utf-8
  • Location—URI of the new database

Message body

The response contains a JSON document that contains some of the following objects:

Name Type Description
error String Error message
ok Boolean Indicates whether the operation was successful
status Integer HTTP error code

Example

The following example creates a new database named cookbook.

Request

PUT /cookbook HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 201 Created
Server: CouchbaseLite 1.485
Location: http://localhost:59840/cookbook
Accept-Ranges: bytes
Content-Length: 18
Content-Type: application/json
Date: Sun, 08 Dec 2013 20:17:16 GMT

{
  "ok" : true
}

The following example shows the error you receive when trying to create a database that already exists:

Request

PUT /cookbook HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 412 Precondition Failed
Transfer-Encoding: chunked
Accept-Ranges: bytes
Content-Type: application/json
Server: CouchbaseLite 1.485
Date: Mon, 09 Dec 2013 19:26:09 GMT

{
  "status" : 412,
  "error" : "file_exists"
}

The following example show the error you receive when you specify an invalid database name.

Request

PUT /ACookbook HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 400 Bad Request
Transfer-Encoding: chunked
Accept-Ranges: bytes
Content-Type: application/json
Server: CouchbaseLite 1.486
Date: Thu, 12 Dec 2013 19:42:12 GMT

{
  "status" : 400,
  "error" : "Invalid database\/document\/revision ID"
}

GET /{db}

This request retrieves information about a database.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

  • 200 OK – Request completed successfully
  • 404 Not Found – Requested database not found

Response headers

This response uses only standard HTTP headers.

Message body

The message body is a JSON document that contains the following objects:

Name Type Description
committed_update_seq Integer Number of committed updates to the database
db_name String Name of the database
db_uuid String Database identifier
disk_format_version Integer Database schema version
disk_size Integer Total amount of data stored on the disk. Units: bytes
doc_count Integer Number of documents in the database
instance_start_time Integer Date and time the database was opened. Units: microseconds since the epoch (1 January 1970)
purge_seq Integer Returns 0.
update_seq Integer Number of updates to the database

Example

The following example retrieves information about a database named beer-db.

Request

GET /beer-db HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Server: CouchbaseLite 1.485
Content-Type: application/json
Accept-Ranges: bytes
Content-Length: 281
Cache-Control: must-revalidate
Date: Fri, 06 Dec 2013 22:31:17 GMT

{
  "instance_start_time" : 1386620242527997,
  "committed_update_seq" : 25800,
  "disk_size" : 15360000,
  "purge_seq" : 0,
  "db_uuid" : "65FB16DF-FFD7-4514-9E8D-B734B066D28D",
  "doc_count" : 5048,
  "db_name" : "beer-db",
  "update_seq" : 25800,
  "disk_format_version" : 11
}

The following example shows the response returned when you request information about a database that does not exist on the server. The example requests information about a database named cookbook, which does not exist on the server.

Request

GET /cookbook HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 404 Not Found
Transfer-Encoding: chunked
Accept-Ranges: bytes
Content-Type: application/json
Server: CouchbaseLite 1.485
Date: Sun, 08 Dec 2013 20:16:50 GMT

{
  "status" : 404,
  "error" : "not_found"
}

DELETE /{db}

This request deletes a database, including all documents and attachments.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

  • 200 OK – Database removed successfully
  • 400 Bad Request – Invalid database name
  • 401 Unauthorized – CouchDB Server Administrator privileges required
  • 404 Not Found – Database doesn’t exist

Response headers

This response uses only standard HTTP headers.

Message body

The response contains a JSON document that contains some of the following objects:

Name Type Description
error String Error message
ok Boolean Indicates whether the operation was successful
status Integer HTTP error code

Example

Request

DELETE /genealogy HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Content-Type: application/json
Accept-Ranges: bytes
Content-Length: 18
Server: CouchbaseLite 1.485
Date: Mon, 09 Dec 2013 04:24:05 GMT

{
  "ok" : true
}

GET /{db}/_all_docs

This request returns a built-in view of all documents in the database.

Request

Request headers

This request does not have any required headers.

Query parameters

| Name | Type | Description | Default
| —— | —— | —— | —— |
| conflicts | Boolean | Include conflict information in the response. This parameter is ignored if the include_docs parameter is false. | false
| descending | Boolean | Return documents in descending order | false
| endkey | string | If this parameter is provided, stop returning records when the specified key is reached. | none
| end_key | string | Alias for the endkey parameter | none | endkey_docid | string | If this parameter is provided, stop returning records when the specified document identifier is reached | none
| end_key_doc_id | string | Alias for the endkey_docid parameter | none
| include_docs | Boolean | Indicates whether to include the full content of the documents in the response | false
| inclusive_end | Boolean | Indicates whether the specified end key should be included in the result | true
| key | string | If this parameter is provided, return only document that match the specified key. | none
| limit | integer | If this parameter is provided, return only the specified number of documents | none
| skip | integer | If this parameter is provided, skip the specified number of documents before starting to return results | 0
| stale | string | Allow the results from a stale view to be used, without triggering a rebuild of all views within the encompassing design document. Valid values: ok and update_after. | none
| startkey | string | If this parameter is provided, return documents starting with the specified key. | none
| start_key | string | Alias for startkey param | none
| startkey_docid | string | If this parameter is provided, return documents starting with the specified document identifier. | none
| update_seq | Boolean | Indicates whether to include update_seq in the response | false

Message body

This request does not use a message body.

Response

Status codes

  • 200 OK – Request completed successfully
  • 400 — Invalid database
  • 404 — Database not found

Response headers

  • Content-Type—The value can be:

    • application/json
    • text/plain; charset=utf-8
  • ETag—Response signature

Message body

The message body is a JSON document that contains the following objects:

Name Type Description
offset integer Starting index of the returned rows.
rows array Array of row objects. Each row contains the following objects: id, key, and value. The value object contains the revision identifier in a rev object.
total_rows integer Number of documents in the database.This number is not the number of rows returned.
update_seq integer Sequence identifier of the underlying database that the view reflects

Example

The following request retrieves all documents from a database named cookbook.

Request

GET /cookbook/_all_docs HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: must-revalidate
Content-Type: application/json
Date: Fri, 13 Dec 2013 02:42:23 GMT
Etag: "3"
Server: CouchbaseLite 1.486

{
  "offset" : 0,
  "rows" : [
    {
      "key" : "209BB170-C1E0-473E-B3C4-A4533ACA3CDD",
      "value" : {
        "rev" : "1-ed0ebedd2fab89227b352f6455a08010"
      },
      "id" : "209BB170-C1E0-473E-B3C4-A4533ACA3CDD"
    },
    {
      "key" : "A329CFEC-29E8-4DCF-BB49-EFCE8CD6B212",
      "value" : {
        "rev" : "1-afbf905396a144446feb2431c37065f9"
      },
      "id" : "A329CFEC-29E8-4DCF-BB49-EFCE8CD6B212"
    },
    {
      "key" : "LemonChicken",
      "value" : {
        "rev" : "1-78abf9a6508671ba8338e4ef6daa910a"
      },
      "id" : "LemonChicken"
    }
  ],
  "total_rows" : 3
}

POST /{db}/_all_docs

This request retrieves specified documents from the database.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

The message body is a JSON document that contains the following object:

Name Type Description
keys array List of identifiers of the documents to retrieve

Response

Status codes

  • 200 OK – Request completed successfully

Response headers

  • Content-Type—The value can be:
    • application/json
    • text/plain; charset=utf-8

Message body

The message body is a JSON document that contains the following objects:

Name Type Description
offset integer Starting index of the returned rows.
rows array Array of row objects. Each row contains the following objects: id, key, and value. The value object contains the revision identifier in a rev object.
total_rows integer Number of documents in the database.This number is not the number of rows returned.

Example

The following request retrieves specified documents from the database named cookbook.

Request

POST /cookbook/_all_docs
Host: localhost:59840

{
    "keys": [
        "LemonChicken",
        "209BB170-C1E0-473E-B3C4-A4533ACA3CDD"
    ]
}

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 406
Content-Type: application/json
    Date: Sun, 15 Dec 2013 21:38:59 GMT
    Server: CouchbaseLite 1.486

{
  "offset" : 0,
  "rows" : [
    {
      "key" : "LemonChicken",
      "value" : {
        "rev" : "3-6210945863a15ee7eff1e540133d19da"
      },
      "id" : "LemonChicken"
    },
    {
      "key" : "209BB170-C1E0-473E-B3C4-A4533ACA3CDD",
      "value" : {
        "rev" : "1-ed0ebedd2fab89227b352f6455a08010"
      },
      "id" : "209BB170-C1E0-473E-B3C4-A4533ACA3CDD"
    }
  ],
  "total_rows" : 2
}

POST /{db}/_bulk_docs

This request enables you to add, update, or delete multiple documents to a database in a single request.

To new documents, you can either specify the ID or let the software create an ID.

To update existing documents, you must provide the document ID, revision identifier, and new document values.

To delete existing documents you must provide the document ID, revision identifier, and a deletion flag (_deleted).

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

The message body is a JSON document that contains the following objects:

Name Type Description Default
all_or_nothing Boolean Optional. Indicates whether to use all-or-nothing semantics for the database commit mode false
docs array List containing new or updated documents. The docs object can contain _id,rev,deleted`, and values for new and updated documents. none
new_edits Boolean Optional. Indicates whether to assign new revision identifiers to new edits. true

Response

Status codes

  • 201 Created – Document(s) have been created or updated
  • 400 Bad Request – The request provided invalid JSON data
  • 417 Expectation Failed – Occurs when all_or_nothing option set as true and at least one document was rejected by validation function
  • 500 Internal Server Error – Malformed data provided, while it’s still valid JSON

Response headers

This response uses only standard HTTP headers.

Message body

The response message body is a JSON documental that contains an array. Each array element contains the following objects:

Name Type Description
id String Document identifier
ok Boolean Indicates whether the operation was successful
rev String revision identifier

Example

Sample request:

The following example adds a new document with the identifier PeachCobbler, modifies the document with the identifier LemonChicken, and deletes the document with the identifier CinnamonCookies.

POST /cookbook/_bulk_docs
Host: localhost:59840

{
    "docs": [
        {
            "_id": "PeachCobbler",
            "description": "Juicy peaches topped with pie crust",
            "title": "Peach Cobbler"
        },
        {
            "_id": "LemonChicken",
            "_rev": "3-6210945863a15ee7eff1e540133d19da",
            "description": "Chinese lemon chicken",
            "serving-suggestion": "Serve with plain jasmine rice.",
            "servings": 4,
            "title": "Lemon Chicken"
        },
        {
            "_deleted": true,
            "_id": "CinnamonCookies",
            "_rev": "1-2c25302ccf3d70d3461f28b8df9fafd0"
        }
    ]
}

Response

HTTP/1.1 201 Created
Accept-Ranges: bytes
Content-Type: application/json
Date: Mon, 16 Dec 2013 17:01:56 GMT
Server: CouchbaseLite 1.486
Transfer-Encoding: chunked

[
  {
    "id" : "PeachCobbler",
    "rev" : "1-eb8eafda1b60edecef37f7daa02baa9e",
    "ok" : true
  },
  {
    "id" : "LemonChicken",
    "rev" : "4-51737756120a34de2d4981ab0f02c5a5",
    "ok" : true
  },
{
    "id" : "CinnamonCookies",
    "rev" : "2-28df61cdda892ad3dd4339f2bce18463",
    "ok" : true
  }
]

GET /{db}/_changes

This request retrieves a sorted list of changes made to documents in the database, in time order of application, can be obtained from the database’s _changes resource. Only the most recent change for a given document is guaranteed to be provided. For example if a document has had fields added, and then deleted, an API client checking for changes will not necessarily receive the intermediate state of added documents.

This request can be used to listen for update and modifications to the database for post processing or synchronization. A continuously connected changes feed is a reasonable approach for generating a real-time log for most applications.

Request

Request headers

This request does not have any required headers.

Query parameters

Name Type Description Default
attachments Boolean Indicates whether to include the Base64-encoded content of attachments in the documents that are included when include_docs is true. this parameter is ignored when include_docs is false. false
att_encoding_info Boolean Indicates whether to include encoding information in attachment stubs when include_docs is true. false
conflicts Boolean Includes conflicts information in response. Ignored if include_docs isn’t true. false
descending Boolean Return the change results in descending sequence order (most recent change first). false
doc_ids array List of document IDs to filter the changes feed as valid JSON array. Used with _doc_ids filter. none
feed string Specifies type of change feed. Valid values: normal, continuous, eventsource, longpoll normal
filter string Reference to a filter function from a design document that will filter whole stream emitting only filtered events. none
heartbeat integer Period in milliseconds after which an empty line is sent in the results. Only applicable for longpoll or continuous feeds. Overrides any timeout to keep the feed alive indefinitely. 60000
include_docs Boolean Indicates whether to include the associated document with each result. f there are conflicts, only the winning revision is returned. false
last-event-id integer Alias for the Last-Event-ID header. none
limit integer Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1. none
since integer Starts the results from the change immediately after the given sequence number. The value can be an integer or a row value. 0
style string Number of revisions to return in the changes array. main_only returns the current winning revision, all_docs returns all leaf revisions including conflicts and deleted former conflicts. main_only
timeout integer Maximum period in milliseconds to wait for a change before the response is sent, even if there are no results. Only applicable for longpoll or continuous feeds. The default value is specified by the httpd/changes_timeout configuration option. If not specified, the default maximum timeout is used to prevent undetected dead connections. 60000
view string Name of a view function to use as a filter none

Message body

Response

Status codes

  • 200 OK – Request completed successfully
  • 400 Bad Request – Bad request

Response headers

This response uses only standard HTTP headers.

Message body

The response message body contains a JSON document with the following objects;

Name Type Description
last_seq integer Last change sequence number
results array List of changes to the database. See the following table for a list of fields in this object.

The results array contains the following objects:

Name Type Description
changes array List of the document’s leafs. Each leaf object contains one field, rev.
id string Document identifier
seq Update sequence number

Example

The following example requests the changes to the database named cookbook and specifies that only two rows be included in the response:

Request

GET /cookbook/_changes?limit=2 HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: must-revalidate
Content-Type: application/json
Date: Mon, 16 Dec 2013 21:09:35 GMT
Etag: "13"
Server: CouchbaseLite 1.486
Transfer-Encoding: chunked

{
  "results" : [
    {
      "seq" : 1,
      "id" : "A329CFEC-29E8-4DCF-BB49-EFCE8CD6B212",
      "changes" : [
        {
          "rev" : "1-afbf905396a144446feb2431c37065f9"
        }
      ]
    },
    {
      "seq" : 2,
      "id" : "209BB170-C1E0-473E-B3C4-A4533ACA3CDD",
      "changes" : [
        {
          "rev" : "1-ed0ebedd2fab89227b352f6455a08010"
        }
      ]
    }
  ],
  "last_seq" : 2
}

POST /{db}/_compact

This request compacts the database. Compaction compresses the disk database file by performing the following operations:

  • Writes a new, optimized version of the database file. Unused sections are removed from the new version during write. Because a new file is temporarily created for this purpose, up to twice the current storage space of the specified database is required for the compaction routine to complete.

  • Removes old revisions of documents from the database, up to the per-database limit specified by the _revs_limit database parameter.

The compaction process runs as a background process.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

  • 202 Accepted – Compaction request has been accepted
  • 400 Bad Request – Invalid database name
  • 401 Unauthorized – Administrator privileges required
  • 415 Unsupported Media Type – Bad Content-Type value

Response headers

This response uses only standard HTTP headers.

Message body

The response contains a JSON document that contains some of the following objects:

Name Type Description
error String Error message
ok Boolean Indicates whether the operation was successful
status Integer HTTP error code

Example

The following example requests the database named cookbook to be compacted.

Request

POST /cookbook/_compact HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 202 Accepted
Accept-Ranges: bytes
Content-Length: 18
Content-Type: application/json
Date: Mon, 16 Dec 2013 17:22:34 GMT
Server: CouchbaseLite 1.486

{
  "ok" : true
}

POST /{db}/_purge

This request permanently removes references to specified deleted documents from the database.

Deleting a document does not remove the document from the database— that just marks it as deleted and creates a new revision to ensure that deleted documents can be replicated to other databases as having been deleted. This also means that you can check the status of a document and determine that the document has been deleted by its absence.

Purging documents does not remove the space used by them on disk. To reclaim disk space, run a database compact (see /db/compact) or compact views (see /db/compact/design-doc) request.

Warning

Avoid using POST/db/_purge requests because they can have unanticipated side effects.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

The request message body is a JSON document that contains an object in which the key is a document identifier and the value is a list of the revision identifiers.

Name Type Description
not applicable object An object that represents the document to be purged. The key is the document identifier and the value is an array that contains identifiers of the revisions to be purged.

Response

Status codes

  • 200 OK – Request completed successfully
  • 400 Bad Request – Invalid database name or JSON payload
  • 415 Unsupported Media Type – Bad Content-Type value

Response headers

This response uses only standard HTTP headers.

Message body

The response message body contains the following objects:

Name Type Description
purge_seq integer Purge sequence number
purged object An object that represents the purged document. The key is the document identifier and the value is an array that contains identifiers of the purged revisions.

Example

Request

POST /cookbook/_purge HTTP/1.1

Response

POST /{db}/_temp_view

Executes a temporary view function for all documents and returns the result.

Request

Request headers

Query parameters

Message body

Response

Status codes

Response headers

Message body

Example

Request

POST /cookbook/_temp_view

Response

Document Resources

Document resources enable you to work with individual documents in a database. The following table lists the document resources:

HTTP method URI pattern Description
POST /{db} Creates a new document in the database
PUT /{db}/{doc} Creates a new document or updates an existing document
GET /{db}/{doc} Retrieves a document
DELETE /{db}/{doc} Deletes a document
PUT /{db}/{doc}/{attachment} Adds or updates attachments for a document
GET /{db}/{doc}/{attachment} Retrieves attachments for a document
DELETE /{db}/{doc}/{attachment} Deletes attachments for a document

The following table defines the parameters used in the URI patterns:

Name Description
attachment Identifier of an attachment
db Name of the database
doc Identifier of a document

POST /{db}

This request creates a new document in the specified database. You can either specify the document ID by including the _id object in the request message body, or let the software generate an ID.

Request

Request headers

The request uses the following headers:

  • AcceptOptional—Valid values are:
    • application/json
    • text/plain
  • Content-TypeRequired—Must be application/json.

Query parameters

The request uses the following query parameter:

Name Type Description Default
batch string Stores the document in batch mode. To use, set the value to ok. none

Response

The response is a JSON document that contains the following objects:

Name Type Description
id String Document identifier
ok Boolean Indicates whether the operation was successful
rev String revision identifier

Example

The following request creates a new document in a database named cookbook.

Request

POST /cookbook HTTP/1.1
Host: localhost:59840
Content-Type: application/json

{
    "description": "Chicken topped with mozzarella and parmesan cheese",
    "servings": 4,
    "title": "Chicken Parmagiana"
}

Response

HTTP/1.1 201 Created
Accept-Ranges: bytes
Content-Length: 115
Content-Type: application/json
Date: Fri, 13 Dec 2013 01:57:54 GMT
Etag: "1-ed0ebedd2fab89227b352f6455a08010"
Location: http://localhost:59840/cookbook/209BB170-C1E0-473E-B3C4-A4533ACA3CDD
Server: CouchbaseLite 1.486

{
  "id" : "209BB170-C1E0-473E-B3C4-A4533ACA3CDD",
  "rev" : "1-ed0ebedd2fab89227b352f6455a08010",
  "ok" : true
}

The following example creates a new document with the identifier LemonChicken in a database named cookbook.

Request

POST /cookbook
Host: localhost:59840
Content-Type: application/json

{
    "_id": "LemonChicken",
    "description": "Chinese lemon chicken",
    "servings": 4,
    "title": "Lemon Chicken"
}

Response

HTTP/1.1 201 Created
Accept-Ranges: bytes
Content-Type: application/json
Date: Fri, 13 Dec 2013 02:31:46 GMT
Etag: "1-78abf9a6508671ba8338e4ef6daa910a"
Location: http://localhost:59840/cookbook/LemonChicken
Server: CouchbaseLite 1.486
Transfer-Encoding: chunked

{
  "id" : "LemonChicken",
  "rev" : "1-78abf9a6508671ba8338e4ef6daa910a",
  "ok" : true
}

PUT /{db}/{doc}

This request creates a new document or creates a new revision of an existing document. It enables you to specify the identifier for a new document rather than letting the software create an identifier. If you want to create a new document and let the software create an identifier, use the POST /db request.

If the document specified by doc does not exist, a new document is created and assigned the identifier specified in doc. If the document already exists, the document is updated with the JSON document in the message body and given a new revision.

Request

Request headers

  • Acceptoptional—Valid values are:

    • application/json
    • text/plain
  • Content-TypeRequired—Must be application/json.

  • If-MatchRequired for document updates f the rev query parameter is not supplied —Revision identifier of the requested document.

Query parameters

Name Type Description Default
batch string Stores the document in batch mode. To use, set the value to ok. none
rev string Revision identifier none

Response

Status codes

  • 201 Created – Document created and stored on disk
  • 202 Accepted – Document data accepted, but not yet stored on disk
  • 400 Bad Request – Invalid request body or parameters
  • 401 Unauthorized – Write privileges required
  • 404 Not Found – Specified database or document ID doesn’t exist
  • 409 Conflict – Document with the specified ID already exists or specified revision is not latest for target document

Response headers

  • Content-Type—The value can be:

    • application/json
    • text/plain; charset=utf-8
  • ETag—Revision identifier enclosed in double quotes

Message body

The response is a JSON document that contains the following objects:

Name Type Description
id String Document identifier
ok Boolean Indicates whether the operation was successful
rev String revision identifier

Example

The following example creates a new document with the identifier ButterChicken in a database named cookbook.

Request

PUT /cookbook/ButterChicken HTTP/1.1
Host: localhost:59840
Content-Type: application/json

{
    "description": "A very buttery chicken dish",
    "nutrition": "500 calories",
    "servings": 4,
    "title": "Butter Chicken"
}

Response

HTTP/1.1 201 Created
Accept-Ranges: bytes
Content-Length: 92
Content-Type: application/json
Date: Fri, 13 Dec 2013 19:34:04 GMT
Etag: "1-4101356e9c47d15d4f8f7390d05dbbcf"
Location: http://localhost:59840/cookbook/ButterChicken
Server: CouchbaseLite 1.486

{
  "id" : "ButterChicken",
  "rev" : "1-4101356e9c47d15d4f8f7390d05dbbcf",
  "ok" : true
}

The following example updates the document with the identifier ButterChicken that was created in the previous example. To update an existing document, the revision identifier of the current document must be supplied in an If-Match header or a rev query parameter. This example shows how to use both methods of specifying the revision.

Request

This form of the request uses the If-Match header to supply the revision identifier:

PUT /cookbook/ButterChicken HTTP/1.1
Host: localhost:59840
Content-Type: application/json
If-Match: 1-4101356e9c47d15d4f8f7390d05dbbcf

{
    "description": "A very buttery chicken dish",
    "nutrition": "500 calories",
    "serving-suggestion": "Serve with rice and green beans.",
    "servings": 4,
    "title": "Butter Chicken"
}

To use the rev query parameter rather than the If-Match header to supply the revision identifier, structure the request like this:

PUT /cookbook/ButterChicken?rev=1-4101356e9c47d15d4f8f7390d05dbbcf HTTP/1.1
Host: localhost:59840
Content-Type: application/json

{
    "description": "A very buttery chicken dish",
    "nutrition": "500 calories",
    "serving-suggestion": "Serve with rice and green beans.",
    "servings": 4,
    "title": "Butter Chicken"
}

Response

HTTP/1.1 201 Created
Accept-Ranges: bytes
Content-Length: 92
Content-Type: application/json
Date: Fri, 13 Dec 2013 19:56:09 GMT
Etag: "2-1b76d07281d4a576130c7d8f9f621d5e"
Location: http://localhost:59840/cookbook/ButterChicken
Server: CouchbaseLite 1.486

{
  "id" : "ButterChicken",
  "rev" : "2-1b76d07281d4a576130c7d8f9f621d5e",
  "ok" : true
}

GET /{db}/{doc}

This request retrieves a document from a database.

Request

Request headers

  • Acceptoptional—Valid values are:

    • application/json
    • multipart/mixed
    • text/plain
  • If-None-Matchoptional—Document revision identifier enclosed in double quotes

Query parameters

The following query parameters are all optional.

Name Type Description Default
attachments Boolean Include attachment bodies in response false
att_encoding_info Boolean Include encoding information in attachment stubs if the attachment is compressed false
atts_since array Include attachments only since specified revisions. Does not include attachments for specified revisions none
conflicts Boolean Include information about conflicts in document false
deleted_conflicts Boolean Include information about deleted conflicted revisions false
latest Boolean Force retrieval of latest leaf revision, no matter what revision was requested false
local_seq Boolean Include last update sequence number for the document false
meta Boolean Acts same as specifying all conflicts, deleted_conflicts and open_revs query parameters false
open_revs array Retrieve documents of specified leaf revisions. You can specify the value all to return all leaf revisions none
rev string Retrieve the specified revision of the document none
revs Boolean Include a list of all known document revisions false
revs_info Boolean Include detailed information for all known document revisions false

Response

The response contains a JSON document in the message body.

Response headers

  • Content-Type—The value can be:

    • application/json
    • multipart/mixed
    • text/plain; charset=utf-8
  • ETag—Document revision identifier contained in double quotes.

  • Transfer-Encoding—This header appears when the request uses the open-revs query parameter. The value is chunked.

Message body

The message body contains the following objects in a JSON document.

Name Type Description
_id string Document identifier
_rev string revision identifier
_deleted Boolean Indicates whether the document is deleted. Appears only when the document was deleted.
_attachments object Stubs for the attachments. Appears only when the document has attachments.
_conflicts array List of revisions with conflicts. Appears only when the request uses the conflicts=true query parameter.
_deleted_conflicts array List of revisions with conflicts that were deleted. Appears only when the request uses the deleted_conflicts=true query parameter.
_local_seq integer Sequence number of the document in the database. Appears only when the request uses the local_seq=true query parameter.
_revs_info array List of objects with information about local revisions and their status. Appears only when the request uses the open_revs=true query parameter.
_revisions object List of locals revision identifiers. Appears only when the request uses the revs=true query parameter.

Example

The following example retrieves a document with the identifier beer_#17_Cream_Ale from a database named beer-db. Because the identifier contains a number sign (#) character, the identifier must be URL encoded in the URI.

Request

GET /beer-db/beer_%2317_Cream_Ale HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: must-revalidate
Content-Length: 259
Content-Type: application/json
Date: Thu, 12 Dec 2013 21:12:28 GMT
Etag: "1-431506b53aeac96a225e619cfa7bb569"
Server: CouchbaseLite 1.486

{
  "category" : "North American Lager",
  "brewery" : "Big Ridge Brewing",
  "style" : "American-Style Lager",
  "updated" : "2010-07-22 20:00:20",
  "_id" : "beer_#17_Cream_Ale",
  "_rev" : "1-431506b53aeac96a225e619cfa7bb569",
  "name" : "#17 Cream Ale"
}

DELETE /{db}/{doc}

This request deletes a document from the database. When a document is deleted, the revision number is updated so the database can track the deletion in synchronized copies.

Request

Request headers

  • Acceptoptional—Valid values are:

    • application/json
    • text/plain
  • If-MatchRequired if the rev query parameter is not supplied —Revision identifier of the requested document.

Query parameters

Name Type Description Default
batch string Stores the document in batch mode. To use, set the value to ok. none
rev string Revision identifier none

Message body

None

Response

Status codes

  • 200 OK – Document successfully removed
  • 202 Accepted – Request was accepted, but changes are not yet stored on disk
  • 400 Bad Request – Invalid request body or parameters
  • 401 Unauthorized – Write privileges required
  • 404 Not Found – Specified database or document ID doesn’t exists
  • 409 Conflict – Specified revision is not the latest for target document

Response headers

  • Content-Type—The value can be:

    • application/json
    • text/plain; charset=utf-8
  • ETag—Revision identifier enclosed in double quotes

Message body

The response is a JSON document that contains the following objects:

Name Type Description
id String Document identifier
ok Boolean Indicates whether the operation was successful
rev String revision identifier

Example

Request

DELETE /cookbook/ButterChicken?rev=2-1b76d07281d4a576130c7d8f9f621d5e
Host: localhost:59840

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: application/json
Date: Fri, 13 Dec 2013 20:52:38 GMT
Etag: "3-7c9a006fb9938b0994cb06a9c11521e7"
Server: CouchbaseLite 1.486
Transfer-Encoding: chunked

{
  "id" : "ButterChicken",
  "rev" : "3-7c9a006fb9938b0994cb06a9c11521e7",
  "ok" : true
}

PUT /{db}/{doc}/{attachment}

This request adds or updates the supplied request content as an attachment to the specified document. The attachment name must be a URL-encoded string (the file name). You must also supply either the rev query parameter or the If-Match HTTP header for validation, and the Content-Type headers (to set the attachment content type).

When uploading an attachment using an existing attachment name, the corresponding stored content of the database will be updated. Because you must supply the revision information to add an attachment to the document, this serves as validation to update the existing attachment.

Uploading an attachment updates the corresponding document revision. Revisions are tracked for the parent document, not individual attachments.

Request

Request headers

  • Content-TypeRequired—MIME type of the attachment.

  • If-MatchRequired if the rev query parameter is not supplied —Revision identifier of the requested document.

Query parameters

Name Type Description Default
rev string Revision identifier none

Message body

The message body contains the attachment, in the format specified in the Content-Type header.

Response

Status codes

  • 200 OK – Attachment successfully removed
  • 202 Accepted – Request was accepted, but changes are not yet stored on disk
  • 400 Bad Request – Invalid request body or parameters
  • 401 Unauthorized – Write privileges required
  • 404 Not Found – Specified database, document or attachment was not found
  • 409 Conflict – Document’s revision wasn’t specified or it’s not the latest

Response headers

  • Accept-Ranges – Range request aware. Used for attachments with application/octet-stream
  • Content-Encoding – Used compression codec. Available if the attachment’s content is a compressible type.
  • Content-Length – Attachment size. If compression codec is used, this value represents the compressed size, not the actual size.
  • Content-MD5 – Base64 encoded MD5 binary digest
  • ETag—Revision identifier enclosed in double quotes

Message body

The response is a JSON document that contains the following objects:

Name Type Description
id String Document identifier
ok Boolean Indicates whether the operation was successful
rev String revision identifier

Example

The following example adds a plain text attachment to the document identified by LemonChicken in the cookbook database.

Request

PUT /cookbook/LemonChicken/lcnote.txt?rev=1-78abf9a6508671ba8338e4ef6daa910a HTTP/1.1
Host: localhost:59840
Content-Type: text/plain

Some notes about the Lemon Chicken recipe from testers

* This recipe is fabulous
* I wish it made more servings

Response

HTTP/1.1 201 Created
Accept-Ranges: bytes
Content-Length: 91
Content-Type: application/json
Date: Fri, 13 Dec 2013 22:52:49 GMT
Etag: "2-6847bbc089e24db84bd0371b9c169566"
Location: http://localhost:59840/cookbook/LemonChicken/lcnote.txt
Server: CouchbaseLite 1.486

{
  "id" : "LemonChicken",
  "rev" : "2-6847bbc089e24db84bd0371b9c169566",
  "ok" : true
}

GET /{db}/{doc}/{attachment}

This request retrieves the file attachment associated with the document. The raw data of the associated attachment is returned (just as if you were accessing a static file). The returned content is the same content type set when the document attachment was added to the database.

Request

Request headers

  • If-MatchOptional —Revision identifier of the requested document. Alternative to the rev query parameter

  • If-None-MatchOptional—The attachment’s Base64-encoded MD5 binary digest.

Query parameters

Name Type Description Default
rev string Revision identifier none

Message body

Response

Status codes

  • 200 OK – Attachment exists
  • 304 Not Modified – Attachment wasn’t modified if ETag equals specified If-None-Match header
  • 401 Unauthorized – Read privilege required
  • 404 Not Found – Specified database, document or attachment was not found

Response headers

  • Accept-Ranges – Range request aware. Used for attachments with application/octet-stream
  • Content-Encoding – Used compression codec. Available if the attachment’s content is a compressible type.
  • Content-Length – Attachment size. If compression codec is used, this value represents the compressed size, not the actual size.
  • Content-MD5 – Base64 encoded MD5 binary digest
  • ETag—Revision identifier enclosed in double quotes

Message body

The message body contains the attachment, in the format specified in the Content-Type header.

Example

Request

The following request retrieves the attachment that was added in the previous example.

GET http://localhost:59840/cookbook/LemonChicken/lcnote.txt?rev=2-6847bbc089e24db84bd0371b9c169566
Host: localhost:59840

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: must-revalidate
Content-Length: 112
Content-Type: text/plain; charset=UTF-8
Date: Fri, 13 Dec 2013 22:59:25 GMT
Etag: "2-6847bbc089e24db84bd0371b9c169566"
Server: CouchbaseLite 1.486

Some notes about the Lemon Chicken recipe from testers

* This recipe is fabulous
* I wish it made more servings

DELETE /{db}/{doc}/{attachment}

This request deletes an attachment to the specified document. To delete an attachment, you must supply the rev query parameter or If-Match header with the current revision identifier.

Request

Request headers

  • Acceptoptional—Valid values are:

    • application/json
    • text/plain
  • If-MatchRequired if the rev query parameter is not supplied —Revision identifier of the requested document.

Query parameters

Name Type Description Default
batch string Stores the document in batch mode. To use, set the value to ok. none
rev string Revision identifier none

Message body

None

Response

Status codes

  • 200 OK – Attachment successfully removed
  • 202 Accepted – Request was accepted, but changes are not yet stored on disk
  • 400 Bad Request – Invalid request body or parameters
  • 401 Unauthorized – Write privileges required
  • 404 Not Found – Specified database, document or attachment was not found
  • 409 Conflict – Document’s revision wasn’t specified or it’s not the latest

Response headers

  • Content-Type—The value can be:

    • application/json
    • text/plain; charset=utf-8
  • ETag—Revision identifier enclosed in double quotes

Message body

The response is a JSON document that contains the following objects:

Name Type Description
id String Document identifier
ok Boolean Indicates whether the operation was successful
rev String revision identifier

Example

The following example deletes the attachment that was added in a previous example.

Request

DELETE /cookbook/LemonChicken/lcnote.txt?rev=2-6847bbc089e24db84bd0371b9c169566
Host: localhost:59840

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 91
Content-Type: application/json
Date: Sat, 14 Dec 2013 00:32:26 GMT
Etag: "3-6210945863a15ee7eff1e540133d19da"
Server: CouchbaseLite 1.486

{
  "id" : "LemonChicken",
  "rev" : "3-6210945863a15ee7eff1e540133d19da",
  "ok" : true
}

Local Document Resources

Local document resources enable you to create documents that are not replicated to other databases. You can use local documents to store configuration or other information that pertains only to the local database. The following table lists the local document resources:

HTTP method URI pattern Description
PUT /{db}/_local/{local-doc} Creates a local document
GET /{db}/_local/{localdoc} Retrieves a local document
DELETE /{db}/local/{local-doc} Deletes a local document

PUT /{db}/local/{local-doc}

This request creates a local document.

Request

Response

Example

GET /{db}/local/{local-doc}

This request retrieves a local document.

Request

Response

Example

DELETE /{db}/local/{local-doc}

This request deletes a local document.

Request

Response

Example

Design Document Resources

Design document resources enable you to create and modify views. The following table lists the design document resources.

HTTP Method URI pattern Description
PUT /{db}/_design/{design-doc} Creates or updates a design document
GET /{db}/_design/{design-doc} Retrieves a design document
DELETE /{db}/_design/{design-doc} Deletes a design document
GET /{db}/_design/{design-doc}/{attachment} Retrieves a design document attachment
PUT /{db}/_design/{design-doc}/{attachment} Uploads a design document attachment
DELETE /{db}/_design/{design-doc}/{attachment} Deletes a design document attachment
GET /{db}/_design/{design-doc}/_view/{view-name} Retrieves all results of a view
POST /{db}/_design/{design-doc}/_view/{view-name} Retrieves specified rows from a view

PUT /{db}/_design/{design-doc}

Request

Response

Example

GET /{db}/_design/{design-doc}

Request

Response

Example

DELETE /{db}/_design/{design-doc}

Request

Response

Example

GET /{db}/_design/{design-doc}/{attachment}

Request

Response

Example

PUT /{db}/_design/{design-doc}/{attachment}

Request

Response

Example

DELETE /{db}/_design/{design-doc}/{attachment}

Request

Response

Example

GET /{db}/design/{design-doc}/view/{view-name}

Request

Response

Example

POST /{db}/design/{design-doc}/view/{view-name}

Request

Response

Example

Server Resources

Server resources enable you to interact with a server that hosts Couchbase Lite databases.

The following table lists the server resources:.

HTTP Method URI pattern Description
GET / Retrieves meta-information about the server
GET /_active_tasks Retrieves a list of tasks running on the server
GET /_all_dbs Retrieves a list of all databases on the server
POST _replicate Starts or cancels a replication operation
GET _session Returns a generic response for compatibility purposes
GET /_uuids Retrieves a list of identifiers of the databases on the server

GET /

This request returns meta-information about the server.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

Response headers

This response uses only standard HTTP headers.

Message body

The response message body contains a JSON document with the following objects:

Name Type Description
CouchbaseLite String Contains the string “Welcome”
couchdb String Contains the string “Welcome”
version String Couchbase Lite version number

Example

The following example requests information about the server running at http://localhost:59840/.

Request

GET / HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Server: CouchbaseLite 1.485
Transfer-Encoding: chunked
Accept-Ranges: bytes
Content-Type: application/json
Cache-Control: must-revalidate
Date: Fri, 06 Dec 2013 19:21:48 GMT

{
  "couchdb" : "Welcome",
  "CouchbaseLite" : "Welcome",
  "version" : "1.485"
}

GET /_active_tasks

This request retrieves a list of all tasks running on the server.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

Response headers

This response uses only standard HTTP headers.

Message body

The response message body contains a JSON document with an array of active tasks. If there are no active tasks, an empty array is returned in the response.

Example

Request

GET /beer-db/_active_tasks HTTP/1.1
Host: localhost:59840

GET _all_dbs

This request retrieves a list of all databases on the server.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

Response headers

This response uses only standard HTTP headers.

Message body

The response message contains the following object:

Name Type Description
not applicable array List of the names of the databases on the server

Example

The following example requests a list of databases on the server. The response lists the three databases on the server: beer-db, cookbook, and genealogy.

Request

GET /_all_dbs HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Server: CouchbaseLite 1.485
Transfer-Encoding: chunked
Accept-Ranges: bytes
Content-Type: application/json
Cache-Control: must-revalidate
Date: Mon, 09 Dec 2013 01:45:38 GMT

[
  "_replicator",
  "beer-db",
  "cookbook",
  "genealogy"
]

POST _replicate

This request starts or cancels a replication operation.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

The request message body is a JSON document that contains the following objects:

Name Type Description Required
create_target Boolean Indicates whether to create the target database No
source string URI of the source database Yes
target string URI of the target database Yes

Response

Status codes

Response headers

This response uses only standard HTTP headers.

Message body

The response message body is a JSON document that contains the following objects.

Name Type Description
ok Boolean Indicates whether the replication operation was successful
session_id string Session identifier

Example

The following example replicates the database named beer-db located at sync.couchbasecloud.com to a database named beer-db on the local server.

Request

POST /_replicate HTTP/1.1
Host: localhost:59840

{
   "create_target" : true,
   "source" : "http://sync.couchbasecloud.com/beer-db/",
   "target" : "beer-db",
}

Response

Status Code: 200 OK
Accept-Ranges: bytes
Date: Fri, 06 Dec 2013 21:57:08 GMT
Server: CouchbaseLite 1.485
Transfer-Encoding: chunked

{
   "session_id":"repl001",
   "ok":true
}

GET /_session

This request retrieves session information. Even though Couchbase Lite doesn’t support user logins, it implements a generic response to the _session API for compatibility with apps, such as Futon, that might call it.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

Response headers

This response uses only standard HTTP headers.

Message body

Example

The following example shows request for session information.

Request

GET /_session
Host: localhost:59840

Response

HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: must-revalidate
Content-Type: application/json
Date: Wed, 18 Dec 2013 21:34:56 GMT
Server: CouchbaseLite 1.486
Transfer-Encoding: chunked

{
  "userCtx" : {
    "name" : null,
    "roles" : [
      "_admin"
    ]
  },
  "ok" : true
}

GET /_uuids

This request retrieves a list of the database identifiers.

Request

Request headers

This request does not have any required headers.

Query parameters

This request does not use query parameters.

Message body

This request does not use a message body.

Response

Status codes

Response headers

This response uses only standard HTTP headers.

Message body

The response message body is a JSON document that contains the following objects.

Name Type Description
uuids array List of database identifiers

Example

The following example requests the UUIDs from the local server.

Request

GET /_uuids HTTP/1.1
Host: localhost:59840

Response

HTTP/1.1 200 OK
Server: CouchbaseLite 1.485
Content-Type: application/json
Accept-Ranges: bytes
Content-Length: 65
Cache-Control: must-revalidate
Date: Mon, 09 Dec 2013 03:20:40 GMT

{
  "uuids" : [
    "E29107F0-DF5F-4273-86C4-4FF2ED0229AD"
  ]
}

Authentication Resources

Authentication resources enable you authenticate users via Facebook or Mozilla Persona.

The following table lists the authentication resources.

HTTP Method URI pattern Description
POST /_facebook_token Facebook
POST /_persona_assertion Persona