A newer version of this documentation is available.

View Latest
March 30, 2025
+ 12

Description of the Sync Gateway Admin REST API, alternative representation as a static page

Resources

This resources section groups together the available API operations under functional categories.

Access Control

Convenience API for Sync function upsert

Get Sync Function

GET /{db}/_config/sync
Description

Get the content of the current Sync Function

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

OK

Sync_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Example HTTP response
Response 200
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""

Update Sync Function

PUT /{db}/_config/sync
Description

Use this convenience endpoint to add or update the Sync function for an existing Sync Gateway database

See the 'Model' below for more info

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

sync function
required

The Javascipt code for the sync function

Sync_model

Responses
HTTP Code Description Schema

200

OK

Sync_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Security
Example HTTP request
Request body
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""
Example HTTP response
Response 200
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""

Delete Sync Function

DELETE /{db}/_config/sync
Description

Use this convenience endpoint to remove an existing Sync function

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

sync function
required

The Javascipt code for the sync function

Sync_model

Responses
HTTP Code Description Schema

200

OK

Sync_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Example HTTP request
Request body
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""
Example HTTP response
Response 200
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""

Authentication

Manage OpenID Connect providers

OpenID Connect Authentication.

GET /{db}/_oidc
Description

Called by clients to initiate the OIDC Authorization Code flow.

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Query

offline
optional

When true, requests a refresh token from the OP. Sets access_type=offline and prompt=consent on the redirect to the OP. Secure clients should set offline=true and persist the returned refresh token to secure storage.

boolean

Query

provider
optional

OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.

string

Responses
HTTP Code Description Schema

302

Redirect to the requested OpenID Connect provider for authentication. Redirect link is returned in the Location header.

No Content

400

Bad request. Reason is returned as "OpenID Connect not configured for database default". If a provider was specified in the request, that provider was not defined in the Sync Gateway config. If no provider was specified, OpenID Connect is not configured in the Sync Gateway config.

No Content

500

Server Error. Sync Gateway is unable to connect and validate the OpenID Connect provider requested.

No Content

OpenID Connect Authentication callback.

GET /{db}/_oidc_callback
Description

Sync Gateway callback URL that clients are redirected to by the OpenID Connect provider.

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Query

code
required

OpenID Connect Authorization code.

string

Query

provider
optional

OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.

string

Responses
HTTP Code Description Schema

200

Successful OpenID Connect authentication.

Response 200

400

Bad request.

No Content

401

Authentication failed. Reason returned in the response body.

No Content

Response 200

Name Description Schema

access_token
optional

OpenID Connect access token

string

expires_in
optional

TTL for id_token

number

id_token
optional

OpenID Connect ID token

string

name
optional

Sync Gateway username

string

refresh_token
optional

OpenID Connect refresh token

string

session_id
optional

Sync Gateway session token

string

token_type
optional

OpenID Connect token type

string

OpenID Connect Authentication.

GET /{db}/_oidc_challenge
Description

Called by clients to initiate the OIDC Authorization Code flow.

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Query

offline
optional

When true, requests a refresh token from the OP. Sets access_type=offline and prompt=consent on the redirect to the OP. Secure clients should set offline=true and persist the returned refresh token to secure storage.

boolean

Query

provider
optional

OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.

string

Responses
HTTP Code Description Schema

302

Redirect to the requested OpenID Connect provider for authentication. Redirect link is returned in the Location header.

No Content

400

Bad request. Reason is returned as "OpenID Connect not configured for database default". If a provider was specified in the request, that provider was not defined in the Sync Gateway config. If no provider was specified, OpenID Connect is not configured in the Sync Gateway config.

No Content

500

Server Error. Sync Gateway is unable to connect and validate the OpenID Connect provider requested.

No Content

OpenID Connect refresh.

GET /{db}/_oidc_refresh
Description

Used to obtain a new OpenID Connect ID token based on the provided refresh token.

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Query

provider
optional

OpenId Connect provider to be used for authentication, from the list of providers defined in the Sync Gateway Config. If not specified, will attempt to authenticate using the default provider.

string

Query

refresh_token
required

OpenID Connect refresh token.

string

Responses
HTTP Code Description Schema

200

Successful OpenID Connect authentication.

Response 200

400

Bad request.

No Content

401

Authentication failed. Unable to refresh token.

No Content

Response 200

Name Description Schema

access_token
optional

OpenID Connect access token

string

expires_in
optional

TTL for id_token

number

id_token
optional

OpenID Connect ID token

string

name
optional

Sync Gateway username

string

session_id
optional

Sync Gateway session token

string

token_type
optional

OpenID Connect token type

string

Bootstrap Configuration

Returns bootstrap settings and updates logging options

Get Server Configuration

GET /_config
Description

Returns the Sync Gateway configuration of the running instance. This is a good method to check if a particular key was set correctly on the config file.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Responses
HTTP Code Description Schema

200

Sync Gateway configuration of the running instance.

Bootstrap_model

Update Logging Options

PUT /_config
Description

Update bootstrap logging options without needing a restart

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Schema

Body

bootstrap logging setting
required

Logging_model

Responses
HTTP Code Description Schema

200

Returned updated Bootstrap logging settings

Logging_model

Database Configuration

Configure sync gateway databases

Get Database Configuration

GET /{db}/_config
Description

Returns the Sync Gateway configuration of the database specified in the URL. This is a good method to check if a particular key was set correctly on the config file.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

Sync Gateway configuration of the running instance.

No Content

Update Database Configuration

PUT /{db}/_config
Description

Use this endpoint to update the configuration of an existing Sync Gateway database.

Provide the database name in the URL path. Provide the required database configuration settings as a JSON object in the request body.

By default the updated database is brought online immediately, unless you include "offline": true in the configuration.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

database configuration details
optional

Provision the database configuration details as JSON object in request body

Database_model

Responses
HTTP Code Description Schema

200

200 - OK - Operation successful

No Content

401

401 - Unauthorized - Error validating credentials

No Content

Security

Get Import_Filter Function

GET /{db}/_config/import_filter
Description

Use this convenience endpoint to get the content of the current import_filter

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

OK

Import_filter_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Example HTTP response
Response 200
json
"\"function(doc) {\\n if (doc.type != 'mobile') {\\n return false\\n }\\n return true\\n}\\n\\n\""

Update Import_Filter Function

PUT /{db}/_config/import_filter
Description

Use this convenience endpoint to add or update the import_filter Javascript function for an existing Sync Gateway database.

See the 'Model' below for more info

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

import_filter
required

The Javascipt code for the import filter function

Import_filter_model

Responses
HTTP Code Description Schema

200

OK

Import_filter_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Security
Example HTTP request
Request body
json
"\"function(doc) {\\n if (doc.type != 'mobile') {\\n return false\\n }\\n return true\\n}\\n\\n\""
Example HTTP response
Response 200
json
"\"function(doc) {\\n if (doc.type != 'mobile') {\\n return false\\n }\\n return true\\n}\\n\\n\""

Delete Import_Filter Function

DELETE /{db}/_config/import_filter
Description

Use this convenience endpoint to remove an existing`import_filter`.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

OK

Import_filter_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Example HTTP response
Response 200
json
"\"function(doc) {\\n if (doc.type != 'mobile') {\\n return false\\n }\\n return true\\n}\\n\\n\""

Get Sync Function

GET /{db}/_config/sync
Description

Get the content of the current Sync Function

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

OK

Sync_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Example HTTP response
Response 200
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""

Update Sync Function

PUT /{db}/_config/sync
Description

Use this convenience endpoint to add or update the Sync function for an existing Sync Gateway database

See the 'Model' below for more info

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

sync function
required

The Javascipt code for the sync function

Sync_model

Responses
HTTP Code Description Schema

200

OK

Sync_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Security
Example HTTP request
Request body
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""
Example HTTP response
Response 200
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""

Delete Sync Function

DELETE /{db}/_config/sync
Description

Use this convenience endpoint to remove an existing Sync function

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

sync function
required

The Javascipt code for the sync function

Sync_model

Responses
HTTP Code Description Schema

200

OK

Sync_model

401

401 - Unauthorized - Error validating credentials

No Content

Consumes
  • application/javascript

Example HTTP request
Request body
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""
Example HTTP response
Response 200
json
"\"function(doc, oldDoc) {\\n channel(doc.channels);\\n}\\n\\n\""

Database Management

Create and manage sync gateway databases

Get Database Data

GET /{db}/
Description

This request retrieves information about the database.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

Request completed successfully. The information is returned in the response body.

Response 200

401

Unauthorized. Login required.

No Content

404

Not Found. Requested database not found.

No Content

Response 200

Name Description Schema

db_name
optional

Name of the database

string

db_uuid
optional

Database identifier

integer

disk_format_version
optional

Database schema version

integer

disk_size
optional

Total amount of data stored on the disk (in bytes)

integer

instance_start_time
optional

Date and time the database was opened (in microseconds since 1 January 1970)

string

state
optional

The state of the specified database.

Possible values are 'Online' and 'Offline'.

A database can be taken offline and brought back online using the /{db}/_offline and /{db}/_online endpoints on the Admin REST API.

string

update_seq
optional

Number of updates to the database

string

Create Database

PUT /{db}/
Description

Use this method to create a new Sync Gateway database.

The database name is taken from the URL path. Pass the required database configuration settings as a JSON object in the request body.

{
    "name": "todo_db"
    "bucket": "todo_app"
}

By default the created database is brought online immediately, unless you include "offline": true in the configuration.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

database configuration details
optional

Provision the database configuration details as JSON object in request body

Database_model

Responses
HTTP Code Description Schema

201

201 - OK - Create Operation successful

No Content

401

401 - Unauthorized - Error validating credentials

No Content

Security

Delete Database

DELETE /{db}/
Description

Delete database

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

Operation completed successfully

doc-resp

All docs

POST /{db}/_all_docs
Description

This request retrieves specified documents from the database.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

access
optional

Indicates whether to include in the response a list of what access this document grants (i.e. which users it allows to access which channels.) This option may only be used from the admin port.

boolean

"false"

Query

channels
optional

Indicates whether to include in the response a channels property containing an array of channels this document is assigned to. Channels not accessible by the user making the request will not be listed.

boolean

"false"

Query

include_docs
optional

Default is false. Indicates whether to include the associated document with each result. If there are conflicts, only the winning revision is returned.

boolean

"false"

Query

revs
optional

Default is false. Indicates whether to include a _revisions property for each document in the response, which contains a revision history of the document. The length of the returned revision tree can be specified with the revs_limit querystring parameter.

boolean

"false"

Query

update_seq
optional

Default is false. Indicates whether to include the update_seq (document sequence ID) property in the response.

boolean

"false"

Body

body
optional

Request body

AllDocs

Responses
HTTP Code Description Schema

200

Query results

QueryResult

All docs

GET /{db}/_all_docs
Description

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

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

access
optional

Indicates whether to include in the response a list of what access this document grants (i.e. which users it allows to access which channels.) This option may only be used from the admin port.

boolean

"false"

Query

channels
optional

Indicates whether to include in the response a channels property containing an array of channels this document is assigned to. Channels not accessible by the user making the request will not be listed.

boolean

"false"

Query

endkey
optional

If this parameter is provided, stop returning records when the specified key is reached.

string

Query

include_docs
optional

Default is false. Indicates whether to include the associated document with each result. If there are conflicts, only the winning revision is returned.

boolean

"false"

Query

keys
optional

Specify a list of document IDs. Note that this is an array field, so to retrieve docs with Ids of "keyid1" and "keyid4", for example, use a request in this format –

curl -X GET \ '%22keyid1%22,%22keyid4%22' \ -H 'Accept: application/json'

< string > array

Query

limit
optional

Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1.

integer

Query

revs
optional

Default is false. Indicates whether to include a _revisions property for each document in the response, which contains a revision history of the document. The length of the returned revision tree can be specified with the revs_limit querystring parameter.

boolean

"false"

Query

startkey
optional

Returns records starting with the specified key.

string

Query

update_seq
optional

Default is false. Indicates whether to include the update_seq (document sequence ID) property in the response.

boolean

"false"

Responses
HTTP Code Description Schema

200

Query results

QueryResult

Add, Update or Delete Bulk Documents

POST /{db}/_bulk_docs
Description

This request enables you to add, update, or delete multiple documents to a database in a single request. To add new documents, you can either specify the ID (_id) or let the software create an ID. To update existing documents, you must provide the document ID, revision identifier (_rev), and new document values. To delete existing documents you must provide the document ID, revision identifier, and the deletion flag (_deleted).

The JSON returned by the _bulk_docs operation consists of an array of JSON structures, one for each document in the original submission. The returned JSON structure should be examined to ensure that all of the documents submitted in the original request were successfully added to the database.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

BulkDocsBody
optional

The request body

BulkDocsBody

BulkDocsBody

Name Description Schema

docs
optional

List containing new or updated documents. Each object in the array can contain the following properties _id, _rev, _deleted, and values for new and updated documents.

< Document_model > array

new_edits
optional

Indicates whether to assign new revision identifiers to new edits.
Default : true

boolean

Responses
HTTP Code Description Schema

201

Documents have been created or updated. The response object is an array with the status for each document submitted in the original request.

BulkDocsSuccess

409

The operation failed with a forbidden error. Probably because the document already exists in the database but a revision number wasn’t specified.

Forbidden

Get Bulk Documents

POST /{db}/_bulk_get
Description

This request returns any number of documents, as individual bodies in a MIME multipart response.

Each enclosed body contains one requested document. The bodies appear in the same order as in the request, but can also be identified by their X-Doc-ID and X-Rev-ID headers. - A body for a document with no attachments will have content type application/json and contain the document itself. - A body for a document that has attachments will be written as a nested multipart/related body. Its first part will be the document’s JSON, and the subsequent parts will be the attachments (each identified by a Content-Disposition header giving its attachment name.)

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

attachments
optional

Include attachment bodies in response. Default is false.

boolean

"false"

Query

revs
optional

Default is false. Indicates whether to include a _revisions property for each document in the response, which contains a revision history of the document. The length of the returned revision tree can be specified with the revs_limit querystring parameter.

boolean

"false"

Query

revs_limit
optional

The number of revisions to include in the response from the document history.

This property is only honoured if revs=true is also sent in the request.

If revs=true is specified and revs_limit isn’t, the full revision history is returned.

For more information see: Revisions page.

integer

Body

BulkGetBody
optional

List of documents being requested.

Each array element is an object that must contain an id property giving the document ID. It may contain a rev property if a specific revision is desired. It may contain an atts_since property (as in a single-document GET) to limit which attachments are sent.

< BulkGetBody > array

BulkGetBody

Name Description Schema

att_since
optional

att_since

string

id
optional

Document ID.

string

rev
optional

rev

string

Responses
HTTP Code Description Schema

200

Request completed successfully

No Content

301

Request failed with a forbidden error. This usually happens because the user requesting that document doesn’t have access to it. Access to documents is granted to users through channels.

Response 301

Response 301

Name Description Schema

_id
optional

The document ID that was requested

string

_removed
optional

Default : true

boolean

_rev
optional

The revision number that was requested

string

Produces
  • multipart/mixed

Example HTTP response
Response 200
json
{ "multipart/mixed (document found)" : "--1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4\nContent-Type: application/json\n\n{\"_id\":\"doc123\",\"_rev\":\"1-c543d6514c609f65180f94af247aaffe\",\"hello\":\"world!\"}\n--1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4\n", "multipart/mixed (document not found)" : "--1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4\nContent-Type: application/json; error=\"true\"\n\n{\"error\":\"not_found\",\"id\":\"doc1234\",\"reason\":\"missing\",\"status\":404}\n--1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4\n" }

Changes

POST /{db}/_changes
Description

Same as the GET /_changes request except the parameters are in the JSON body.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

ChangesBody
optional

The request body

ChangesBody

ChangesBody

Name Description Schema

active_only
optional

Default is false. When true, the changes response doesn’t include either deleted documents, or notification for documents that the user no longer has access to.
Default : false

boolean

channels
optional

A comma-separated list of channel names. The response will be filtered to only documents in these channels. (This parameter must be used with the sync_gateway/bychannel filter parameter; see below.)

string

doc_ids
optional

A list of document IDs as a valid JSON array. The response will be filtered to only documents with these IDs. (This parameter must be used with the _doc_ids filter parameter; see below.)

< string > array

feed
optional

Default is 'normal'. Specifies type of change feed. Valid values are normal, continuous, longpoll, websocket.
Default : "normal"

string

filter
optional

Indicates that the returned documents should be filtered. The valid values are sync_gateway/bychannel and _doc_ids.

string

heartbeat
optional

Default is 0. Interval in milliseconds at which an empty line (CRLF) is written to the response. This helps prevent gateways from deciding the socket is idle and closing it. Only applicable to longpoll or continuous feeds. Overrides any timeout to keep the feed alive indefinitely. Setting to 0 results in no heartbeat.

integer

include_docs
optional

Default is false. Indicates whether to include the associated document with each result. If there are conflicts, only the winning revision is returned.
Default : false

boolean

limit
optional

Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1.

integer

since
optional

Starts the results from the change immediately after the given sequence ID. Sequence IDs should be considered opaque; they come from the last_seq property of a prior response.

object

style
optional

Default is 'main_only'. Number of revisions to return in the changes array. The only possible value is all_docs and it returns all leaf revisions including conflicts and deleted former conflicts.
Default : "main_only"

string

timeout
optional

Default is 300000. 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. Setting to 0 results in no timeout.

integer

Responses
HTTP Code Description Schema

200

Request completed successfully

Changes

Get List of Changes (query parameters)

GET /{db}/_changes
Description

This request retrieves a sorted list of changes made to documents in the database, in time order of application.

Each document appears at most once, ordered by its most recent change, regardless of how many times it’s been changed. 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.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

active_only
optional

Default is false. When true, the changes response doesn’t include either deleted documents, or notification for documents that the user no longer has access to.

boolean

"false"

Query

channels
optional

A comma-separated list of channel names. The response will be filtered to only documents in these channels. (This parameter must be used with the sync_gateway/bychannel filter parameter; see below.)

string

Query

doc_ids
optional

A list of document IDs as a valid JSON array. The response will be filtered to only documents with these IDs. This parameter must be used with the filter=_doc_ids and feed=normal parameters.

< string > array

Query

feed
optional

Default is 'normal'. Specifies type of change feed. Valid values are normal, continuous, longpoll, websocket.

string

"normal"

Query

filter
optional

Indicates that the reported documents should be filtered. The valid values are sync_gateway/bychannel and _doc_ids.

string

Query

heartbeat
optional

Default is 0. Interval in milliseconds at which an empty line (CRLF) is written to the response.

This helps prevent gateways from deciding the socket is idle and closing it. Only applicable to longpoll or continuous feeds. Overrides any timeout to keep the feed alive indefinitely. Setting to 0 results in no heartbeat.

integer

0

Query

include_docs
optional

Default is false. Indicates whether to include the associated document with each result. If there are conflicts, only the winning revision is returned.

boolean

"false"

Query

limit
optional

Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1.

integer

Query

since
optional

Starts the results from the change immediately after the given sequence ID.

Sequence IDs should be considered opaque; they come from the last_seq property of a prior response.

integer

Query

style
optional

Default is 'main_only'. 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.

string

"main_only"

Query

timeout
optional

Default is 300000. 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. Setting to 0 results in no timeout.

integer

300000

Responses
HTTP Code Description Schema

200

Request completed successfully

Changes

Compact Database

POST /{db}/_compact
Description

Use the /{db}/_compact endpoint to start a compaction process. The process purges the JSON bodies of non-leaf revisions.

Using this endpoint following a failed compaction will trigger a restart of the compact_id at the appropriate phase (where possible).

This process is also run periodically by the system.

Note - Leaf revisions are not purged during compaction.

Compaction does not remove JSON bodies of leaf nodes (conflicting branches). So it is also important to resolve conflicts in your application in order to re-claim disk space.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

action
optional

Use the action parameter to start or stop a _compact process.

The value must be one of : - start - immediately starts (or restarts) a compaction and returns its status

* stop - immediately stops the active compaction and returns the status

This parameter works in conjunction with compaction type.

string

"start"

Query

dry_run
optional

Use dry_run only for attachment compaction.

If this is set to true the process will run but will not execute the final purge of attachments. It can be used to check how many attachments will be purged.

string

"false"

Query

reset
optional

Use reset only for attachment compaction.

If this is set to true the start action will not attempt to resume a failed process but will force a fresh compact to start.

string

"false"

Query

type
optional

Use the type option to specify the type of compaction required.

The type must be one of : - attachment for legacy pre-3.0 attachment compaction

* tombstone for database compaction, which purges the JSON bodies of non-leaf revisions.

This parameter works in conjunction with compaction action.

string

"tombstone"

Responses
HTTP Code Description Schema

200

OK - This successful response indicates _compact process was started. The response body comprises a JSON object showing the _compact status.

Compact_Response

400

Bad Request

This can mean that a required parameter has not been provided, the value supplied is invalid, or the combination of provided parameters is invalid.

Compaction API returns a 400 Bad Request error in the following cases: - A GET /{db}/_compact request is submitted with an invalid value for type parameter (anything other than tombstone or attachment). - A POST /{db}/_compact request is submitted with an invalid value for type parameter (type must be either tombstone or attachment) and or action parameter (action must be either start or stop).

No Content

503

Service Unavailable

A 503 Service Unavailable error indicates that the system is not ready to handle the submitted compaction start request due another compaction is running. You may encounter this error when you submit a compaction request in the middle of another.

No Content

Get Compact Status

GET /{db}/_compact
Description

Use this request to return the current status of a compaction.

Set the type parameter to one of: - tombstone - A GET request to /{db}/_compact?type=tombstone returns the number of tombstones removed. - attachment - A GET request to /{db}/_compact?type=attachment returns the number of attachments that are removed from the bucket.

For example: { "status": "running", "start_time": "2021-12-02T18:26:17.086152Z", "last_error": "", "marked_attachments": 0, "purged_attachments": 0, "compact_id": "68302d2d-2c56-434e-94e0-33c0d0437828", "phase": "cleanup" }

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

type
optional

Use the type option to specify the type of compaction required.

The type must be one of : - attachment for legacy pre-3.0 attachment compaction

* tombstone for database compaction, which purges the JSON bodies of non-leaf revisions.

This parameter works in conjunction with compaction action.

string

"tombstone"

Responses
HTTP Code Description Schema

200

OK - A successful response will return a JSON object containing the _compact status.

The current phase of running compact processes is returned in phase.

Compact_Response

Take Database Offline

POST /{db}/_offline
Description

This request takes the specified database offline.

An offline database is not accessible through Sync Gateway’s Public REST API. However, some commands can be given to Sync Gateway through the Admin REST API.

Taking a database offline will:

  • Cleanly closes all active _changes feeds for this database.

  • Rejects all access to the database through the Public REST API (503 Service Unavailable).

  • Rejects most Admin API requests (503 Service Unavailable). A specific, short list of Admin REST API requests remain available (GET /{db}, PUT /{db}/_config, POST /{db}/_resync).

  • Stops webhook event handlers.

  • Does not take the backing Couchbase Server bucket offline. The bucket remains available and Sync Gateway keeps its connection to the bucket.

When a database is offline, you can load properties for the database, without stopping and re-starting the Sync Gateway instance. The new properties are applied when the database is brought online.

Taking a database offline that is in the progress of coming online will take the database offline after it comes online.

For more information about taking a database offline and bringing it back online, see this guide.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

Database brought online

No Content

Bring Database Online.

POST /{db}/_online
Description

When a database is online, Sync Gateway serves both Public and Admin REST API requests for the database. This request brings the specified database online, either immediately or after a specified delay.

Bringing a database online:

  • Closes the databases connection to the backing Couchbase Server bucket.

  • Reloads the database configuration, and connects to the backing Couchbase Server bucket.

  • Re-establishes access to the database from the Public REST API.

  • Accepts all Admin API requests.

You can bring an offline database online after a specific delay. Uses for this include:

  • Making a database available for Couchbase Mobile clients at a specific time.

  • Making databases on several Sync Gateway instances available at the same time.

For more information about taking a database offline and bringing it back online, see this guide.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

body
optional

Optional request body to specify a delay.

body

body

Name Description Schema

delay
optional

Delay in seconds before bringing the database online.

integer

Responses
HTTP Code Description Schema

200

OK - online request accepted.

No Content

503

Service Unavailable - Database resync is in progress.

No Content

Start or Stop Resync

POST /{db}/_resync
Description

Use the _resync operation whenever you have modified the database’s sync function such that the channel or access mappings for any existing document would change as a result.

The request will start or stop the _resync process depending upon the action parameter provided. If no action parameter is given then start is assumed.

action=start

The start action causes all documents to be reprocessed by the database’s sync function. This is an asynchronous operation.

When the sync function is invoked by _resync, the requireUser() and requireRole() calls will always return 'true'.

A _resync operation on a database that is not in the offline state will be rejected (503 Service Unavailable).

action=stop

The currently running resync operation is stopped.

regenerate_sequences=true Use this only when requested to do so by the Couchbase support team

This request will start a resync while regenerating sequences.

The resync action is carried out only on the node that the POST is made to. It is not cross-node aware.

In a multi-node cluster, the resync must be only run on one node. Users should bring other nodes offline before initiating this action. Starting it on more than one node will result in multiple resyncs running, with undefined system behavior.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

action
optional

The action query can be “start” or “stop”. If neither is provided,“start” is used as the default.

* Start will 'begin' the asynchrounous resync operation.

* Stop will stop the resync operation and will return

string

"start"

Query

regenerate_sequences
optional

Use this only when requested to do so by the Couchbase support team

Set regenerate_sequences=true along with action=start in order to begin a resync while regenerating sequences.

string

"none"

Responses
HTTP Code Description Schema

200

OK

Resync-response

400

400 - Database _resync not running

No Content

503

503 error code. The meaning varies depending on the action parameter:

* action=start - Database must be offline before calling _resync.

* action=stop - Database _resync already in progress

No Content

Show resync status

GET /{db}/_resync
Description

This request returns the status of the asynchronous _resync operation, including:

  • status

  • docs processed

  • docs changed

  • last error (if any)

Sync Gateway Roles Required:

  • Sync Gateway Architect

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

OK

Resync-response

Get Revisions DIff List

POST /{db}/_revs_diff
Description

Given a set of document/revision IDs, returns the subset of those that do not correspond to revisions stored in the database.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

body
optional

Request body

< body > array

body

Name Description Schema

key
optional

document id

string

value
optional

revision id

string

Responses
HTTP Code Description Schema

200

The request was successful. Returns a list of revision IDs for that document (the ones that are not stored in the database)

< Response 200 > array

Response 200

Name Description Schema

key
optional

document id

string

value
optional

revision id

string

Database Security

Create and manage database users and roles

Create New Role

POST /{db}/_role
Description

This request creates a new role

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

role
optional

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

Role_model

Responses
HTTP Code Description Schema

201

201 - OK - Create Operation successful

No Content

401

401 - Unauthorized - Error validating credentials

No Content

409

409 - Conflict - For example, an object with this name already exists

No Content

Get All Roles

GET /{db}/_role
Description

This request returns all the roles in the specified database.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

200 OK - Returns the list of roles as an array of strings

The message body contains the list of roles in a JSON array. Each element of the array is a string representing the name of a role in the specified database.

< string > array

401

401 - Unauthorized - Error validating credentials

No Content

Get Specific Role

GET /{db}/_role/{name}
Description

Request a specific role by name.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Without Application or Application Read Only users will be unable to see dynamic user or role data.

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

Role name, may contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a role any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a role name in a URL path it must be escaped again using percent encoding for example if a role is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same role name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Responses
HTTP Code Description Schema

200

The response contains information about this role.

Response 200

401

401 - Unauthorized - Error validating credentials

No Content

Response 200

Name Description Schema

admin_channels
optional

The admin channels that this role has granted access to. Admin channels are the ones which are granted access to in the config file or via the Admin REST API.

< string > array

all_channels
optional

All the channels that this role has access to.

< string > array

name
optional

string

Update Specific Role

PUT /{db}/_role/{name}
Description

Use this convenience endpoint to upsert a Sync Gateway role.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

Role name, may contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a role any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a role name in a URL path it must be escaped again using percent encoding for example if a role is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same role name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Body

role
optional

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

Role_model

Responses
HTTP Code Description Schema

200

200 - OK - Operation successful

No Content

201

201 - OK - Create Operation successful

No Content

401

401 - Unauthorized - Error validating credentials

No Content

Security

Delete Specific Role

DELETE /{db}/_role/{name}
Description

This request deletes the role with the specified name.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

Role name, may contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a role any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a role name in a URL path it must be escaped again using percent encoding for example if a role is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same role name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Responses
HTTP Code Description Schema

200

200 OK - The role was successfully deleted

No Content

Create New User

POST /{db}/_user/
Description

This request creates a new user

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application`

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

user configuration data
optional

Provision the user configuration data in JSON format in the body

User_model

Responses
HTTP Code Description Schema

201

201 - OK - Create Operation successful

No Content

401

401 - Unauthorized - Error validating credentials

No Content

409

409 - Conflict - For example, an object with this name already exists

No Content

Get All Users

GET /{db}/_user/
Description

This request returns a list of all users

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

The message body contains the list of users in a JSON array. Each element of the array is a string representing the name of a user in the specified database.

< string > array

404

404 - Not Found - Object missing or misreferenced

No Content

Get User Data

GET /{db}/_user/{name}
Description

This request returns information about the specified user.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Without Application or Application Read Only users will be unable to see dynamic user or role data.

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

User’s name, may contain contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a user any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a user name in a URL path it must be escaped again using percent encoding for example if a user is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same user name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Responses
HTTP Code Description Schema

200

200 OK - Returns information about the specified user

User-response

401

401 - Unauthorized - Error validating credentials

No Content

Update User Data

PUT /{db}/_user/{name}
Description

Use this method to create or update a user

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

User’s name, may contain contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a user any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a user name in a URL path it must be escaped again using percent encoding for example if a user is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same user name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Body

user configuration data
optional

Provision the user configuration data in JSON format in the body

User_model

Responses
HTTP Code Description Schema

200

200 - OK - Operation successful

No Content

201

201 - OK - Create Operation successful

No Content

401

401 - Unauthorized - Error validating credentials

No Content

Security

Delete Specific User

DELETE /{db}/_user/{name}
Description

This request deletes the user with the specified name

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

User’s name, may contain contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a user any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a user name in a URL path it must be escaped again using percent encoding for example if a user is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same user name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Responses
HTTP Code Description Schema

200

200 - OK - Operation successful

No Content

401

401 - Unauthorized - Error validating credentials

No Content

Design Documents

Work with sync gateway design docs

Get Views of a design document

GET /{db}/_design/{ddoc}
Description

Query a design document.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

ddoc
required

Design document name

string

Responses
HTTP Code Description Schema

200

Views for design document

Response 200

Response 200

Name Schema

my_view_name
optional

View

Update views of a design document

PUT /{db}/_design/{ddoc}
Description

Update views of a design document

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

ddoc
required

Design document name

string

Body

body
optional

The request body

View

Responses
HTTP Code Description Schema

200

OK

No Content

Delete design document

DELETE /{db}/_design/{ddoc}
Description

Delete a design document.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

ddoc
required

Design document name

string

Responses
HTTP Code Description Schema

200

The status

Design

default

Unexpected error

Error

Query a view

GET /{db}/_design/{ddoc}/_view/{view}
Description

Query a view on a design document.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

ddoc
required

Design document name

string

Path

view
required

View name

string

Query

conflicts
optional

Include conflict information in the response. This parameter is ignored if the include_docs parameter is false.

boolean

Query

descending
optional

Return documents in descending order.

boolean

Query

end_key
optional

Alias for the endkey parameter.

string

Query

end_key_doc_id
optional

Alias for the endkey_docid parameter.

string

Query

endkey
optional

If this parameter is provided, stop returning records when the specified key is reached.

string

Query

endkey_docid
optional

If this parameter is provided, stop returning records when the specified document identifier is reached.

string

Query

group
optional

Group the results using the reduce function to a group or single row.

boolean

Query

group_level
optional

Specify the group level to be used.

integer

Query

include_docs
optional

Only works when using Couchbase Server 3.0 and earlier. Indicates whether to include the full content of the documents in the response.

boolean

Query

inclusive_end
optional

Indicates whether the specified end key should be included in the result.

boolean

Query

key
optional

If this parameter is provided, return only document that match the specified key.

string

Query

limit
optional

If this parameter is provided, return only the specified number of documents.

integer

Query

skip
optional

If this parameter is provided, skip the specified number of documents before starting to return results.

integer

Query

stale
optional

Allow the results from a stale view to be used, without triggering a rebuild of all views within the encompassing design document. Valid values are ok and update_after.

string

Query

start_key
optional

Alias for startkey param.

string

Query

startkey
optional

If this parameter is provided, return documents starting with the specified key.

string

Query

startkey_docid
optional

If this parameter is provided, return documents starting with the specified document identifier.

string

Query

update_seq
optional

Indicates whether to include the update_seq property in the response.

boolean

Responses
HTTP Code Description Schema

200

Query results

QueryResult

Document

Manage documents and attachments

Create Document

POST /{db}/
Description

This request creates a new document in the specified database.

You can either specify the document ID by including the _id in the request message body (the value must be a string), or let the software generate an ID.

The maximum size allowed for a document is 20MB.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

body
optional

The document body

object

Responses
HTTP Code Description Schema

201

Operation completed successfully

doc-resp

Get Specific Local Document

GET /{db}/_local/{local_doc}
Description

This request retrieves a local document.

Local document IDs begin with _local/. Local documents are not replicated or indexed, don’t support attachments, and don’t save revision histories. In practice they are almost only used by Couchbase Lite’s replicator, as a place to store replication checkpoint data.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

local_doc
required

Local document IDs begin with _local/.

string

Responses
HTTP Code Description Schema

200

OK

No Content

Update Specific Local Document

PUT /{db}/_local/{local_doc}
Description

This request creates or updates a local document. Local document IDs begin with _local/. Local documents are not replicated or indexed, don’t support attachments, and don’t save revision histories. In practice they are almost only used by the client’s replicator, as a place to store replication checkpoint data.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

local_doc
required

Local document IDs begin with _local/.

string

Responses
HTTP Code Description Schema

201

Operation completed successfully

doc-resp

Delete Specific Local Document

DELETE /{db}/_local/{local_doc}
Description

This request deletes a local document. Local document IDs begin with _local/. Local documents are not replicated or indexed, don’t support attachments, and don’t save revision histories. In practice they are almost only used by Couchbase Lite’s replicator, as a place to store replication checkpoint data.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

local_doc
required

Local document IDs begin with _local/.

string

Query

batch
optional

Stores the document in batch mode. To use, set the value to ok.

string

Query

rev
optional

Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)

string

Responses
HTTP Code Description Schema

200

Operation completed successfully

doc-resp

Purge document

POST /{db}/_purge
Description

The purge command provides a way to remove a document from the bucket itself. The operation removes all the revisions (active and tombstones) for the specified document(s). A common usage of this endpoint is to remove tombstone documents that are no longer needed, thus recovering storage space and reducing data replicated to clients. Other clients are not notified when a revision has been purged; so in order to purge a revision from the system it must be done from all databases (on Couchbase Lite and Sync Gateway).

When convergence is enabled (introduced in Sync Gateway 1.5), this endpoint removes the document and its associated extended attributes.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

body
optional

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

PurgeBody

Responses
HTTP Code Description Schema

200

OK - The purge operation was successful

< string > array

Document with metadata

GET /{db}/_raw/{doc}
Description

Returns the document with the metadata.

Note: The direct use of this endpoint is unsupported. The sync metadata is maintained internally by Sync Gateway and its structure can change. It should not be used to drive business logic of applications since the response to the /{db}/_raw/{id} endpoint can change at any time.\

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

doc
required

Document ID

string

Responses
HTTP Code Description Schema

200

OK

DocMetadata

Revision Tree structure in Graphviz Dot format | not officially supported

GET /{db}/_revtree/{doc}
Description

Returns the dot syntax of the revision tree which can be rendered into a PNG image with the CLI dot tool.

  • Install the dot tool via brew install graphviz.

  • Save the response text to a file (for example, revtree.dot).

  • Render a PNG by calling dot -Tpng revtree.dot > revtree.png.

Note: This endpoint is useful for debugging purposes only. It is not officially supported.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

doc
required

Document ID

string

Responses
HTTP Code Description Schema

200

Success and returns the revtree as plain text.

No Content

Produces
  • text/plain

Get Specific Document

GET /{db}/{doc}
Description

This request retrieves a document from a database. Sync Gateway Roles Required (CBS 7.0.2 Developer Preview): - Sync Gateway Application - Sync Gateway Application Read Only

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Path

doc
required

Document ID

string

Query

attachments
optional

Include attachment bodies in response. Default is false.

boolean

"false"

Query

atts_since
optional

Include attachments only since specified revisions. Does not include attachments for specified revisions.

< string > array

Query

open_revs
optional

Option to fetch specified revisions of the document. The value can be all to fetch all leaf revisions or an array of revision numbers (i.e. open_revs=["rev1", "rev2"]). Only leaf revision bodies that haven’t been pruned are guaranteed to be returned.

If this option is specified the response will be in multipart format. Use the Accept: application/json request header to get the result as a JSON object.

string

Query

rev
optional

Revision identifier of the revision to get.

By default, Sync Gateway returns the current revision. This parameter is generally only needed for conflict resolution. For example where the app might need to retrieve a conflicting leaf revision that isn’t the current revision.

string

Query

revs
optional

Default is false. Indicates whether to include a _revisions property for each document in the response, which contains a revision history of the document. The length of the returned revision tree can be specified with the revs_limit querystring parameter.

boolean

"false"

Query

show_exp
optional

Whether to show the _exp property in the response.

boolean

"false"

Responses
HTTP Code Description Schema

200

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

object

Create or update document

PUT /{db}/{doc}
Description

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. The maximum size allowed for a document is 20MB.

Since Sync Gateway 1.3, an expiry property (_exp) can also be specified to purge the document after a given time. If convergence is enabled (introduced in Sync Gateway 1.5), the behavior of the expiry feature changes in the following way: when the expiry value is reached, instead of getting purged, the active revision of the document is tombstoned. If there is another non-tombstoned revision for this document (i.e a conflict) it will become the active revision. The tombstoned revision will be purged when the server’s metadata purge interval is reached.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Path

doc
required

Document ID

string

Query

new_edits
optional

Default is true. Setting this to false indicates that the request body is an already-existing revision that should be directly inserted into the database, instead of a modification to apply to the current document. (This mode is used by the replicato.)

This option must be used in conjunction with the _revisions property in the request body.

boolean

"true"

Query

rev
required

Revision identifier of the revision to update. It must be the last revision in the history.

string

Body

Document
optional

Request body

Document_model

Responses
HTTP Code Description Schema

200

Operation completed successfully

doc-resp

Delete document

DELETE /{db}/{doc}
Description

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.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

doc
required

Document ID

string

Query

rev
required

Revision identifier of the revision to delete. It must be the identifier of the latest revision in the history.

string

Responses
HTTP Code Description Schema

200

OK

No Content

Get attachment

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

Use this request to get the file attachment associated with a document. It returns the raw data of the associated attachment, just as if you were accessing a static file.

The Content-Type response header is the same content type set when the document attachment was added to the database.

To remove an attachment from a document, simply update the _attachments dictionary of the document in the PUT "/{db}/{id}" request.

Use the meta parameter to request that only the document ID of the attachment blob be returned

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema Default

Path

attachment
required

Attachment name. This value must be URL encoded. For example, if the attachment name is blob_/avatar, the path component passed to the URL should be blob_%2Favatar (tested with URLEncoder).

string

Path

db
required

Database name

string

Path

doc
required

Document ID

string

Query

meta
optional

If true only the document ID of the attachment blob is returned in the response body

boolean

"false"

Query

rev
optional

Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)

string

Responses
HTTP Code Description Schema

200

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

string (binary)

304

Not Modified, the attachment wasn’t modified if ETag equals the If-None-Match header

No Content

400

Bad Request - A non boolean value was supplied for the meta parameter.

No Content

404

Not Found, the specified database, document or attachment was not found.

No Content

Example HTTP response
Response 200
json
"GET /{db}/{doc}/{attachment}?meta=true\n{\n \"content_type\": \"text/plain\",\n \"length\": 2,\n \"key\": \"_sync:att2:uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek=:sha1-Kq5sNclPz7QV2+lfQIuc6R7oRu0=\"\n}\n\n"

Add or update a document attachment

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

Use this request to add or update the supplied request content as an attachment to the specified document.

  • The maximum content size of an attachment is 20MB.

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

To remove an attachment from a document, simply update the _attachments dictionary of the document in the PUT "{db}/{id}" request.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Application

Parameters
Type Name Description Schema

Header

Content-Type
optional

Attachment Content-Type

string

Path

attachment
required

Attachment name. This value must be URL encoded. For example, if the attachment name is blob_/avatar, the path component passed to the URL should be blob_%2Favatar (tested with URLEncoder).

string

Path

db
required

Database name

string

Path

doc
required

Document ID

string

Query

rev
optional

Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)

string

Body

body
optional

The request body

string (binary)

Responses
HTTP Code Description Schema

200

Operation completed successfully

No Content

409

Conflict, the document revision wasn’t specified or it’s not the latest.

No Content

Logging

Update bootstrap logging settings

Update Logging Options

PUT /_config
Description

Update bootstrap logging options without needing a restart

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Schema

Body

bootstrap logging setting
required

Logging_model

Responses
HTTP Code Description Schema

200

Returned updated Bootstrap logging settings

Logging_model

Replication

Manage inter-Sync Gateway replication

Create a new replication definition

POST /{db}/_replication
Description

The replication endpoint is used to manage both _ad hoc and persistent replication operations.

Using a POST request you can insert a new set of replication details.

To Cancel a Replication You can cancel continuous replications by adding the cancel field to the JSON request object and setting the value to true. Note that the structure of the request must be identical to the original for the cancellation request to be honoured. For example, if you requested continuous replication, the cancellation request must also contain the continuous field.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

ReplicationBody
optional

This replication request message body is a JSON document that comprises all the properties required to upsert a replication.

If the replicationID matches an existing replication_id then the values of any properties provided in the body are used to update the existing replication’s property values.

Replication_model

Responses
HTTP Code Description Schema

200

Replication successfully updated

ReplicationResponse

201

Replication successfully inserted

ReplicationResponse

Get all replication definitions

GET /{db}/_replication
Description

Returns an array object containing all replication definitions

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Responses
HTTP Code Description Schema

200

Successful response - returns an array of replication definitions in the body as JSON

ReplicationResponseBody

Get a replication definition

GET /{db}/_replication/{replicationID}
Description

Returns requested (replicationID) replication definition

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

replicationID
required

The {replicationID} parameter identifies the target replication.

string

Responses
HTTP Code Description Schema

200

Successful response - returns requested replication definition in the body as JSON

ReplicationResponseBody

Upsert a replication definition

PUT /{db}/_replication/{replicationID}
Description

The replication endpoint is used to manage both _ad hoc and persistent replication operations.

Using a PUT request you can update (or insert, if it doesn’t exist) a set of replication details.

To cancel a replication You can cancel continuous replications by adding the cancel field to the JSON request object and setting the value to true.

Note that the structure of the request must be identical to the original for the cancellation request to be honoured.

For example, if you requested continuous replication, the cancellation request must also contain the continuous field.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

replicationID
required

If supplied, the <i>replicationID</i> parameter must be a valid replication id.

If it is not supplied for a <i>new</i> replication*, then a random UUID is generated.

string

Body

ReplicationBody
optional

This replication request message body is a JSON document that comprises all the properties required to upsert a replication.

If the replicationID matches an existing replication_id then the values of any properties provided in the body are used to update the existing replication’s property values.

Replication_model

Responses
HTTP Code Description Schema

200

Replication successfully updated

ReplicationResponse

201

Replication successfully inserted

ReplicationResponse

Security

Cancel and delete replication

DELETE /{db}/_replication/{replicationID}
Description

Deletes a specific (replicationID) replication - Removes persisted replication definition - Removes all checkpoints associated with the replication - Deletes all replication status information associated with the replication

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

replicationID
required

The {replicationID} parameter identifies the target replication.

string

Responses
HTTP Code Description Schema

200

Replication successfully deleted

No Content

Returns replication status data for replications matching the criteria

GET /{db}/_replicationStatus
Description

About

Returns replication status data for all replications matching the criteria specified in the {querystring} parameter.

Options

The {queryString} parameter supports the following filter parameters - see Parameter section for more details

  • activeOnly

  • localOnly

  • includeConfig

  • includeError

Behavior

The selection is made from all replications across all nodes.

By default the response includes status data for replications in any state (starting, running, stopped or error) from across all nodes.

<h5>Example</h5>

 http://localhost:4985/{db}/_replicationStatus?activeOnly=false&localOnly=false&includeError=true

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Query

activeOnly
optional

When true, only active replications (state=starting, running, stopping) are returned

boolean

"false"

Query

includeConfig
optional

When true the replication definition is included in the response.

boolean

"false"

Query

includeError
optional

When false, omits replications stopped due to error (state=error)

By default the response includes replications in error state.

boolean

"true"

Query

localOnly
optional

When true returns only replications run (or running) the local node since startup.

By default the response includes replications run or running across all nodes since node start-up.

boolean

"false"

Responses
HTTP Code Description Schema

200

Returns information about the active replications

ReplicationStatusResponseBody

Returns information on specified replication

GET /{db}/_replicationStatus/{replicationID}
Description

Returns the status of the requested (replicationID) replication

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

replicationID
required

The {replicationID} parameter identifies the target replication.

string

Responses
HTTP Code Description Schema

200

Information about specified replication.

ReplicationStatusResponseBody

Modify replication status

PUT /{db}/_replicationStatus/{replicationID}
Description

Use this endpoint to change the status of the specified (replicationID) replication using the value of the action parameter.

The action parameter specifies the status to be set - valid values are

  • start - starts a stopped replication

  • stop - stops an active replication

  • reset - resets a stopped replication (resets checkpoint to zero). For bidirectional replication, both push and pull checkpoints are reset to zero.

For example

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Replicator

Parameters
Type Name Description Schema Default

Path

db
required

Database name

string

Path

replicationID
required

The {replicationID} parameter identifies the target replication.

string

Query

action
required

The value of the {action} parameter specifies the value you want the selected replication’s status set to.

Valid values are:

* start : Use this action to start a stopped replication

* stop : Use this action to stop a started replication

* reset : Use this action to reset a stopped replication. This will set the checkpoint to zero. For bidirectional replication, both push and pull checkpoints are reset to zero.

string

"none"

Responses
HTTP Code Description Schema

200

The required status is successfully set

ReplicationStatusResponseBody

Server

Manage server activities

Get Server Metadata

GET /
Description

Returns meta-information about the server.

Responses
HTTP Code Description Schema

200

Meta-information about the server.

Server

Get List of Active Tasks (v1 replications only)

GET /_active_tasks

operation.deprecated

Description

Deprecated @ 2.8

Replaced by Inter-Sync Gateway Replication (v2)'s [_replicationStatus](#/server/get__replicationStatus) endpoint. This _active_tasks endpoint is retained only for backward compatibility.

Use this end point to return the status of active Inter-Sync Gateway Replication (v1) replications. Only replications configured on the local node are returned.

The response is as defined in [_replicationStatus](#/replications/getdb_replicationStatus) except that it also includes:

  • end_last_seq, which returns the maximum of (last_seq_pull, last_seq_push)

  • start_last_seq, which is not populated (as was the case prior to Sync Gateway 2.8)

The Inter-Sync Gateway Replication (v2) equivalent is _replicationStatus?localOnly=true&activeOnly=true - see [_replicationStatus](#/replications/getdb_replicationStatus).

Responses
HTTP Code Description Schema

200

Information about active replications.

ActiveTasks_model

Get List of All Databases

GET /_all_dbs
Description

List all databases

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Responses
HTTP Code Description Schema

200

Identify all available databases

< AllDatabases > array

Get Server Configuration

GET /_config
Description

Returns the Sync Gateway configuration of the running instance. This is a good method to check if a particular key was set correctly on the config file.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Responses
HTTP Code Description Schema

200

Sync Gateway configuration of the running instance.

Bootstrap_model

Update Logging Options

PUT /_config
Description

Update bootstrap logging options without needing a restart

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Schema

Body

bootstrap logging setting
required

Logging_model

Responses
HTTP Code Description Schema

200

Returned updated Bootstrap logging settings

Logging_model

Get Sync Gateway Statistics

GET /_expvar
Description

The `Expvar`method returns a number of runtime variables that you can view for debugging or performance monitoring purposes.

This method can also be accessed using Sync Gateway’s Metrics REST API

See : Sync Gateway Statistics Schema for more details on the metrics collected and reported by Sync Gateway.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

  • External stats reader

Responses
HTTP Code Description Schema

200

OK - indicates success

ExpVars

Set Logging Tags

POST /_logging
Description

Enabling logging for a tag provides additional diagnostic information for that logging area.

The POST request only updates the tags specified in the request body.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Description Schema

Query

level
optional

Deprecated - please use logLevel instead This setting determines the verbosity of the logging - level=1 - The default, regular, logging - level=2 - Enables warnings and panics logging - level=3 - Will log panics only

integer

Query

logLevel
optional

This setting determines the verbosity of the logging.

Available values are - none - error - warn - info - debug - trace

Note that the setting is additive. For example, setting info will also enable both error and warn.

string

Body

log_keys
optional

Use the body to provide a list of the log keys you want to set.

For example - {"Changes++":true, "Cache":true, "HTTP":true, "DCP":true, "WS": true, "WSFrame": true, "Replicate": true}

log_keys

log_keys

Name Description Schema

Access
optional

Anytime an access() call is made in the sync function.

boolean

Admin
optional

Admin processes in Sync Gateway.

boolean

All
optional

Use the wildcard character to set all log keys For example {"":true}

boolean

Auth
optional

Authentication.

boolean

Bucket
optional

Sync Gateway interactions with the bucket (trace level only).

boolean

CRUD
optional

Updates made by Sync Gateway to documents.

boolean

Cache
optional

Interactions with Sync Gateway’s in-memory channel cache.

boolean

Changes
optional

Processing of /{db}/_changes requests.

boolean

DCP
optional

DCP-feed processing.

boolean

Events
optional

Event processing (webhooks).

boolean

HTTP
optional

All requests made to the Sync Gateway REST APIs.

boolean

HTTP+
optional

Additional information about HTTP requests (response times, status codes).

boolean

Import
optional

Introduced in Sync Gateway 1.5 to help troubleshoot the import process of a document (this is the Sync Gateway process to make a document that was added through N1QL or the Server SDKs mobile-aware). This log key can be useful to troubleshoot why a given document was not successfully imported.

boolean

Javascript
optional

All logging from Javascript. This includes - sync function, import filters, webhook filter function, and the custom ISGR conflict resolvers

boolean

Migrate
optional

Logs messages thhat show when old inline document metdata is upgraded to xattrs

boolean

Query
optional

Query is used for Sync Gateway code related to N1QL queries

boolean

Replicate
optional

Log messages related to replications between Sync Gateways (using sg-replicate). This tag cannot be used for replications initiated by Couchbase Lite.

boolean

SGCluster
optional

Log messages related to the sharded import and HA sg-replicate

boolean

Sync
optional

Activity which relates to synchronization between Couchbase Lite and Sync Gateway

boolean

SyncMsg
optional

Can be used for additional Sync logging output

boolean

WS
optional

Websocket replication log messages

boolean

WSFrame
optional

Can be used for additional WS logging output

boolean

gocb
optional

All logging emitted by the GoCB SDK

boolean

none
optional

Use "none" or "" as the key to disable all log keys. For example {"none":true}

boolean

Responses
HTTP Code Description Schema

201

The operation was successful

No Content

Get Logging Tags

GET /_logging
Description

Get logging tags of running instance.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Responses
HTTP Code Description Schema

200

The response is a set of key-value pairs. The key is a log tag and the value is a boolean to indicate whether this tag is enabled.

LogTags

Set Logging Tags

PUT /_logging
Description

Enabling logging for a tag provides additional diagnostic information for that logging area.

The PUT request replaces all existing logging tags with the ones specified in the request body.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Description Schema

Query

level
optional

Deprecated - please use logLevel instead This setting determines the verbosity of the logging - level=1 - The default, regular, logging - level=2 - Enables warnings and panics logging - level=3 - Will log panics only

integer

Query

logLevel
optional

This setting determines the verbosity of the logging.

Available values are - none - error - warn - info - debug - trace

Note that the setting is additive. For example, setting info will also enable both error and warn.

string

Body

log_keys
optional

Use the body to provide a list of the log keys you want to set.

For example - {"Changes++":true, "Cache":true, "HTTP":true, "DCP":true, "WS": true, "WSFrame": true, "Replicate": true}

log_keys

log_keys

Name Description Schema

Access
optional

Anytime an access() call is made in the sync function.

boolean

Admin
optional

Admin processes in Sync Gateway.

boolean

All
optional

Use the wildcard character to set all log keys For example {"":true}

boolean

Auth
optional

Authentication.

boolean

Bucket
optional

Sync Gateway interactions with the bucket (trace level only).

boolean

CRUD
optional

Updates made by Sync Gateway to documents.

boolean

Cache
optional

Interactions with Sync Gateway’s in-memory channel cache.

boolean

Changes
optional

Processing of /{db}/_changes requests.

boolean

DCP
optional

DCP-feed processing.

boolean

Events
optional

Event processing (webhooks).

boolean

HTTP
optional

All requests made to the Sync Gateway REST APIs.

boolean

HTTP+
optional

Additional information about HTTP requests (response times, status codes).

boolean

Import
optional

Introduced in Sync Gateway 1.5 to help troubleshoot the import process of a document (this is the Sync Gateway process to make a document that was added through N1QL or the Server SDKs mobile-aware). This log key can be useful to troubleshoot why a given document was not successfully imported.

boolean

Javascript
optional

All logging from Javascript. This includes - sync function, import filters, webhook filter function, and the custom ISGR conflict resolvers

boolean

Migrate
optional

Logs messages thhat show when old inline document metdata is upgraded to xattrs

boolean

Query
optional

Query is used for Sync Gateway code related to N1QL queries

boolean

Replicate
optional

Log messages related to replications between Sync Gateways (using sg-replicate). This tag cannot be used for replications initiated by Couchbase Lite.

boolean

SGCluster
optional

Log messages related to the sharded import and HA sg-replicate

boolean

Sync
optional

Activity which relates to synchronization between Couchbase Lite and Sync Gateway

boolean

SyncMsg
optional

Can be used for additional Sync logging output

boolean

WS
optional

Websocket replication log messages

boolean

WSFrame
optional

Can be used for additional WS logging output

boolean

gocb
optional

All logging emitted by the GoCB SDK

boolean

none
optional

Use "none" or "" as the key to disable all log keys. For example {"none":true}

boolean

Responses
HTTP Code Description Schema

201

The operation was successful

No Content

Delete Obsolete Design Documents

POST /_post_upgrade
Description

Starting in Sync Gateway 2.0, design documents used internally by Sync Gateway will include a version number in their name.

This version is incremented at each change, but the previous version of the design documents are retained, as they may be required by other nodes.

Use this _post_upgrade endpoint to remove any obsolete design documents when you are sure they are no longer needed.

TIP: Use the preview=true query string option to check which design documents will be removed.

Typical use cases for this end point include:

  • After upgrading Sync Gateway - see (upgrade guide).

  • After moving from non-import-docs to import-docs methods. That is, from import-docs=False to import-docs=True

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Description Schema Default

Query

preview
optional

Lists the design documents to be removed if the request is sent without this paramter.

boolean

"false"

Responses
HTTP Code Description Schema

200

The request was successful.

No Content

Start or Cancels Replication

POST /_replicate

operation.deprecated

Description

This API endpoint is now deprecated. It is replaced by the Inter-Sync Gateway Replication (v2) replication endpoint

About

This endpoint is used to start or cancel a database replication operation.

  • Starting a replication with the _replicate endpoint will implicitly set adhoc=true for the replication

  • Setting cancel=true will set the replication state to STOPPING

Canceling replications

You can cancel continuous replications by adding the cancel field to the JSON request object and setting the value to true.

Note that the structure of the request must be identical to the original for the cancellation request to be honoured. For example, if you requested continuous replication, the cancellation request must also contain the continuous field.

Constraints

  • Use this endpoint only for Inter-Sync Gateway Replication (v1) replications.

Parameters
Type Name Description Schema

Body

ReplicationBody
optional

SGR1 replication The request message body is a JSON document that contains the following objects.

ReplicationBody

ReplicationBody

Name Description Schema

cancel
optional

Indicates that a running replication task should be cancelled, the running task is identified by passing its replication_id or by passing the original source and target values.

boolean

changes_feed_limit
optional

The maximum number of change entries to pull in each loop of a continuous changes feed.

integer

continuous
optional

Specifies whether the replication should be in continuous mode.

boolean

filter
optional

Indicates that the documents should be filtered using the specified filter function name. A common value used when replicating from Sync Gateway is sync_gateway/bychannel to limit the pull replication to a set of channels.

string

query_params
optional

A set of key/value pairs to use in the querystring of the replication. For example, the channels field can be used to pull from a set of channels (in this particular case, the filter key must be set for the channels field to work as expected).

object

replication_id
optional

If the cancel parameter is true then this is the id of the active replication task to be cancelled, otherwise this is the replication_id to be used for the new replication. If no replication_id is given for a new replication it will be assigned a random UUID.

string

source
optional

Identifies the database to copy revisions from. Can be a string containing a local database name or a remote database URL, or an object whose url property contains the database name or URL. Also an object can contain headers property that contains custom header values such as a cookie.

string

target
optional

Identifies the database to copy revisions to. Same format and interpretation as source.

string

Responses
HTTP Code Description Schema

200

200 OK

ReplicationResponse

Start Sgcollect_info

POST /_sgcollect_info
Description

Starting in Sync Gateway 2.1, sgcollect_info can be triggered using this endpoint.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Description Schema

Body

sgcollect_info
optional

Options that can be specified to use in an sgcollect_info run

sgcollect_info

sgcollect_info

Name Description Schema

customer
optional

Customer name to use when uploading logs. required - if upload is set

string

output_dir
optional

Where to store the collected zip.
Default : "configured `LogFilePath location (for example /home/sync_gateway/logs)"`

string

redact_level
optional

Can be set to none or partial for redaction of collected logs.
Default : "none"

string

redact_salt
optional

If set, use this salt when redacting logs.

string

ticket
optional

Zendesk ticket number to use when uploading logs.

string

upload
optional

Whether to upload the collected logs.
Default : false

boolean

upload_host
optional

s3 URL for upload.
Default : "https://uploads.couchbase.com"

string

Responses
HTTP Code Description Schema

200

The request was successful.

No Content

Get Sgcollect_info Status

GET /_sgcollect_info
Description

Will return information about whether sgcollect_info is currently running or not.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Responses
HTTP Code Description Schema

200

The operation was successful

SGCollectInfoStats

Stop Sgcollect_info

DELETE /_sgcollect_info
Description

sgcollect_info can be cancelled using ths endpoint.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Dev Ops

Parameters
Type Name Description Schema

Body

sgcollect_info
optional

Options that can be specified to use in an sgcollect_info run

sgcollect_info

sgcollect_info

Name Description Schema

customer
optional

Customer name to use when uploading logs. required - if upload is set

string

output_dir
optional

Where to store the collected zip.
Default : "configured `LogFilePath location (for example /home/sync_gateway/logs)"`

string

redact_level
optional

Can be set to none or partial for redaction of collected logs.
Default : "none"

string

redact_salt
optional

If set, use this salt when redacting logs.

string

ticket
optional

Zendesk ticket number to use when uploading logs.

string

upload
optional

Whether to upload the collected logs.
Default : false

boolean

upload_host
optional

s3 URL for upload.
Default : "https://uploads.couchbase.com"

string

Responses
HTTP Code Description Schema

200

The request was successful.

No Content

Session

Manage user sessions

Create New Session

POST /{db}/_session
Description

If the credentials provided in the request body are valid, the session is created with an idle session timeout of 24 hours. An idle session timeout in the context of Sync Gateway is defined as the following: - If 10% or more of the current expiration time has elapsed when a subsequent request with that session id is processed, the session’s expiry time is automatically updated to 24 hours from that time.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Body

SessionBody
optional

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

SessionBody

SessionBody

Name Description Schema

name
optional

Username of the user the session will be associated to.

string

ttl
optional

Default is 24 hours (86400 seconds). The TTL (time-to-live) of the session, in seconds. The value must be greater than 0.
Example : 180

integer

Responses
HTTP Code Description Schema

200

Session successfully created.

Response 200

Response 200

Name Description Schema

cookie_name
optional

Cookie used for session handling

string

expires
optional

Expiration time for session.

string

session_id
optional

Session ID.

string

Get Session Data

GET /{db}/_session/{sessionid}
Description

This request retrieves information about a session.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

  • Sync Gateway Application Read Only

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

sessionid
required

Session id

string

Responses
HTTP Code Description Schema

200

200 OK - Request completed successfully.

Response 200

Response 200

Name Description Schema

authentication_handlers
optional

< object > array

ok
optional

Success flag

boolean

userCtx
optional

Contains an object with properties channels (the list of channels for the user associated with the session) and name (the user associated with the session)

object

Delete Specific Session

DELETE /{db}/_session/{sessionid}
Description

This request deletes a single session.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

sessionid
required

Session id

string

Responses
HTTP Code Description Schema

200

200 OK - Request completed successfully.

If the session is successfully deleted, the response has an empty message body. If the session is not deleted, the message body contains error information.

No Content

Delete All User Sessions

DELETE /{db}/_user/{name}/_session
Description

This request delete the session for the specified user.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

User’s name, may contain contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a user any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a user name in a URL path it must be escaped again using percent encoding for example if a user is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same user name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Responses
HTTP Code Description Schema

200

User session deleted.

No Content

Delete Specific User Session

DELETE /{db}/_user/{name}/_session/{sessionid}
Description

This request delete the specified session for the specified user.

Sync Gateway Roles Required (CBS 7.0.2 Developer Preview):

  • Sync Gateway Architect

  • Sync Gateway Application

Parameters
Type Name Description Schema

Path

db
required

Database name

string

Path

name
required

User’s name, may contain contain any combination of the characters [a-z A-Z 0-9 - + . @ %], when creating a user any other characters must be percent encoded, see: https://en.wikipedia.org/wiki/Percent-encoding.

When passing a user name in a URL path it must be escaped again using percent encoding for example if a user is created with the name "0|59", the '|' character must first be percent-encoded resulting in "0%7C59". When using the same user name in a URL path it must be percent-encoded a second time resulting in "0%257C59"

string

Path

sessionid
required

Session id

string

Responses
HTTP Code Description Schema

200

User session deleted.

No Content

Definitions

Bootstrap_model

Sync Gateway’s start-up configuration properties

Name Description Schema

api
optional

Define API related configuration properties

API configuration

auth
optional

Define Auth related configuration properties

Auth configuration

bootstrap
optional

Define fundamental bootstrap related configuration properties

Bootstrap configuration

logging
optional

Define logging configuration

Logging_model

max_file_descriptors
optional

Maximum number of open file descriptors.

integer

replicator
optional

Define Replicator related configuration properties

Replicator configuration

unsupported
optional

Collection of unsupported properties

Unsupported configuration

API configuration

Name Description Schema

admin_interface
optional

Port or TCP network address (IP address and the port) that the Admin REST API listens on.

The loopback address prefix before the port (127.0.0.1) means the interface will not be reachable from other hosts. To make it reachable, change it to ":4985".

Change requires restart of Admin API
Default : "127.0.0.1:4985"

string

admin_interface_authentication
optional

Use the admin_interface_authentication property to disable authentication for the metrics API. This option should be used with discretion and only in test environments.

By default the Admin API requires Couchbase Server RBAC authentication. The user must provide credentials to an existing user with an appropriate Sync Gateway role.
Default : true

boolean

compress_responses
optional

Whether to compress HTTP responses. Set to false to disable compression of HTTP responses.
Default : true

boolean

cors
optional

Configuration object for allowing cross-origin resource sharing (CORS). This is useful to interact directly with Sync Gateway from HTML 5 applications via XHR.

Change requires HTTP server restart

cors

hide_product_version
optional

Determines whether product versions are removed from Server headers and REST API responses. This setting does not apply to the Admin REST API.

This customization of the Sync Gateway response avoids revealing the version of the Sync Gateway to HTTP requests to the root path.
Default : false

boolean

https
optional

Group in which to specify any API HTTPS configuration properties

https

idle_timeout
optional

Maximum duration (in seconds) to wait for the next request when keep-alives are enabled

Change requires HTTP server restart

integer

max_connections
optional

Maximum number of incoming HTTP connections to accept.

Change requires HTTP server restart

integer

metrics_interface
optional

This defines the Port or TCP network address (IP address and the port) that the Metrics REST API will listen on.

Using the loopback address prefix before the port (127.0.0.1) means the interface will not be reachable from other hosts.

For example "metricsInterface": "127.0.0.1:4986"
Default : "127.0.0.1:4986"

string

metrics_interface_authentication
optional

Use the metrics_interface_authentication property to disable authentication for the metrics API. This option should be used with discretion and only in test environments.

By default the Metrics API requires Couchbase Server RBAC authentication. The user must provide credentials to an existing user with an appropriate Sync Gateway role.
Default : true

boolean

pretty
optional

(Deprecated) Whether to pretty-print JSON responses.
Default : false

boolean

profile_interface
optional

TCP network address (IP address and the port) that the Go profile API listens on. You can obtain Go profiling information from the interface. You can omit the IP address.

string

public_interface
optional

Public REST API port

Change requires restart of Public API
Default : ":4984"

string

read_header_timeout
optional

Maximum duration (in seconds) allowed to read request headers

Change requires HTTP server restart

integer

server_read_timeout
optional

Maximum duration in seconds before timing out the read of an HTTP(S) request.

This property only effects the HTTP connections on the Sync Gateway public and admin ports.

Sync Gateway is written in the Go programming language, therefore the value set in the configuration file is passed to Go’s server instance https://golang.org/pkg/net/http/#Server.

Change requires HTTP server restart

integer

server_write_timeout
optional

Maximum duration in seconds before timing out the write of an HTTP(S) response.

This property only effects the HTTP connections on the Sync Gateway public and admin ports.

Sync Gateway is written in the Go programming language, therefore the value set in the configuration file is passed to Go’s server instance https://golang.org/pkg/net/http/#Server.

Change requires HTTP server restart

integer

cors

Name Description Schema

headers
optional

List of HTTP headers that can be used by domains specified in the origin and login_origin properties.

A common value is ["Content-Type"] as clients use the Content-Type: application/json header when sending data as JSON in the body of POST/PUT requests.

Change requires HTTP server restart

< string > array

login_origin
optional

List of allowed login origins.

Change requires HTTP server restart

< string > array

max_age
optional

Value for the Access-Control-Max-Age header. This is the period of time, in seconds, that the response to a CORS preflight request is cached before sending another preflight request.

Change requires HTTP server restart

integer

origin
optional

List of allowed origins; use a wildcard character () to allow access from everywhere.

*Note that the wildcard (*) cannot be used if you plan to authenticate users as well (by using the withCredentials flag on the client side). Instead specify the explicit domain(s) in the origin and login_origin properties of the configuration file.

Change requires HTTP server restart

< string > array

https

Name Description Schema

tls_cert_path
optional

Absolute or relative path on the filesystem to the TLS certificate file, if TLS is used to secure Sync Gateway connections

To use plaintext, omit both this property and the tls_key_path property.

A relative path is from the directory that contains the Sync Gateway executable file.

Change requires HTTP server restart

string

tls_key_path
optional

Absolute or relative path on the filesystem to the TLS private key files.

To use plaintext, omit both this property and the tls_cert_path property.

A relative path is from the directory that contains the Sync Gateway executable file.

Change requires HTTP server restart

string

tls_minimum_version
optional

Enforce a minimum TLS version to be used in replications with Couchbase Lite.

Possible values are:

* "tlsv1"

* "tlsv1.1"

* "tlsv1.2"

* "tlsv1.3"

Change requires HTTP server restart
Default : "tlsv1.2"

string

Auth configuration

Name Description Schema

bcrypt_cost
optional

Cost to use for bcrypt password hashes

integer

Bootstrap configuration

Name Description Schema

ca_cert_path
optional

Absolute or relative path on the filesystem to the root CA certificate to verify the certificate chain and hostname of the Couchbase Server cluster.

Works in conjunction with server_tls_skip_verify to control whether system root pool is used or not. Set this empty and server_tls_skip_verify true to avoid using system root pool

string

config_update_frequency
optional

Sets the interval between checks for new or updated configurations made by other nodes in Couchbase Server

It is provided as string, which uses Go’s duration format (e.g: 1s = 1 second, 5m = 5 minutes , 1h32m15s = 1 hour, 32 mins, 15 seconds) see: https://pkg.go.dev/time#ParseDuration
Default : "10s"

string

group_id
optional

The ID of the configuration group to which this node belongs.
Default : "default"

string

kv_tls_port
optional

Optional value for the Memcached TLS port, if not using the default (11207)

integer

max_concurrent_query_ops
optional

Sets the maximum number of concurrent query operations allowed

integer

password
optional

The password to be used when authenticating to the server.
Default : "none"

string

server
optional

Sets the endpoint for the Couchbase Server holding (database) configuration details.

The value of the server property specifies the Hostname(s) to the Couchbase Server node(s) in the cluster.

Sync Gateway supports the ability to specify multiple hosts in the configuration. Sync Gateway supports both the couchbase:// and http:// schemes for specifying connection endpoints.

Sync Gateway also supports SSL in the connection to Couchbase Server; use the couchbases:// scheme for this. As with the Couchbase Server SDKs, the https:// scheme is not supported.

Examples of valid server values for IPv4 include: - couchbase://host1 - couchbases://host1 - couchbase://host1,host2 - couchbase://host1:11210,host2, - couchbases://host1:11207,host2 - http://host1:8091 - http://host1,host2:8091 - http://foo:bar@host1:8091

Examples of valid server values for IPv6 include: - http://[2001:db8::8811]:8091 // single node IPv6 - http scheme with default server port - couchbases://[2001:db8::8811] // single node SSL IPv6 - default port (omitted) - couchbase://[2001:db8::8811],[2001:db8::8822]:888 // node1 default port, node2 port 888

As with the SDK, when using the couchbase:// or couchbases:// schemes, the port is not required, but if specified should be the external/internal bucket ports (defaults are 11210 or 11207 respectively). Attempting to use the admin ports (8091/18091) will result in a startup error.

Alternate Addresses

On startup, Sync Gateway will try each hostname that is provided until it is able to connect successfully.

By default, if a remote cluster has an external address set, then when SG connects it will apply a heuristic to determine whether to choose between external or default (internal) addresses.

The choice is based on the host names supplied in the connection string. - SG uses external networking only when none of the supplied host names match any of Couchbase Server’s internal node addresses, and an external address is defined. - In all other cases Sync Gateway uses the default (internal) networking.

However, it is possible to override this behavior by adding a network parameter to the connection string.

The network parameter can be – - auto - this is the default value if no parameter is provided. In this case the heuristic described above is applied to determine the address used; so effectively there is no override. - external - to always force use of the external address - default - to always force use of the internal address

For example: "server": "couchbases://my-cbs-server?network=default"

Will force the connection to ignore any alternative external addresses configured on the Couchbase Server node.

Lost Connections

If the connection to Couchbase Server is lost during normal operations, Sync Gateway will automatically re-connect to another node in the cluster. During that re-connection period, the Sync Gateway will appear offline - see Taking Databases Offline - and documents will not be replicated to mobile clients.
Default : "none"

string

server_tls_skip_verify
optional

Defaults to false, which requires a valid CA Cert Path. Works in conjunction with ca_cert_path to control whether system root pool is used or not. Set this true and ca_cert_path empty to allow, for example, self-signed or un-trusted certificates. This will be the default of-of-the-box setting.

boolean

use_tls_server
optional

Default to true, which forces the connection to Couchbase Server to use TLS.

Use use_tls_server to enforce use of a secure scheme (for example, couchbases://) to connect to Couchbase Server.

Set this false to use a non-secure scheme (for example with couchbase://).

If the scheme used does not match that indicated by the use_tls_server value (for example, couchbases:// with use_tls_server = false) then Sync Gateway will error and refuse to start.
Default : true

boolean

username
optional

The username to be used when authenticating to the server.
Default : "none"

string

x509_cert_path
optional

Use x509_cert_path to define the absolute or relative path on the filesystem to the x509 certificate.

Relative paths are relative to the directory containing the Sync Gateway executable.

string

x509_key_path
optional

Absolute or relative path on the filesystem to the X509 key.

Relative paths are relative to the directory containing the Sync Gateway executable.

string

Replicator configuration

Name Description Schema

blip_compression
optional

This sets the 'deflate' compression level to use when compressing messages sent via the WebSocket protocol, where:

* 0 means no compression, * 1 means fastest (least) compression * 9 means slowest (most) compression.

integer

max_heartbeat
optional

This specifies the Maximum Heartbeat value for the _changes feed requests; the time in second between heartbeats. - The default value of maxHeartbeat is 0 (zero) - The minimum value of maxHeartbeat is 25 (25,000 ms)

integer

Unsupported configuration

Name Description Schema

http2.enabled
optional

Default : false

boolean

stats_log_freq
optional

It is provided as string, which uses Go’s duration format (e.g: 1s = 1 second, 5m = 5 minutes , 1h32m15s = 1 hour, 32 mins, 15 seconds) see: https://pkg.go.dev/time#ParseDuration
Default : "1m"

string

use_stdlib_json
optional

Default : false

boolean

Logging_model

Holding object for all logging-related settings.

Note that in addition to setting these logging values in the bootstrap configuration file, you can also use the ADMIN Rest API to set or change the values without requiring a full reload. See: Rest Admin API

A full logging initialization is required.

See the Logging page for a fuller explanation on logging settings.

Name Description Schema

console
optional

Settings for the console output logging.

console

debug
optional

The debug logging-level provides lower level development analysis

* Minimum max_age is 1 day _ Log File Name is sg_debug.log

debug

error
optional

Activate the error logging level - see Logging page for more on log levels.

error

info
optional

The information logging-level provides important diagnostics for support and customers

info

log_file_path
optional

Absolute or relative path on the filesystem to the log file. A relative path is from the directory that contains the Sync Gateway executable file.

Changes require full logging re-initialization

string

redaction_level
optional

Optionally, log files can be redacted. This means that user-data, considered to be private, is removed. Such data includes:

* Key/value pairs in JSON documents

* Usernames

* Query-fields that reference key/value pairs and/or usernames

* Names and email addresses retrieved during product registration

* Extended attributes

This redaction of user-data is referred to as partial redaction.

To enable it, set this property to "redaction_level" : "partial" in the configuration file:
Default : "none"

string

stats
optional

The stats logging level

stats

trace
optional

The trace logging-level.

trace

warn
optional

The warning logging-level is triggered when Sync Gateway detects something is wrong but it can still service requests

* Minimum max_age is 90 days

* Log File Name is sg_warn.log

warn

console

Name Description Schema

collation_buffer_size
optional

Size of the collation buffer

integer

color_enabled
optional

Use ANSI color codes in the console output (Linux/MacOS only).
Default : false

boolean

enabled
optional

Indicates whether console logging is enabled

boolean

file_output
optional

Changes require full logging re-initialization

string

log_keys
optional

List of log keys to enable for diagnostic logging.

Available log key values are described in the Log Keys page

< string > array

log_level
optional

The level of logging.

Log levels are cumulative (that is, log entries at WARN will also be included in the INFO and DEBUG logs).

See: Log Levels page
Default : "info"

string

rotation
optional

The log file may be rotated by defining a "rotation" sub document. See details in log rotation.

rotation

rotation

Name Description Schema

localtime
optional

If true, it uses the computer’s local time to format the backup timestamp. False uses UTC.
Default : false

boolean

max_age
optional

The maximum number of days to retain old log files. This can’t be set below the minimum allowed value for the given level.

integer

max_size
optional

The maximum size in MB of the log file before it gets rotated.

integer

rotated_logs_size_limit
optional

Controls how much disk space the rotated (and compressed) log files for this level can take up.

The value is expressed in megabytes. The minimum value is 10 and there is no maximum value.

integer

debug

Name Description Schema

collation_buffer_size
optional

Size of the collation buffer

integer

enabled
optional

Sets this logging-level on or off.

Note, you are advised to keep this log level enabled when troubleshooting issues. Enabling this log level is a requirement to receive Enterprise Support.
Default : false

boolean

rotation
optional

The log file may be rotated by defining a "rotation" sub document. See details in log rotation.

rotation

rotation

Name Description Schema

localtime
optional

If true, it uses the computer’s local time to format the backup timestamp. False uses UTC.
Default : false

boolean

max_age
optional

The maximum number of days to retain old log files. This can’t be set below the minimum allowed value for the given level.

integer

max_size
optional

The maximum size in MB of the log file before it gets rotated.

integer

rotated_logs_size_limit
optional

Controls how much disk space the rotated (and compressed) log files for this level can take up.

The value is expressed in megabytes. The minimum value is 10 and there is no maximum value.

integer

error

Name Description Schema

collation_buffer_size
optional

Size of the collation buffer

integer

enabled
optional

Enable this error log level.

* The error, warn and info log levels are enabled by default.

* The debug log level is disabled by default.

Note: You are advised to keep this log level enabled to troubleshoot issues.

Enabling this log level is a requirement to receive Enterprise Support.

boolean

rotation
optional

The log file may be rotated by defining a "rotation" sub document.

See details in log rotation.

rotation

rotation

Name Description Schema

localtime
optional

If true, it uses the computer’s local time to format the backup timestamp. False uses UTC.
Default : false

boolean

max_age
optional

The maximum number of days to retain old log files. This can’t be set below the minimum allowed value for the given level.

integer

max_size
optional

The maximum size in MB of the log file before it gets rotated.

integer

rotated_logs_size_limit
optional

Controls how much disk space the rotated (and compressed) log files for this level can take up.

The value is expressed in megabytes. The minimum value is 10 and there is no maximum value.

integer

info

Name Description Schema

collation_buffer_size
optional

Size of the collation buffer

integer

enabled
optional

Whether to enable this log level.
Default : true

boolean

rotation
optional

The log file may be rotated by defining a "rotation" sub document

rotation

rotation

Name Description Schema

localtime
optional

If true, it uses the computer’s local time to format the backup timestamp. False uses UTC.
Default : false

boolean

max_age
optional

The maximum number of days to retain old log files. This can’t be set below the minimum allowed value for the given level.

integer

max_size
optional

The maximum size in MB of the log file before it gets rotated.

integer

rotated_logs_size_limit
optional

Controls how much disk space the rotated (and compressed) log files for this level can take up.

The value is expressed in megabytes. The minimum value is 10 and there is no maximum value.

integer

stats

Name Description Schema

collation_buffer_size
optional

Size of the collation buffer

integer

enabled
optional

Whether to enable this log level.
Default : false

boolean

rotation
optional

The log file may be rotated by defining a "rotation" sub document. See details in log rotation.

rotation

rotation

Name Description Schema

localtime
optional

If true, it uses the computer’s local time to format the backup timestamp. False uses UTC.
Default : false

boolean

max_age
optional

The maximum number of days to retain old log files. This can’t be set below the minimum allowed value for the given level.

integer

max_size
optional

The maximum size in MB of the log file before it gets rotated.

integer

rotated_logs_size_limit
optional

Controls how much disk space the rotated (and compressed) log files for this level can take up.

The value is expressed in megabytes. The minimum value is 10 and there is no maximum value.

integer

trace

Name Description Schema

collation_buffer_size
optional

Size of the collation buffer

integer

enabled
optional

Whether to enable this log level.
Default : false

boolean

rotation
optional

The log file may be rotated by defining a "rotation" sub document. See details in log rotation.

rotation

rotation

Name Description Schema

localtime
optional

If true, it uses the computer’s local time to format the backup timestamp. False uses UTC.
Default : false

boolean

max_age
optional

The maximum number of days to retain old log files. This can’t be set below the minimum allowed value for the given level.

integer

max_size
optional

The maximum size in MB of the log file before it gets rotated.

integer

rotated_logs_size_limit
optional

Controls how much disk space the rotated (and compressed) log files for this level can take up.

The value is expressed in megabytes. The minimum value is 10 and there is no maximum value.

integer

warn

Name Description Schema

collation_buffer_size
optional

Size of the collation buffer

integer

enabled
optional

Whether to enable this log level. The error, warn and info log levels are enabled by default. The debug log level is disabled by default.

Note, however, that you are advised to keep this log level enabled to troubleshoot issues. Enabling this log level is a requirement to receive Enterprise Support.

boolean

rotation
optional

The log file may be rotated by defining a "rotation" sub document. See details in log rotation.

rotation

rotation

Name Description Schema

localtime
optional

If true, it uses the computer’s local time to format the backup timestamp. False uses UTC.
Default : false

boolean

max_age
optional

The maximum number of days to retain old log files. This can’t be set below the minimum allowed value for the given level.

integer

max_size
optional

The maximum size in MB of the log file before it gets rotated.

integer

rotated_logs_size_limit
optional

Controls how much disk space the rotated (and compressed) log files for this level can take up.

The value is expressed in megabytes. The minimum value is 10 and there is no maximum value.

integer

Database_model

This database object defines the JSON configuration of a sync gateway database.

Provision the configuration using the request message body of a put /{db}/ and-or put /{db}/_config that comprises all the properties required to upsert a replication.

Name Description Schema

allow_conflicts
optional

Use allow_conflict to define whether Sync Gateway will handle conflicts.

The default of true indicates that conflicts are handled.

Set the value to false to cause Sync Gateway to reject any attempt to write conflicting revisions (returning a 409 HTTP status code). It will be up to the client to resolve the conflict.

Restarting Sync Gateway with this property enabled will not automatically result in disk space savings (compaction on a document won’t occur until a document is updated).

Constraints: - Push replications to pre-2.8 targets do not support the "allow_conflicts": false setting; the target must use "allow_conflicts": true.

Change initiates a database restart.
Default : true

boolean

allow_empty_password
optional

Use allow_empty_password to define whether to Sync Gateway users can be created with empty passwords.
Default : false

boolean

bucket
optional

Defines the Couchbase Server bucket to be used for this Sync Gateway database bucket

If not specified, then the database name is used as the bucket name.
Default : "the database name"

string

bucket_op_timeout_ms
optional

Use bucket_op_timeout_ms to define how long Sync Gateway will wait for a bucket operation to complete before timing out and trying again.

You may increase this value where there is a heavy load on Couchbase Server and operations are likely to take more than 2.5 seconds to complete.

The default value is 2500 milliseconds.

Changes initiate a database restart.

integer

cache
optional

The cache group of properties define the configuration for this database’s channel and revision caches

Cache

client_partition_window_secs
optional

Use the client_partition_window_secs property to define how long clients can remain offline for without losing replication metadata.

Default 2 592 000 seconds (30 days)
Default : "2592000"

string

compact_interval_days
optional

Use `` property to define the interval between scheduled compaction runs (in days).

Set a zero (0) value to suppress running compactions.

Change initiates a database restart.

number

delta_sync
optional

NOTE: Delta Sync is an Enterprise Edition feature on Sync Gateway and Couchbase Lite.

Use the delta_sync object to specify the delta sync configuration properties.

In this context, delta-sync, is the ability to replicate only those parts of a Couchbase mobile document that have changed. This results in significant savings in bandwidth consumption as well as throughput improvements; both useful benefits when network bandwidth is typically constrained.

Delta Sync does not apply to attachment contents.

Delta Sync is disabled by default on the Sync Gateway. You can enable it through the enabled property.

If delta sync is enabled on Sync Gateway, then Couchbase Lite clients will switch to using delta sync automatically. Similarly, if delta sync is disabled on Sync Gateway, clients will switch to normal mode.

Changes initiate a database reload

Delta Sync

enable_shared_bucket_access
optional

Use the enable_shared_bucket_access property to define whether to use extended attributes to store sync metadata. This is required to enable mobile-to-server data sync (mobile convergence).

You can learn more about this functionality in Syncing with Couchbase Server

This property works in conjunction with the import_docs property, which determines whether a node participates in import processing. Leave enable_shared_bucket_access true on all nodes participating in such a configuration.

On start-up, Sync Gateway will generate the mobile-specific metadata for all the pre-existing documents in the Couchbase Server bucket. From then on, documents can be inserted on the Server directly (with N1QL or SDKs) or through the Sync Gateway REST API.

Change initiates a database restart
Default : true

boolean

event_handlers
optional

Webhooks in Sync Gateway are designed to minimize performance impacts on Sync Gateway’s regular processing.

Sync Gateway manages the number of processes that are spawned for webhook event handling, so that slow response times from the HTTP POST operations don’t consume available CPU resources on Sync Gateway nodes.

When a webhook event handler is defined, after Sync Gateway has updated a document, Sync Gateway adds a document_changed event to an asynchronous event-processing queue (the event queue).

New processes are then spawned to apply the filter function to the documents and to perform the HTTP POST operations.

When an event is not added to the event queue, but is instead discarded, a warning message is written to the the Sync Gateway log.

You can configure Sync Gateway to log information about event handling, by including either the log key Event or Events+ in the Log property in your Sync Gateway configuration file. Events+ is more verbose.

See also: Webhook..

Event Handler

guest
optional

Defines whether a GUEST user is available and able to interacted, unauthenticated, with the Public REST API

guest

import_backup_old_rev
optional

Use the import_backup_old_rev property to define whether import should attempt to create a temporary backup of the previous revision body, when available

string

import_docs
optional

Use the import_docs property to define whether the Sync Gateway node should automatically import Couchbase Server documents;

This property works in conjunction with the enable_shared_bucket_access property, which enables Xattrs.

Since Sync Gateway 2.7, all Sync Gateway nodes can be configured as import nodes. This results in performance benefits as the import process is shared across all Sync Gateway nodes.

Prior to version 2.7, import_docs can only be set to true on a single node.

Changes initiate a database restart
Default : false

boolean

import_filter
optional

Import_filter_model

import_partitions
optional

Use the import_partitions property to define how many import partitions should be used for import sharding.

Partitions are distributed among all Sync Gateway nodes participating in import processing (import_docs:true), and each process a subset of the server’s vbuckets.

Each partition is processed by a separate goroutine, so import_partitions can be used to tune concurrency based on the number of Sync Gateway nodes, and the number of cores per node.

integer

isgr_enabled
optional

Use the isgr_enabled property to define whether this Sync Gateway node can be assigned inter-Sync Gateway replications for this database.

If set to false, the Sync Gateway node will not participate in inter-Sync Gateway replications.
Default : true

boolean

isgr_websocket_heartbeat_secs
optional

If set, this duration (in seconds) is used as a custom heartbeat interval for websocket ping frames in inter-Sync Gateway replications.

integer

local_doc_expiry_secs
optional

Use the local_doc_expiry_secs property to define an expiry value for local documents managed on Sync Gateway.

Local documents are used by the Couchbase Lite replicator to track up to which sequence number a given client has synchronized and where it should resume the next time it connects to Sync Gateway.

Clients failing to replicate within the expiry window are forced to restart their replication from the beginning (sequence zero).

This property is intended to minimize accumulation of obsolete replication checkpoint documents in the Couchbase Server bucket.

The default is 7776000 seconds (90 days).

integer

name
optional

Use name to define the Sync Gateway database name.

Change initiates database restart

string

num_index_replicas
optional

use num_index_replicas property to define the number of index replicas used when creating the core Sync Gateway indexes.

Only applicable if databases.$db.use_views is set to false (default value).

Change initiates a database restart.

integer

offline
optional

Use offline to determine whether Sync Gateway should start the database in offline mode.

The default of false means the database will be online.
Default : false

boolean

oidc
optional

Use the oidc object properties to defined any OpenID Connect providers and associated credentials.

OIDC Group

old_rev_expiry_seconds
optional

Use the old_rev_expiry_seconds property to define the number of seconds before old revisions are removed from Couchbase Server buckets.

integer

query_pagination_limit
optional

Use the query_pagination_limit property to define the Query limit to be used during pagination of large queries.

Change initiates a database restart.

integer

revs_limit
optional

This property defines the maximum depth to which a document’s revision tree can grow.

It value governs the point at which to prune a document’s revision tree.

For more information see: Revisions page.

integer

send_www_authenticate_header
optional

Whether to send WWW-Authenticate header in 401 responses.
Default : true

boolean

serve_insecure_attachment_types
optional

The sending of a content-disposition header for attachments with headers such as "text/html" forces a download, rather than browser rendering.

Use this option to suppress sending the content-disposition, allowing the browser to render the attachment.
Default : false

boolean

session_cookie_http_only
optional

This flag disallows cookies from being used by Javascript; by default javascript CAN use them
Default : false

boolean

session_cookie_name
optional

Starting in Sync Gateway 2.0, it is possible to customize the session cookie name that is used for this database.

This property is mostly used by web applications interacting with multiple Sync Gateway databases.

Browsers typically have two methods of determining which cookie to use for a given request: the URL path, or the cookie name.

Use this property, to set different cookie names for each database specified in the configuration file. Let’s consider the following configuration file:

[source,json] ---- { "databases": { "db1": { "session_cookie_name": "CustomName1", "bucket": "bucket-1" }, "db2": { "session_cookie_name": "CustomName2", "bucket": "bucket-2" } } } }

----

With this configuration, the Set-Cookie response header of the POST :4984/{db}/_session endpoint (Public REST API) would then have the form "CustomName1=3cad4b95524179bf144fe0d92b8f09877bb86bf5;path=/db1/".

When using POST :4985/{db}/_session (Admin REST API) to create a session, the cookie value is returned in the response body instead of the Set-Cookie header. In this case, it could also be set by the client, for web applications it would be the following in JavaScript:

[source,javascript] ---- cookie1String = "CustomName1=3cad4b95524179bf144fe0d92b8f09877bb86bf5;path=/db1/"; document.cookie = cookie1String; ----
Default : "SyncGatewaySession"

string

session_cookie_secure
optional

Override secure cookie flag (that is, disable secure cookies).

If SSLCert is set, then secure cookies are also used by default. However, this flag can be set false to override this behavior and allow insecure cookies to be used alongside SSL.

If SSLCert is not set then this flag defaults to false.
Default : true

boolean

slow_query_warning_threshold
optional

The maximum wait time, in milliseconds,for N1QL or View queries made by Sync Gateway

Log warnings if the run time of a N1QL or View query, made by Sync Gateway, exceeds this value.

integer

sync
optional

Sync_model

unsupported
optional

This group comprises an unrelated collection of unsupported properties that may, potentially, be useful in controlled testing scenarios.

NOTE: Due to the unsupported nature of these options, there is no guarantee on their continued availability.

Unsupported Properties Model

use_views
optional

If set to true, Sync Gateway will use views instead of GSI for system functions like authentication and replication.
Default : false

boolean

user_xattr_key
optional

The user_xattr_key identifies the user xattr used to hold the channel access grants for documents in this database.

If it is not specified or its value is spaces or null then this feature is disabled (default).

If you change the value of this key, no existing grant assignments will be changed until a document mutation is triggered. This can be done in a number of ways: - a mutation to the document which we’ll see via DCP - an on-demand import either through write or get - by using the resync function.

Dependencies: The user_xattr_key feature requires that –

* enable_shared_bucket_access be = true

* xattrs be supported on the connected Couchbase Server

Change initiates a database restart
Default : "none"

string

view_query_timeout_secs
optional

Use the view_query_timeout_secs property to define the view query timeout in seconds.

This is the time Sync Gateway should wait for a view query response from Couchbase Server before it times out.

The timeout applies to both view and N1QL queries issued by Sync Gateway.

integer

Cache

Name Description Schema

channel_cache
optional

Use the channel_cache group’s properties to configure the database’s channel cache

Changes initiate a database restart

Channel Cache

rev_cache
optional

Use the rev_cache properties to configure the revision cache

Revision Cache

Channel Cache

Name Description Schema

compact_high_watermark_pct
optional

Use compact_high_watermark_pct to define the trigger value for starting channel cache eviction. Specify the value as a percentage (of max_number)

When the cache size, determined by max_number, reaches the high watermark, the eviction process iterates through the cache, removing inactive channels.

integer

compact_low_watermark_pct
optional

Use compact_low_watermark_pct to define the trigger value for stopping channel cache eviction. Specify the value as a percentage (of max_number)

When the cache size, determined by max_number returns to a value lower than compact_low_watermark_pct, the cache eviction process is stopped.

integer

enable_star_channel
optional

Use enable_star_channel to define whether Sync GAteway should use the all documents (*) channel - sometimes referred to as the 'star' channel.
Default : true

boolean

expiry_seconds
optional

Use expiry_seconds to define how long (in seconds) Sync Gateway should keep cached entries beyond the minimum retained.

integer

max_length
optional

Maximum number of entries maintained in cache per channel.

integer

max_num_pending
optional

Use max_num_pending to define the maximum number of pending sequences before skipping the sequence.

integer

max_number
optional

Use max_number to define the maximum number of channel caches allowed at any one point. This property is used alongside the associated eviction watermarks compact_low_watermark_pct and compact_high_watermark_pct to control the cache size.

The default value for this property is 50000. Assuming the default channel min_length and max_length values, this would result in a memory usage under 1GB.

Tuning this property is an Enterprise Edition feature - in the Community Edition any change to the default value is ignored.

Enterprise Edition Only: The max_number value can be tuned to optimize for cache hits (requests that are handled using the cache), as opposed to cache misses (requests that require a round-trip to Couchbase Server to fetch data). The cache hit/miss ratio can be obtained with the following:

cache hit/miss ratio = cache.chan_cache_hits / cache.chan_cache_misses

Increasing the max_number value can increase the cache hit/miss ratio, resulting in better cache utilization.

If the cache size grows to reach the high watermark (compact_high_watermark_pct), channels with no connected replications will be evicted before channels which are associated with an active pull replication (i.e a blip-based pull replication in Couchbase Lite 2.x, or an active /{db}/_changes request in Couchbase Lite 1.x).

The minimum allowed value is 100.

It isn’t possible to remove the limit altogether, users who wish to remove the limit would need to set max_number to an arbitrarily high value.

integer

max_wait_pending
optional

Maximum wait time in milliseconds for a pending sequence before skipping sequences.

integer

max_wait_skipped
optional

Maximum wait time in milliseconds for a skipped sequence before abandoning the sequence.

integer

min_length
optional

Minimum number of entries maintained in cache per channel.

integer

query_limit
optional

Limit used for channel queries

integer

Revision Cache

Name Description Schema

shard_count
optional

Tuning this property is an Enterprise Edition feature. The Community Edition is configured with the default value, and will ignore any value in the configuration file.

Number of shards the rev cache should be split into. More shards allows for lower cache contention when accessing distinct revisions, at the cost of some memory overhead per-shard. This generally should not greatly exceed the number of CPU threads available to Sync Gateway.

It is generally not recommended to set this property, unless advised by Couchbase Enterprise Support.

integer

size
optional

Size of the revision cache, specified as the total number of document revisions to cache in memory for all recently accessed documents.

When the revision cache is full, Sync Gateway removes less recent document revisions to make room for new document revisions. Adjust this property to tune memory consumption by Sync Gateway, for example on servers with less memory and in cases when Sync Gateway creates many new documents and/or updates many documents relative to the number of read operations.

Disabling the revision cache

Disabling the revision cache is an Enterprise Edition feature.

To disable the revision entirely, set this property to 0. Setting this property to 0 on the Community Edition is ignored.

Disabling the revision cache would be useful when there are very large documents or if you expect a very low cache hit rate. Otherwise it could negatively impact the latency of replications. It is generally not recommended to disable the revision cache, unless advised by Couchbase Enterprise Support.

integer

Delta Sync

Name Description Schema

enabled
optional

Use the delta_sync.enabled property to turn delta sync mode on or off for the given database.

The following configuration example enables delta sync.

[source,json] ---- { "databases": { "db": { "delta_sync": { "enabled": true, "rev_max_age_seconds": 86400 } } } } ----

Footnotes

* Use of Delta Sync incurs additional bucket storage requirements which can be tuned with the rev_max_age_seconds property.

* Delta Sync is automatically enabled for peer-to-peer sync between Couchbase Lite clients.

* Delta sync is disabled for Couchbase Lite database replicas.

* Push replications do not use Delta Sync when pushing to a pre-2.8 target.
Default : false

boolean

rev_max_age_seconds
optional

Use delta_sync.rev_max_age_seconds to adjust the time box within which deltas can be generated.

On a write operation, the revision body is backed up in the bucket and retained for rev_max_age_seconds to calculate future revision deltas. As a result, new deltas can only be generated for read requests that come in within the rev_max_age_seconds time window. The storage of backed up revision bodies for delta sync incurs additional bucket storage requirements.

The additional storage can be calculated with the following formula: (doc_size * updates_per_day * 86400) / rev_max_age_seconds.

For example, with rev_max_age_seconds’s default value, an average document size of 4 KB and 100 writes/day, enabling delta sync would take up an additional 400 KB of storage on Couchbase Server ((4 * 100 * 86400)/86400`).

Setting this value to 0 will generate deltas opportunistically on pull replications, with no additional storage requirements.

integer

Event Handler

Name Description Schema

db_state_changed
optional

Use the db_state_changed property group to define the actions to perform when a db_state change is detected.

db_state_changed model

document_changed
optional

The configuration for the action to perform when a document change is detected.

Document Changed

max_processes
optional

Maximum number of events that can be processed concurrently, that is, no more than max_processes concurrent processes will be spawned for event handling.

The default value should work well in the majority of cases. You should not need to adjust it to tune performance. However, if you wish to ensure that most webhook posts are sent, you can set it to sufficiently high value.

integer

wait_for_process
optional

Maximum wait time in milliseconds before canceling event processing for an event that is detected when the event queue is full.

If you set the value to 0 (zero), then incoming events are discarded immediately if the event queue is full.

If you wish to avoid any blocking of standard Sync Gateway processing this may be a desirable value to use.

The default value should work well in the majority of cases. You should not need to adjust it to tune performance.
Default : "100"

string

db_state_changed model

Name Description Schema

filter
optional

Use db_state_changed.filter`` to define a JavaScript function that determines which state changes to post.

string

handler
optional

Specify the type of event handler.

This must be webhook currently).

string

options
optional

Options can be specified per-handler, and are specific to each handler type.

string

timeout
optional

Defines the period in seconds to wait for a response to the operation. Default: 60

integer

url
optional

Defines the URL to post to (for a webhook event handler).

string

Document Changed

Name Description Schema

filter
optional

Use document_changed.filter to define a JavaScript function that determines which documents to post.

The filter function accepts the document body as input and returns a boolean value.

* If the filter function returns true, then Sync Gateway posts the document.

* If the filter function returns false, then Sync Gateway does not post the document.

* If no filter function is defined, then Sync Gateway posts all changed documents.

Filtering only determines which documents to post. It does not extract specific content from documents and post only that.

string

handler
optional

Specify the type of event handler.

This must be webhook currently).

string

options
optional

Options can be specified per-handler, and are specific to each handler type.

string

timeout
optional

Defines the period in seconds to wait for a response to the POST operation.

Using a timeout ensures that slow-running POST operations don’t cause the webhook event queue to back up.

Slow-running POST operations are discarded (if they time out), so that new events can be processed. When the timeout is reached, Sync Gateway stops listening for a response.

A value of 0 (zero) means no timeout.

You should not need to adjust it to tune performance as he default value should work well in the majority of cases.

integer

url
optional

Defines the URL to post documents to (for a webhook event handler).

string

guest

Name Description Schema

disabled
optional

Set disabled = false to allow GUEST

For example: curl -X PUT username:password@localhost:4985/db/_config -H "Content-Type: application/json" --data-binary '{"guest": {"disabled":false}}
Default : true

boolean

OIDC Group

Name Description Schema

default_provider
optional

Use this default_provider property to identify the provider to use for OIDC requests that do not specify a provider.

If only one provider is specified in the providers map, then that is used as the default provider. If multiple providers are defined and default_provider is not specified, requests to /db/_oidc must specify the provider parameter.

string

providers
optional

Include an entry for each OIDC provider

OIDC Providers

OIDC Providers

Name Schema

this_provider
optional

OIDC Provider

OIDC Provider

Name Description Schema

allow_unsigned_provider_tokens
optional

Unsigned provider tokens are not accepted.

Set "allow_unsigned_provider_tokens": true to opt-in to accepting unsigned tokens from providers.
Default : false

boolean

callback_url
optional

The callback URL to be invoked after the end-user obtains a client token. When not provided, Sync Gateway will generate it based on the incoming request.

Optional

string

client_id
optional

The client ID defined in the provider for Sync Gateway.

string

disable_callback_state
optional

DisableCallbackState determines whether or not to maintain state between the /_oidc and /_oidc_callback endpoints.

Disabling this action is NOT recommended as it will increase vulnerability to Cross-Site Request Forgery (CSRF, XSRF).

Set "disable_callback_state": true to switch-off callback state.
Default : false

boolean

disable_cfg_validation
optional

Couchbase Sync Gateway, by default, applies strict validation of the OpenID Connect configuration based on the OIDC specification.

Set "disable_cfg_validation": true when you do not want strict validation of the OIDC configuration.
Default : false

boolean

disable_session
optional

By default, Sync Gateway will create a new session for the user upon successful OIDC authentication, and set that session in the usual way on the oidc_callback and _oidc_refresh responses.

If disable_session is set to true, the session is not created (clients must use the ID token for subsequent authentications).

_Optional

string

discovery_url
optional

Optional. Discovery URL used to obtain the OpenID Connect provider configuration. If not specified, the default discovery endpoint of [issuer]/.well-known/openid-configuration will be used.

string

include_access
optional

Optional. When true, the oidccallback response will include the access_token, expires_at and token_type properties returned by the OP.

string

issuer
optional

The OpenID Connect Provider issuer.

string

register
optional

Whether Sync Gateway should automatically create users for successfully authenticated users that don’t have an already existing user in Sync Gateway.

Optional.

string

scope
optional

By default, Sync Gateway uses the scope "openid email" when calling the OP’s authorize endpoint.

If the scope property is defined in the config (as an array of string values), it will override this scope.

*Optional. *

string

user_prefix
optional

Optional. Specifies the prefix for Sync Gateway usernames for the provider. When not specified, defaults to issuer.

string

username_claim
optional

You can use username_claim to specify a claim other than subject to use as the Sync Gateway username.

The specified claim must be a string, as numeric claims may be un-marshalled inconsistently between Sync Gateway and the underlying OIDC library.

When authenticating incoming OIDC tokens, Sync Gateway currently treats the username as [subject]. By default user_prefix is the issuer, but can be customized in the Sync Gateway provider config. Subject is always the sub claim in the token.

Behavior:

* If username_claim is set but user_prefix is not set, use that claim as the Sync Gateway username.

* If username_claim is set and user_prefix is also set, use [user_prefix][username_claim] as the Sync Gateway username.

* If username_claim is not set and user_prefix is set, use [subject] as the Sync Gateway username (existing behavior).

* If neither username_claim nor user_prefix are set, use [issuer][subject] as the Sync Gateway username (existing behavior).
Default : "optional"

string

validation_key
optional

Client secret associated with the client. Required for auth code flow.

string

Unsupported Properties Model

Name Description Schema

api_endpoints
optional

api_endpoints

disable_clean_skipped_query
optional

Clean skipped sequence processing bypasses final check

boolean

oidc_test_provider
optional

Config settings for OIDC test provider

oidc_test_provider

oidc_tls_skip_verify
optional

Unsupported option for use in development and testing environment ONLY

oidc_tls_skip_verify can be used to enable the use of self-signed certs for OpenID Connection testing.
Default : false

boolean

remote_config_tls_skip_verify
optional

Unsupported option for use in development and testing environment ONLY

Use only to enable self signed certificates for testing external JavaScript load.
Default : false

boolean

sgr_tls_skip_verify
optional

Unsupported option for use in development and testing environment ONLY

sgr_tls_skip_verify can be used to skip validation of TLS certs used for Inter-Sync Gateway Replication.
Default : false

boolean

user_views
optional

Configuration settings for user views

user_views

warning_thresholds
optional

Warning Threshold

api_endpoints

Name Description Schema

enable_couchbase_bucket_flush
optional

Determines whether Couchbase buckets can be flushed using the Admin REST API.

Use only for testing purposes if it is necessary to flush data in between tests to start with a clean DB.

boolean

oidc_test_provider

Name Description Schema

enabled
optional

Unsupported option for use in development and testing environment ONLY

Determines whether the oidc_test_provider endpoints should be exposed on the public API.

boolean

user_views

Name Description Schema

user_views_enabled
optional

Unsupported option for use in development and testing environment ONLY

Use to determine whether pass-through view query is supported through public API

boolean

Warning Threshold

Name Description Schema

access_and_role_grants_per_doc
optional

Number of access and role grants per document to be used as a threshold for grant count warnings

boolean

channel_name_size
optional

Number of channel name characters to be used as a threshold for channel name warnings

boolean

channels_per_doc
optional

Number of channels per document to be used as a threshold for channel count warnings

boolean

channels_per_user
optional

Number of channels per user to be used as a threshold for channel count warnings

boolean

xattr_size_bytes
optional

Number of bytes to be used as a threshold for XATTR size limit warnings

boolean

Import_filter_model

The import_filter controls whether a document written to the Couchbase Server bucket should be made available to Couchbase Mobile clients (that is, whether it ought to be imported).

You should provision the filter as a Javascript function in the request body of a call to the Admin Rest API endpoint put {db}/_config/import_filter.

Set the header’s content type to content-Type: application/javascript.

The function takes the document body as parameter and is expected to return a boolean to indicate whether the document should be imported.

If you do not provide a filter function then no filter will be applied and ALL documents will be imported.

Type : string

Role_model

Use the role property to define a Sync Gateway role

Name Description Schema

admin_channels
optional

Array of channel names the role allows access to

< string > array

all_channels
optional

Lists all the channels the role has access to including any assigned by the sync function.

This is a derived property and changes to it are ignored.

< string > array

name
required

Name of the role

string

Role_and_User_model

Name Schema

Role
optional

Role_model

User
optional

User_model

Sync_model

The sync property is a Javascript function that determines which users can access which documents.

This JavaScript function is provisioned using the Admin Rest API Endpoint put /{db}/_config/sync

Add the function as plain javascript in the request body, with the content-Type: application/javascript header.

Type : string

User_model

Definition of a Sync Gateway user

Change initiates database restart

Name Description Schema

admin_channels
optional

The channels that the user is able to access.

< string > array

admin_roles
optional

An array of the roles this user is associated with.

< string > array

all_channels
optional

Shows the channels the user can access, as granted by the sync function.

This is a read-only property. Changes to it are ignored.

< string > array

disabled
optional

This property is usually not included.

If the value is true, access for the account is disabled and the user will not be able to login.

boolean

email
optional

Email address of the user.

string

name
required

The user name (the same name used in the URL path).

The valid characters for a user name are alphanumeric ASCII characters and the underscore character.

The name property is required in a POST request.

You don’t need to include it in a PUT request because the user name is specified in the URL.

string

password
optional

Password of the user.

Mandatory, unless allow_empty_password=true.

string

roles
optional

Shows the roles this user is associated with by the Sync function.

This is a read-only property. Changes to it are ignored.

< string > array

User-response

Name Description Schema

admin_channels
optional

The channels that the user is able to access.

< string > array

all_channels
optional

Shows the channels the user can access, as granted by the sync function.

< string > array

disabled
optional

This property is usually not included. If the value is true, access for the account is disabled and the user will not be able to login.

boolean

email
optional

Email address of the user.

string

name
optional

The user name (the same name used in the URL path).

string

AllDatabases

List of available databases in cluster

Type : < string > array

ActiveTasks_model

Name Description Schema

continuous
optional

Whether the replication is continuously monitoring for changes on the source database to send them to the target.

boolean

direction
optional

Inter-Sync Gateway Replication (v1) is uni-directional; valid values are push or pull.

string

doc_write_failures
optional

The number of docs that have failed to be written (pushed) to the target database. These docs will not be retried.

integer

docs_read
optional

The number of docs that have been read (fetched) from the source database.

integer

docs_written
optional

The number of docs that have been written (pushed) to the target database.

integer

end_last_seq
optional

Deprecated The most recent last_seq value received from the source database during replication. Use the last_seq_push and last_seq_pull values instead.

integer

is_persistent
optional

flag to distinguish between the persistent and adhoc replications

boolean

last_seq_pull
optional

The last seq number pulled from the source to target.

The last_seq_pull result can be used by apps to determine if a specific document has been synced to target or not. Do this by querying the _raw endpoint and comparing the sequence number of document with the last_seq value that was replicated.

integer

last_seq_push
optional

The last seq number pushed from the source to target.

The last_seq_push result can be used by apps to determine if a specific document has been synced to target or not. Do this by querying the _raw endpoint and comparing the sequence number of document with the last_seq value that was replicated.

integer

replication_id
optional

The replication Id.

string

source
optional

The URL of the source database (i.e "http://example.com:4985/source";).

string

status
optional

Stopped / running

These will be adhoc replications (running) or persistent replications (stopped or running).

string

target
optional

The URL of the target database (i.e "http://example.com:4985/target";).

string

DocMetadata

Name Schema

_sync
optional

_sync

_sync

Name Description Schema

history
optional

history

parents
optional

< integer > array

recent_sequences
optional

< integer > array

rev
optional

Revision number of the current revision

string

sequence
optional

Sequence number of this document

integer

history

Name Description Schema

channels
optional

< string > array

parents
optional

< integer > array

revs
optional

< string > array

time_saved
optional

Timestamp of the last operation?

string

Error

Name Schema

code
optional

integer (int32)

fields
optional

string

message
optional

string

SGCollectInfoStats

Name Description Schema

status
optional

The current status of sgcollect_info

string

ExpVars

Name Description Schema

cb
optional

Variables reported by the Couchbase SDK (go_couchbase package)

object

cmdline
optional

Built-in variables from the Go runtime, lists the command-line arguments

object

mc
optional

Variables reported by the low-level memcached API (gomemcached package)

object

memstats
optional

Dumps a large amount of information about the memory heap and garbage collector

object

syncGateway_changeCache
optional

syncGateway_changeCache

syncGateway_db
optional

syncGateway_db

syncgateway
optional

Monitoring stats

syncgateway

syncGateway_changeCache

Name Description Schema

lag-queue-0000ms
optional

Histogram of delay from Tap feed till doc is posted to changes feed

object

lag-tap-0000ms
optional

Histogram of delay from doc save till it shows up in Tap feed

object

lag-total-0000ms
optional

Histogram of total delay from doc save till posted to changes feed

object

maxPending
optional

Max number of sequences waiting on a missing earlier sequence number

object

outOfOrder
optional

Number of out-of-order sequences posted

object

view_queries
optional

Number of queries to channels view

object

syncGateway_db

Name Description Schema

channelChangesFeeds
optional

Number of calls to db.changesFeed, i.e. generating a changes feed for a single channel.

object

channelLogAdds
optional

Number of entries added to channel logs

object

channelLogAppends
optional

Number of times entries were written to channel logs using an APPEND operation

object

channelLogCacheHits
optional

Number of requests for channel-logs that were fulfilled from the in-memory cache

object

channelLogRewriteCollisions
optional

Number of collisions while attempting to rewrite channel logs using SET

object

channelLogRewrites
optional

Number of times entries were written to channel logs using a SET operation (rewriting the entire log)

object

document_gets
optional

Number of times a document was read from the database

object

revisionCache_adds
optional

Number of revisions added to the revision cache

object

revisionCache_hits
optional

Number of times a revision-cache lookup succeeded

object

revisionCache_misses
optional

Number of times a revision-cache lookup failed

object

revs_added
optional

Number of revisions added to the database (including deletions)

object

sequence_gets
optional

Number of times the database’s lastSequence was read

object

sequence_reserves
optional

Number of times the database’s lastSequence was incremented

object

syncgateway

Name Description Schema

global
optional

Global Sync Gateway stats

global

per_db
optional

This array contains stats for all databases declared in the config file - see the Sync Gateway Statistics Schema for more details on the metrics collected and reported by Sync Gateway.

The statistics for each {$db_name} database are grouped into:

* cache related statistics * cbl_replication_push * cbl_replication_pull * database_related_statistics * delta_sync * gsi_views * security_related_statistics * shared_bucket_import * per_replication statistics for each replication_id

< per_db > array

per_replication
optional

An array of stats for each replication declared in the config file

Deprecated @ 2.8: used only by inter-sync-gateway replications version 1.

< per_replication > array

global

Name Description Schema

resource_utilization
optional

Resource utilization stats

resource_utilization

resource_utilization

Name Schema

admin_net_bytes_recv
optional

integer

admin_net_bytes_sent
optional

integer

error_count
optional

integer

go_memstats_heapalloc
optional

integer

go_memstats_heapidle
optional

integer

go_memstats_heapinuse
optional

integer

go_memstats_heapreleased
optional

integer

go_memstats_pausetotalns
optional

integer

go_memstats_stackinuse
optional

integer

go_memstats_stacksys
optional

integer

go_memstats_sys
optional

integer

goroutines_high_watermark
optional

integer

num_goroutines
optional

integer

process_cpu_percent_utilization
optional

integer

process_memory_resident
optional

integer

pub_net_bytes_recv
optional

integer

pub_net_bytes_sent
optional

integer

system_memory_total
optional

integer

warn_count
optional

integer

per_db

Name Schema

cache
optional

object

database
optional

object

per_replication
optional

< object > array

security
optional

object

per_replication

Name Schema

$replication_id
optional

$replication_id

$replication_id

Name Description Schema

sgr_active
optional

Whether the replication is active at this time. Deprecated @ 2.8: used only by inter-sync-gateway replications version 1.

boolean

sgr_docs_checked_sent
optional

The total number of documents checked for changes since replication started. This represents the number of potential change notifications pushed by Sync Gateway. Constraints This is not necessarily the number of documents pushed, as a given target might already have the change. Used by versions 1 and 2.

integer

sgr_num_attachment_bytes_transferred
optional

The total number of attachment bytes transferred since replication started. Deprecated @ 2.8: used only by inter-sync-gateway replications version 1.

integer

sgr_num_attachments_transferred
optional

The total number of attachments transferred since replication started. Deprecated @ 2.8: used only by inter-sync-gateway replications version 1.

integer

sgr_num_docs_failed_to_push
optional

The total number of documents that failed to be pushed since replication started. Used by versions 1 and 2.

integer

sgr_num_docs_pushed
optional

The total number of documents that were pushed since replication started. Used by versions 1 and 2.

integer

Forbidden

Name Description Schema

error
optional

Default : "conflict"

string

id
optional

string

reason
optional

string

status
optional

integer

LogTags

Name Description Schema

Access
optional

access() calls made by the sync function

boolean

Attach
optional

Attachment processing

boolean

Auth
optional

Authentication

boolean

Bucket
optional

Sync Gateway interactions with the bucket (verbose logging).

boolean

CRUD
optional

Updates made by Sync Gateway to documents (CRUD+ for verbose logging)

boolean

Cache
optional

Interactions with Sync Gateway’s in-memory channel cache (Cache+ for verbose logging)

boolean

Changes
optional

Processing of _changes requests (Changes+ for verbose logging)

boolean

DCP
optional

DCP-feed processing (verbose logging)

boolean

Events
optional

Event processing (webhooks) (Events+ for verbose logging)

boolean

Feed
optional

Server-feed processing (Feed+ for verbose logging)

boolean

HTTP
optional

All requests made to the Sync Gateway REST APIs (Sync and Admin). Note that the log keyword HTTP is always enabled, which means that HTTP requests and error responses are always logged (in a non-verbose manner). HTTP+ provides more verbose HTTP logging.

boolean

PurgeBody

Document ID

Name Description Schema

a_doc_id
optional

Only possible value is ["*"]. It permanently removes all revisions for that document ID.

< enum (*) > array

BulkDocsSuccess

Name Description Schema

id
optional

Design document identifier

string

rev
optional

Revision identifier

string

ChangesFeedRow

Name Description Schema

changes
optional

List of the document’s leafs. Each leaf object contains one field, rev.

< changes > array

id
optional

Document identifier

string

seq
optional

Update sequence number

integer

changes

Name Description Schema

rev
optional

Identifier of the document revision that changed.

string

QueryRow

Name Description Schema

doc
optional

The document body. This is only returned if include_docs=true is specified in the URL.

object

id
optional

The ID of the document.

string

key
optional

The key in the output row.

object

value
optional

The value in the output row.

object

Design

Name Description Schema

count
optional

Total number of items available.

integer (int32)

limit
optional

Number of items to retrieve (100 max).

integer (int32)

offset
optional

Position in pagination.

integer (int32)

AllDocs

Name Description Schema

keys
optional

List of identifiers of the documents to retrieve

< string > array

Changes

Name Description Schema

last_seq
optional

Last change sequence number

object

results
optional

List of changes to the database. See the following table for a list of fields in this object.

< ChangesFeedRow > array

Compact_Response

JSON Respponse to a _compact request

Name Description Schema

compact_id
optional

Unique identifier

string

end_time
optional

Time the _compact process ended for example "2015-09-23T17:27:17.55+01:00"

string

last_error
optional

Text of the last error message.

string

marked_attachments
optional

The number of attachments marked during the mark` phase.

integer

phase
optional

This item indicates the current phase of running compact processes. It can be useful in monitoring progress.

For failed processes, this indicates the phase at which a compact_id restart will commence (where relevant).

Phases include: - mark - sweep - cleanup

string

purged_attachments
optional

The number of attachments purged by the sweep phase of the _compact process.

integer

start_time
optional

Time the _compact process started for example "2015-09-23T17:27:17.55+01:00"

string

status
optional

State of the _compact process (Running, Stopped, Completed)

string

Document_model

Name Description Schema

_attachments
optional

Array of attachments

< _attachments > array

_exp
optional

Expiry time after which the document will be purged.

The expiration time is set and managed on the Couchbase Server document (TTL is not supported for databases in walrus mode).

The value can be specified in two ways; in ISO-8601 format, for example the 6th of July 2016 at 17:00 in the BST timezone would be 2016-07-06T17:00:00+01:00; it can also be specified as a numeric Couchbase Server expiry value.

Couchbase Server expiries are specified as Unix time, and if the desired TTL is below 30 days then it can also represent an interval in seconds from the current time (for example, a value of 5 will remove the document 5 seconds after it is written to Couchbase Server).

The document expiration time is returned in the response of GET /{db}/{doc} when show_exp=true is included in the querystring.

As with the existing explicit purge mechanism, this applies only to the local database; it has nothing to do with replication.

This expiration time is not propagated when the document is replicated.

The purge of the document does not cause it to be deleted on any other database.

string

_id
optional

The document ID.

string

_rev
optional

Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)

string

_revisions
optional

_revisions

_attachments

Name Schema

attachment_name
optional

attachment_name

attachment_name

Name Description Schema

content_type
optional

The content type of the attachment.

string

digest
optional

Reference to stored attachment content

string

length
optional

integer

revpos
optional

integer

stub
optional

Default : true

boolean

ver
optional

Indicate that the attachment reference is made through the new reference scheme (not exposed). Value = 2.

integer

_revisions

Name Description Schema

ids
optional

Array of valid revision IDs, in reverse order (latest first).

< string > array

start
optional

Prefix number for the latest revision.

integer

doc-resp

Name Description Schema

id
optional

Document identifier

string

ok
optional

Indicates whether the operation was successful

boolean

rev
optional

Revision identifier

string

QueryResult

Name Description Schema

offset
optional

Starting index of the returned rows.

string

rows
optional

< QueryRow > array

total_rows
optional

Number of documents in the database. This number is not the number of rows returned.

integer

ReplicationResponse

Name Description Schema

ok
optional

Indicates whether the replication operation was successful

boolean

session_id
optional

Session identifier

string

Replication_model

Data schema for the replication model

Name Description Schema

adhoc
optional

" About

Use the Admin REST API’s adhoc parameter to specify that a replication is ad hoc rather than persistent.

Behavior

Ad hoc replications behave the same as normal replications, but they are automatically removed when their status changes to stopped. This will usually be on completion, but may also be as a result of user action.

Constraints

This parameter is NOT available to configured replications; only those initialized using the Admin REST API."
Default : false

boolean

batch_size
optional

About

Use the optional batch_size property to specify the number of changes to be included in a single batch during replication.

integer

cancel
optional

About

Use this parameter on,y when you want to want to cancel an existing active replication.

Constraints

* This parameter is NOT available in configured replications; only those initialized using the Admin REST API.

* NOTE that the body of the request must be the same as the replication’s replication definition for the cancellation request to be honoured. For example, if you requested continuous replication, the cancellation request must also contain the continuous field.
Default : false

boolean

conflict_resolution_type
optional

About

The conflict_resolution_type property defines the conflict resolution policy that Sync Gateway applies when resolving conflicting revisions.

The default behavior is that automatic conflict resolution policy is applied.

Valid options - default - localWins - remoteWins - custom

Behavior

* default - Selecting default applies the following conflict resolution policy * Deletes always win (the delete with longest revision history wins if both revisions are deletes) * The revision with the longest revision history wins (so, the one with most changes and consequently the highest revision Id). * localWins - Selecting localWins will result in local revisions always being the winner in any conflict.

* remoteWins - Selecting remoteWins will result in remote revisions always being the winner in any conflict. * custom - Selecting custom specifies that you want to handle conflict resolution with your own application logic. You must provide this logic as a Javascript function by specifying it in using the custom-conflict-resolver parameter.

Example

---- "conflict_resolution_type":"remoteWins" ----

Constraints

* Replications created prior to version 2.8 will default to default.
Default : "default"

string

continuous
optional

About

The continuous property specifies whether this replication will run in continuous mode.

Behavior

* continuous=true– In continuous mode, changes are immediately synced in accordance with the replication definition. * continuous=false– Detected changes are synced in accordance with the replication definition. The replication ceases once all revisions are processed.

Constraints

* Optional for stops and removes
Default : false

boolean

custom_conflict_resolver
optional

About

The optional custom_conflict_resolver property specifies the Javascript function that will be used to resolve conflicts, if the custom conflict resolution type is specified in the conflict_resolution_type.

Options

The property is mandatory when conflict_resolution_type=custom and will be ignored in all other cases.

Using

Provide the required logic in a Javascript function, as a string within backticks (see also the description for the sync function`.

The function takes one parameter struct representing the conflict and comprising - the document id - the local document - the remote document

The function returns a document struct representing the winning revision.

Example

---- "custom_conflict_resolver":` function(conflict) { console.log("full remoteDoc doc: "+JSON.stringify(conflict.RemoteDocument)); return conflict.RemoteDocument; }` ----

Constraints

Using complex custom_conflict_resolver functions can noticeably degrade performance. Use a built-in resolver whenever possible.
Default : "none"

string

direction
optional

About

The mandatory direction property specifies whether the replication is push, pull or pushAndPull relative to this node.

The property value is referenced by the remote property.

Behavior

* pull - changes are pulled from the remote database * push - changes are pushed to the remote database * pushAndPull - changes are both pushed-to and pulled-from the remote database

Constraints

Replications created prior to version 2.8 derive their direction from the source/target url of the replication.

string

enable_delta_sync
optional

About

The optional enable_delta_sync parameter turns on delta sync for a replication. It works in conjunction with the database level setting delta_sync.enabled.

Options

* "enable_delta_sync": true, the replication can use delta sync (depending on delta_sync.enabled setting) * "enable_delta_sync": false, the replication cannot use delta sync

Behavior

The optional enable_delta_sync parameter works in conjunction with the database level delta_sync.enabled setting, to determine whether this replication uses delta sync.

* If "delta_sync.enabled": true for both databases involved in the replication, then this parameter enables or disables its use for this specific replication. * In all other cases it has no effect and the replication runs without delta-sync.

Constraints

* Applies ONLY to Enterprise Edition deployments. * Depends upon the setting of the database level parameter delta_sync.enabled * Replications created prior to version 2.8 must run with "enable_delta_sync": false * Push replications will not use Delta Sync when pushing to a pre-2.8 target
Default : false

boolean

filter
optional

About

Use the optional filter`property to defines the function to be used to filter documents.

Options

A common value used when replicating from Sync Gateway is `sync_gateway/bychannel. This option limits the pull replication to a specific set of channels. You can specify the required channels using query_params.

Behavior

Works in conjunction with query_params to control the documents processed by the replication.

Example

---- "filter":"sync_gateway/bychannel" ----

Constraints

OPTIONAL for stops and removes (even if defined during creation)

string

initial_state
optional

About

The optional initial_state property is used to specify that the replication must be launched in 'Stopped' mode

Behavior

All replications are configured to start on Sync Gateway launch. So, if omitted, the state defaults to 'Running'.

Constraints*

Replications created prior to version 2.8 will all default to a state of 'Running'.
Default** : "Running"

string

max_backoff_time
optional

The *max_backoff_time*property specifies the time-period (in minutes) during which Sync Gateway will attempt to reconnect lost or unreachable remote targets.

On disconnection, Sync Gateway will do an exponential backoff up to the specified value, after which it will attempt to reconnect indefinitely every max_backoff_time minutes.

If a zero value is specified, then Sync Gateway will do an exponential backoff up to an interval of five minutes before stopping the replication.

NOTE - this value defaults to five minutes for replications created prior to version 2.8.

integer

password
optional

About

Use password to provide the login password value for the accredited user running this replication.

Behavior

These details are used to authenticate credentials and approve access to data.

Once provided and recorded, the password data is redacted and will not be displayed in either the configuration file or Admin REST API. A string of * will be displayed in its place.
Default
* : "mandatory"

string

purge_on_removal
optional

About

The optional purge_on_removal property specifies, per replication, whether the removal of a channel triggers a purge.

Options - true or false - Default = false - Document removals are ignored by receiving end

Behavior

If purge_on_removal=false, then the removal of channels is ignored (not purged) by the receiving end.

Constraints

* Applies only to PULL replications, including the PULL portion of a PUSHANDPULL replication.

* Replications created prior to version 2.8 must be run with purge_on_removal=false.
Default : false

boolean

query_params
optional

About

The query_params property defines a set of key/value pairs used in the query string of the replication.

Behavior

This property works in conjunction with filters and channels to provide routing.

Using

You can use query_params’ channels function to pull from a specific set of `channels. To do so, you would also need to set the filter to sync_gateway/bychannels.

Example

[source,json] ---- "filter":"sync_gateway/bychannel", "query_params": { "channels":["channel.user1"] }, ----

Constraints

OPTIONAL for stops and removes (even if defined during creation)

< string > array

remote
optional

About

The remote property represents the endpoint of a database for the remote Sync Gateway. That is, it identifies the remote Sync Gateway database that is the subject of this replication’s push, pull or pushAndPull action.

Typically the endpoint will include URI, Port and Database name elements.

You can also include user credentials in the URL, in the form <username>:<password>. The credentials relate to an existing Sync Gateway user on the remote server.

Example `"remote": "http://user:password@example.com:4985/db1-remote"; `

Format

* a string containing a valid URL for a (remote) Sync Gateway database. * an object whose url property contains the Sync Gateway database URL.

Behavior

Dependent upon setting of direction.

If direction is : - pull, 'remote' defines the remote cluster from which data is pulled - push, 'remote' defines the remote cluster to which data is pushed - pushAndPull, 'remote' defines the push configuration.

Example

[source,json] ---- "remote": "http://www.example.com:4984/sample-database", ----

string

replication_id
optional

About

The replication_id property specifies either:

* For NEW replications, the ID to be assigned to the the replication. If no replication_id is specified, Sync Gateway will assign a random UUID to new replications.

* For existing replications, this is the ID of the required replication.

* If cancel=true, this is the id of the active replication task to be cancelled.

Constraints

If this is specified in the body of a POST or PUT request then it must be the same value as specified in the request URL.

string

username
optional

About

Use username to provide the name of the accredited user running this replication.

Behavior

These details are used to authenticate credentials and approve access to data

Once provided and recorded, the username data is redacted and will not be displayed in either the configuration file or Admin REST API. A string of * will be displayed in its place.
Default
* : "Mandatory"

string

ReplicationStatusResponseBody

Name Description Schema

config
optional

This optional response content is returned only when using the {querystring} option with includeConfig=true. For example,

---- GET http://localhost:4985/db-local/_replicationStatus?includeError=true&includeConfig=true ----

It comprises the replication definition as would be returned using a GET request to the _replication endpoint.

object

delta_recv
optional

The number of delta-sync changes sent

integer

delta_requested
optional

The number of delta-sync changes requested.

This should always be non-zero when delta_sync.enabled is true.

integer

delta_sent
optional

This is the number of deltas sent.

Whether or not deltas are sent and-or received is based on whether the remote:

* has deltas enabled, and-or

* can generate a delta for the requested revision.

integer

doc_write_conflict
optional

The number of docs that were in conflict.

integer

doc_write_failures
optional

The number of docs that have failed to be written (pushed) to the target database. These docs will not be retried.

integer

docs_purged
optional

The number of docs that have been purged.

integer

docs_read
optional

The number of docs that have been read (fetched) from the source database.

integer

docs_written
optional

The number of docs that have been written (pushed) to the target database.

integer

error_message
optional

A message describing the reason for the latest error. It is reset each Sync Gateway restart.

string

last_seq_pull
optional

Last sequence number processed in pull replication.

The last_seq_pull result can be used by apps to determine if a specific document has been synced to target or not.

To do this, query the _raw endpoint and compare the sequence number of the document with the last_seq value (push or pull as approperiate) replicated.

string

last_seq_push
optional

Last sequence value processed in push replication.

The last_seq_push result can be used by apps to determine if a specific document has been synced to target or not.

To do this, query the _raw endpoint and compare the sequence number of the document with the last_seq value (push or pull as approperiate) replicated.

string

rejected_by_local
optional

Count of documents that were received by the local but did not get replicated because they were rejected by the sync function on the local

integer

rejected_by_remote
optional

Count of documents that were sent to the remote but did not get replicated because they were rejected by the sync function on the remote

integer

replication_id
optional

The replication Id.

string

status
optional

The status of the replication.

Valid values are: - Starting - Started - Stopping - Stopped - Error

string

Resync-response

Name Description Schema

docs_changed
optional

Shows the number of documents that have been changed as a result of the sync function.

Docs are only changed if when run through the new sync function the resulting doc is different to the currently stored doc.

integer

docs_procesed
optional

Shows the number of documents that have been run through the sync function.

integer

last_error
optional

Will ONLY be present when status = “stopped on error”

In the event of an error in the _resync process this field will contain error details. Otherwise it is not visible.

string

start_time
optional

The _resync process start time in ISO 8601 format (for example: 2012-04-23T18:25:43.511Z)

string

status
optional

Indicates the status of the resync operation.

Possible values:

* running,

* stopped,

* stopping,

* stopped on error

string

Server

Name Description Schema

couchdb
optional

Contains the string 'Welcome' (this is required for compatibility with CouchDB)

string

vendor/name
optional

The server type ('Couchbase Sync Gateway)

string

vendor/version
optional

The server version

string

version
optional

Sync Gateway version number

string

ReplicationResponseBody

This is the replication definition set returned in response to a GET request.

Name Description Schema

this_rep
optional

This is the replication definition set returned in response to a GET request.

this_rep

this_rep

Name Description Schema

adhoc
optional

Indicates whether this replication is ad hoc ("adhoc": true) or Persistent. Both replications behave in the same way, except that adhoc replications are automatically removed when their status changes to stopped. This will usually be on completion, but may also be as a result of user action).
Default : false

boolean

batch_size
optional

About

The batch_size property specifies the number of changes to be included in a single batch during replication.

integer

conflict_resolution_type
optional

About

The conflict_resolution_type property specifies the conflict resolution policy Sync Gateway will apply when resolving conflicting revisions.

The default behavior is that automatic conflict resolution policy is applied.

Valid options

* default

* localWins

* remoteWins

* custom

Behavior

* default - Selecting default applies the following conflict resolution policy

* Deletes always win (the delete with longest revision history wins if both revisions are deletes)

* The revision with the longest revision history wins (so, the one with most changes and consequently the highest revision Id).

* localWins - Selecting localWins will result in local revisions always being the winner in any conflict.

* remoteWins - Selecting remoteWins will result in remote revisions always being the winner in any conflict.

* custom - Selecting custom specifies that you want to handle conflict resolution with your own application logic. You must provide this logic as a Javascript function by specifying it in using the custom-conflict-resolver parameter.

Example

---- "conflict_resolution_type":"remoteWins" ----

Constraints

* Replications created prior to version 2.8 will default to default.
Default : "default"

string

continuous
optional

About

The continuous property specifies whether this replication runs in continuous, or single-shot, mode.

Behavior

* continuous=true– In continuous mode, changes are immediately synced in accordance with the replication definition.

* continuous=false– Detected changes are synced in accordance with the replication definition. The replication ceases once all revisions are processed.

Constraints

* Optional for stops and removes
Default : false

boolean

custom_conflict_resolver
optional

About

The custom_conflict_resolver property specifies the Javascript function that will be used to resolve conflicts, if the custom conflict resolution type is specified in the conflict_resolution_type.

Options

The property is mandatory when conflict_resolution_type=custom and will be ignored in all other cases.

Using

Provide the required logic in a Javascript function, as a string within backticks (see also the description for the sync function`.

The function takes one parameter struct representing the conflict and comprising

* the document id

* the local document

* the remote document

The function returns a document struct representing the winning revision.

Example

---- "custom_conflict_resolver":` function(conflict) { console.log("full remoteDoc doc: "+JSON.stringify(conflict.RemoteDocument)); return conflict.RemoteDocument; }` ----

Constraints

Using complex custom_conflict_resolver functions can noticeably degrade performance. Use a built-in resolver whenever possible.
Default : "none"

string

direction
optional

About

The mandatory direction property indicates whether the replication is push, pull or pushAndPull.

The property value is referenced by the remote property.

Constraints

Replications created prior to version 2.8 derive the direction from the source/target url of the replication.

string

enable_delta_sync
optional

About

The enable_delta_sync property specifies whether delta sync is, or is not, used for the replication.

Options

To use delta sync or not.

* enable_delta_sync=true - the replication runs using delta sync

* enable_delta_sync=false - the replication runs without delta sync

Behavior

The impact of this property is dependent on the delta_sync.enabled setting for the relevent databases as indicated here.

* If "delta_sync.enabled": true for both databases involved in the replication, then this parameter enables or disables its use for this specific replication.

* In all other cases it has no effect and the replication runs without delta-sync.

Constraints

* Requires Enterprise Edition * Replications created prior to version 2.8 run with enable_delta_sync=false
Default : false

boolean

filter
optional

About

Use the optional filter property to defines the function to be used to filter documents.

Options

A common value used when replicating from Sync Gateway is sync_gateway/bychannel. This option limits the pull replication to a specific set of channels. You can specify the required channels using query_params.

Behavior

Works in conjunction with query_params to control the documents processed by the replication.

Example

---- "filter":"sync_gateway/bychannel" ----

Constraints

OPTIONAL for stops and removes (even if defined during creation)

string

initial_state
optional

About

The optional initial_state property is used to specify that the replication must be launched in 'Stopped' mode

Behavior

All replications are configured to start on Sync Gateway launch. So, if omitted, the state defaults to 'Running'.

Constraints*

Replications created prior to version 2.8 will all default to a state of 'Running'.
Default** : "Running"

string

max_backoff_time
optional

About

The max_backoff_time property indicates the time-period (in minutes) during which Sync Gateway will attempt to reconnect lost or unreachable remote targets.

On disconnection, Sync Gateway will do an exponential backoff up to the specified value, after which it will attempt to reconnect indefinitely every max_backoff_time minutes.

If the value is zero, Sync Gateway will do an exponential backoff up to an interval of five minutes before stopping the replication.

Constrains

This value defaults to five minutes for replications created prior to version 2.8.

integer

password
optional

The password, forms part of the login credentials used to access the data.

All password data is redacted and is displayed as a string of *.
Default
* : "Mandatory"

string

perf_tuning_params
optional

The perf_tuning_params are yet to be defined (subject to performance testing)

NOTE - This property replaces the 'changes_feed_limit' at version 2.8

object

purge_on_removal
optional

About

The optional purge_on_removal property specifies, per replication, whether the removal of a channel triggers a purge.

Options - true or false - Default = false - Document removals are ignored by receiving end

Behavior

If purge_on_removal=false, then the removal of channels is ignored (not purged) by the receiving end.

Constraints

* Applies only to PULL replications, including the PULL portion of a PUSHANDPULL replication.

* Replications created prior to version 2.8 must be run with purge_on_removal=false.
Default : false

boolean

query_params
optional

About

The query_params property defines a set of key/value pairs used in the query string of the replication.

Behavior

This property works in conjunction with filters and channels to provide routing.

Using

You can use query_params’ channels function to pull from a specific set of `channels. To do so, you would also need to set the filter to sync_gateway/bychannels.

Example

[source,json] ---- "filter":"sync_gateway/bychannel", "query_params": { "channels":["channel.user1"] }, ----

Constraints

OPTIONAL for stops and removes (even if defined during creation)

< string > array

remote
optional

About

The remote property represents a database URL for the remote Sync Gateway. That is, it identifies the remote Sync Gateway database that is the subject of this replication’s push, pull or pushAndPull action.

Behavior

Dependent upon setting of direction. If direction is :

* pull, this is the cluster from which data is pulled

* push, this is the cluster to which data is pushed

* pushAndPull, this is the cluste from which data is pushed.

Example

---- "remote": "http://www.example.com:4984/db2name", ----

Constraints

* You must specify the 'remote' database’s url even if it is located on the same cluster as the replication’s database.

* OPTIONAL for stops and removes

string

replication_id
optional

About

The replication_id property indicates the ID that Sync Gateway assigned to the replication.

Sync Gateway assigns a random UUID if no replication_id is specified when the replication is created.

string

username
optional

The username forms part of the credentials used to authenticate and approve access to data

This field is redacted a string of '*' is displayed in its place.
Default
* : "Mandatory"

string

ReplicationStatistics-SGR1

This is the replication definition set returned in response to an ExpVars GET request.

Name Description Schema

replname
optional

This object comprises the stats collected and recorded for the inter-sync-gateway replication named $replname (which equates to a replication_id).

The same structure is used to return statistics from inter-sync-gateway replications versions 1 and 2, but not all items are populated by each version.

replname

replname

Name Description Schema

sgr_active
optional

Whether the replication is active at this time. Deprecated @ 2.8: used only by inter-sync-gateway replications version 1.

boolean

sgr_docs_checked_sent
optional

The total number of documents checked for changes since replication started.

This represents the number of potential change notifications pushed by Sync Gateway.

Constraints - This is not necessarily the number of documents pushed, as a given target might already have the change.

* Used by versions 1 and 2.

integer

sgr_num_attachment_bytes_transferred
optional

The total number of attachment bytes transferred since replication started. Deprecated @ 2.8: used only by inter-sync-gateway replications version 1.

integer

sgr_num_attachments_transferred
optional

The total number of attachments transferred since replication started. Deprecated @ 2.8: used only by inter-sync-gateway replications version 1.

integer

sgr_num_docs_failed_to_push
optional

The total number of documents that failed to be pushed since replication started.

Used by versions 1 and 2.

integer

sgr_num_docs_pushed
optional

The total number of documents that were pushed since replication started.

Used by versions 1 and 2.

integer

View

Name Description Schema

_rev
optional

Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)

string

views
optional

List of views to save on this design document.

views

views

Name Description Schema

my_view_name
optional

The view’s map/reduce functions.

my_view_name

my_view_name

Name Description Schema

map
optional

Inline JavaScript definition for the map function

string

reduce
optional

Inline JavaScript definition for the reduce function

string