swagger: '2.0'
info:
  title: Sync Gateway
  description: |
    Documentation for the Sync Gateway Admin REST API.
    This page is generated from the Sync Gateway Admin Swagger spec, the exact same information is also available at [developer.couchbase.com/mobile/swagger/sync-gateway-admin](http://developer.couchbase.com/mobile/swagger/sync-gateway-admin/).
  version: '1.0'
# the domain of the service
host: localhost:4985
# array of all schemes that your API supports
schemes:
- http
- https
# will be prefixed to all paths
consumes:
- application/json
produces:
- application/json
paths:
  /{db}/{doc}/{attachment}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/doc'
    - $ref: '#/parameters/attachment'
    get:
      tags:
      - attachment
      summary: Get attachment
      description: |
        This request retrieves a file attachment associated with the document. The raw data of the associated attachment is returned (just as if you were accessing a static file). The 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. From then on, the attachment will not be replicated but will still reside in the Couchbase Server bucket (see open ticket [#1648](https://github.com/couchbase/sync_gateway/issues/1648)).
      parameters:
      - $ref: '#/parameters/rev'
      responses:
        200:
          description: The message body contains the attachment, in the format specified in the Content-Type header.
          schema:
            type: string
            format: binary
        304:
          description: Not Modified, the attachment wasn't modified if ETag equals the If-None-Match header
        404:
          description: Not Found, the specified database, document or attachment was not found.
    put:
      tags:
      - attachment
      summary: Add or update attachment
      description: |
        This request adds or updates 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. From then on, the attachment will not be replicated but will still reside in the Couchbase Server bucket (see open ticket [#1648](https://github.com/couchbase/sync_gateway/issues/1648)).
      parameters:
      - $ref: '#/parameters/rev'
      - $ref: '#/parameters/body'
      - $ref: '#/parameters/content_type'
      responses:
        200:
          description: Operation completed successfully
          schema:
            $ref: '#/definitions/Success'
        409:
          description: Conflict, the document revision wasn't specified or it's not the latest.
  /_active_tasks:
    get:
      tags:
      - server
      summary: Return status of Inter-Sync Gateway Replication (v1) replications
      description: |+
        <h5>**Deprecated @ 2.8** replaced by Inter-Sync Gateway Replication (v2)'s *[_replicationStatus](#/server/get__replicationStatus)* endpoint. This **_active_tasks** endpoint is retained **solely** for backward compatibility.<h5>

        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/get__db___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/get__db___replicationStatus).
      responses:
        200:
          description: Information about active replications.
          schema:
            type: array
            items:
              type: object
              $ref: '#/definitions/ActiveTaskResponseBody'

  /_all_dbs:
    get:
      tags:
      - server
      summary: Lists node's databases
      description: |+
        Return a list all databases running on the node
      responses:
        200:
          description: |+
            OK -- Operation successful

            The response body contains a string array containing the names of all databases running on this sync gateway node
          schema:
            $ref: '#/definitions/all_dbs'

  /{db}/_bulk_docs:
    parameters:
      - $ref: '#/parameters/db'
    post:
      tags:
      - database
      summary: 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.
      parameters:
        - $ref: '#/parameters/bulkdocs'
      responses:
        201:
          description: Documents have been created or updated. The response object is an array with the status for each document submitted in the original request.
          schema:
            type: array
            items:
              $ref: '#/definitions/BulkDocsSuccess'
        409:
          description: The operation failed with a forbidden error. Probably because the document already exists in the database but a revision number wasn't specified.
          schema:
            $ref: '#/definitions/Forbidden'
  /:
    get:
      tags:
      - server
      summary: Server
      description: |
        Returns meta-information about the server.
      responses:
        200:
          description: Meta-information about the server.
          schema:
            $ref: '#/definitions/Server'
  /{db}/_bulk_get:
    parameters:
    - $ref: '#/parameters/db'
    post:
      tags:
      - database
      summary: 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.)
      produces:
      - 'multipart/mixed'
      parameters:
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/revs_limit'
      - $ref: '#/parameters/attachments'
      - $ref: '#/parameters/bulkget'
      responses:
        200:
          description: Request completed successfully
          examples:
            multipart/mixed (document found): |
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
              Content-Type: application/json

              {"_id":"doc123","_rev":"1-c543d6514c609f65180f94af247aaffe","hello":"world!"}
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
            multipart/mixed (document not found): |
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
              Content-Type: application/json; error="true"

              {"error":"not_found","id":"doc1234","reason":"missing","status":404}
              --1cba224ff2aa106566e3ab65de9c861c24558ba368f8cd7f6fcde53b88f4
        301:
          description: 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.
          schema:
            type: object
            properties:
              _id:
                type: string
                description: The document ID that was requested
              _removed:
                type: boolean
                default: true
              _rev:
                type: string
                description: The revision number that was requested
  /{db}/_local/{local_doc}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/local_doc'
    get:
      tags:
      - document
      summary: Get 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.
      responses:
        200:
          description: The message body contains the following objects in a JSON document.
          schema:
            $ref: '#/definitions/Success'
    put:
      tags:
      - document
      summary: Create or update a local document
      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.
      responses:
        201:
          description: Created
          schema:
            $ref: '#/definitions/Success'
    delete:
      tags:
      - document
      summary: Delete a local document
      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.
      parameters:
      - $ref: '#/parameters/rev'
      - $ref: '#/parameters/batch'
      responses:
        200:
          description: Document successfully removed
          schema:
            $ref: '#/definitions/Success'
  /{db}/_changes:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - database
      parameters:
      - $ref: '#/parameters/limit'
      - $ref: '#/parameters/style'
      - $ref: '#/parameters/active_only'
      - $ref: '#/parameters/include_docs'
      - $ref: '#/parameters/filter'
      - $ref: '#/parameters/channels_list'
      - $ref: '#/parameters/doc_ids'
      - $ref: '#/parameters/feed'
      - $ref: '#/parameters/since'
      - $ref: '#/parameters/heartbeat'
      - $ref: '#/parameters/timeout'
      summary: 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.
      responses:
        200:
          description: Request completed successfully
          schema:
            $ref: '#/definitions/Changes'
    post:
      tags:
      - database
      parameters:
      - $ref: '#/parameters/changes_body'
      summary: Changes
      description: |
        Same as the GET /_changes request except the parameters are in the JSON body.
      responses:
        200:
          description: Request completed successfully
          schema:
            $ref: '#/definitions/Changes'
  /{db}/{doc}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/doc'
    get:
      tags:
      - document
      parameters:
      - $ref: '#/parameters/rev_get'
      - $ref: '#/parameters/attachments'
      - $ref: '#/parameters/atts_since'
      - $ref: '#/parameters/open_revs'
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/show_exp'
      summary: Get document
      description: This request retrieves a document from a database.
      responses:
        200:
          description: The message body contains the following objects in a JSON document.
          schema:
            type: object
    put:
      tags:
      - document
      parameters:
      - in: body
        name: Document
        description: Request body
        schema:
          $ref: '#/definitions/Document'
      - $ref: '#/parameters/new_edits'
      - $ref: '#/parameters/rev_put'
      summary: Create or update document
      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 behaviour 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.
      responses:
        200:
          description: The response is a JSON document that contains the following objects
          schema:
            $ref: '#/definitions/Success'
    delete:
      tags:
      - document
      parameters:
      - $ref: '#/parameters/rev_delete'
      summary: Delete document
      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.
      responses:
        200:
          description: Document successfully removed
          schema:
            $ref: '#/definitions/Success'
  /{db}/_design/{ddoc}/_view/{view}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/ddoc'
    - $ref: '#/parameters/view'
    get:
      tags:
      - query
      summary: Query a view
      description: |
        Query a view on a design document.
      parameters:
      - in: query
        name: conflicts
        description: Include conflict information in the response. This parameter is ignored if the include_docs parameter is false.
        type: boolean
      - in: query
        name: descending
        description: Return documents in descending order.
        type: boolean
      - in: query
        name: endkey
        description: If this parameter is provided, stop returning records when the specified key is reached.
        type: string
      - in: query
        name: end_key
        description: Alias for the endkey parameter.
        type: string
      - in: query
        name: endkey_docid
        description: If this parameter is provided, stop returning records when the specified document identifier is reached.
        type: string
      - in: query
        name: end_key_doc_id
        description: Alias for the endkey_docid parameter.
        type: string
      - in: query
        name: include_docs
        description: Only works when using Couchbase Server 3.0 and earlier.  Indicates whether to include the full content of the documents in the response.
        type: boolean
      - in: query
        name: inclusive_end
        description: Indicates whether the specified end key should be included in the result.
        type: boolean
      - in: query
        name: group
        description: Group the results using the reduce function to a group or single row.
        type: boolean
      - in: query
        name: group_level
        description: Specify the group level to be used.
        type: integer
      - in: query
        name: key
        description: If this parameter is provided, return only document that match the specified key.
        type: string
      - in: query
        name: limit
        description: If this parameter is provided, return only the specified number of documents.
        type: integer
      - in: query
        name: skip
        description: If this parameter is provided, skip the specified number of documents before starting to return results.
        type: integer
      - in: query
        name: stale
        description: 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.
        type: string
      - in: query
        name: startkey
        description: If this parameter is provided, return documents starting with the specified key.
        type: string
      - in: query
        name: start_key
        description: Alias for startkey param.
        type: string
      - in: query
        name: startkey_docid
        description: If this parameter is provided, return documents starting with the specified document identifier.
        type: string
      - in: query
        name: update_seq
        description: Indicates whether to include the update_seq property in the response.
        type: boolean
      responses:
        200:
          description: Query results
          schema:
            $ref: '#/definitions/QueryResult'
  /{db}/_all_docs:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - database
      summary: All docs
      description: |
        This request returns a built-in view of all the documents in the database.
      parameters:
      - $ref: '#/parameters/access'
      - $ref: '#/parameters/channels'
      - $ref: '#/parameters/include_docs'
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/update_seq'
      - $ref: '#/parameters/limit'
      - $ref: '#/parameters/keys'
      - $ref: '#/parameters/startkey'
      - $ref: '#/parameters/endkey'
      responses:
        200:
          description: Query results
          schema:
            $ref: '#/definitions/QueryResult'
    post:
      tags:
      - database
      summary: All docs
      description: |
        This request retrieves specified documents from the database.
      parameters:
      - $ref: '#/parameters/access'
      - $ref: '#/parameters/channels'
      - $ref: '#/parameters/include_docs'
      - $ref: '#/parameters/revs'
      - $ref: '#/parameters/update_seq'
      - in: body
        name: body
        description: Request body
        schema:
          $ref: '#/definitions/AllDocs'
      responses:
        200:
          description: Query results
          schema:
            $ref: '#/definitions/QueryResult'
  /{db}/_oidc:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - auth
      summary: OpenID Connect Authentication.
      description: |
        Called by clients to initiate the OIDC Authorization Code flow.
      parameters:
      - in: query
        name: offline
        description: 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.
        type: boolean
        required: false
      - in: query
        name: provider
        description: 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.
        type: string
        required: false
      responses:
        302:
          description: Redirect to the requested OpenID Connect provider for authentication. Redirect link is returned in the Location header.
        400:
          description: 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.
        500:
          description: Server Error.  Sync Gateway is unable to connect and validate the OpenID Connect provider requested.
  /{db}/_oidc_callback:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - auth
      summary: OpenID Connect Authentication callback.
      description: |
        Sync Gateway callback URL that clients are redirected to by the OpenID Connect provider.
      parameters:
      - in: query
        name: code
        description: OpenID Connect Authorization code.
        type: string
        required: true
      - in: query
        name: provider
        description: 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.
        type: string
        required: false
      responses:
        200:
          description: Successful OpenID Connect authentication.
          schema:
            type: object
            properties:
              id_token:
                type: string
                description: OpenID Connect ID token
              refresh_token:
                type: string
                description: OpenID Connect refresh token
              session_id:
                type: string
                description: Sync Gateway session token
              name:
                type: string
                description: Sync Gateway username
              access_token:
                type: string
                description: OpenID Connect access token
              token_type:
                type: string
                description: OpenID Connect token type
              expires_in:
                type: number
                description: TTL for id_token
        400:
          description: Bad request.
        401:
          description: Authentication failed.  Reason returned in the response body.
  /{db}/_oidc_challenge:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - auth
      summary: OpenID Connect Authentication.
      description: |
        Called by clients to initiate the OIDC Authorization Code flow.
      parameters:
      - in: query
        name: offline
        description: 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.
        type: boolean
        required: false
      - in: query
        name: provider
        description: 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.
        type: string
        required: false
      responses:
        302:
          description: Redirect to the requested OpenID Connect provider for authentication. Redirect link is returned in the Location header.
        400:
          description: 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.
        500:
          description: Server Error.  Sync Gateway is unable to connect and validate the OpenID Connect provider requested.
  /{db}/_oidc_refresh:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - auth
      summary: OpenID Connect refresh.
      description: |
        Used to obtain a new OpenID Connect ID token based on the provided refresh token.
      parameters:
      - in: query
        name: refresh_token
        description: OpenID Connect refresh token.
        type: string
        required: true
      - in: query
        name: provider
        description: 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.
        type: string
        required: false
      responses:
        200:
          description: Successful OpenID Connect authentication.
          schema:
            type: object
            properties:
              id_token:
                type: string
                description: OpenID Connect ID token
              session_id:
                type: string
                description: Sync Gateway session token
              name:
                type: string
                description: Sync Gateway username
              access_token:
                type: string
                description: OpenID Connect access token
              token_type:
                type: string
                description: OpenID Connect token type
              expires_in:
                type: number
                description: TTL for id_token
        400:
          description: Bad request.
        401:
          description: Authentication failed.  Unable to refresh token.
################################################################################
# Replication endpoint path
################################################################################
  /{db}/_replication/:
    post:
      tags:
      # - database
      - replication
      summary: Create a new replication definition
      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.

        <br>**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.
      parameters:
      - $ref: '#/parameters/db-local'
      # - $ref: '#/parameters/replication_id-upsert'
      - $ref: '#/parameters/replication__replication-body'
      responses:
        200:
          description: Replication successfully updated
          schema:
            $ref: '#/definitions/ReplicationResponse'
        201:
          description: Replication successfully inserted
          schema:
            $ref: '#/definitions/ReplicationResponse'
    get:
      tags:
      # - database
      - replication
      summary: Retrieve all replication definitions
      description: |
        Returns an array object containing all replication definitions
      parameters:
        - $ref: '#/parameters/db-local'
      responses:
        200:
          description: Successful response - returns an array of replication definitions in the body as JSON
          schema:
            type: array
            items:
              # type: object
              $ref: '#/definitions/ReplicationResponseBody'

  /{db}/_replication/{replicationID}:
    get:
      tags:
      # - database
      - replication
      summary: Retrieve a replication definition
      description: |
        Returns requested (**replicationID**) replication definition
      parameters:
        - $ref: '#/parameters/db-local'
        - $ref: '#/parameters/replication_id-required'

      responses:
        200:
          description: Successful response - returns requested replication definition in the body as JSON
          schema:
            # type: array
            # items:
            type: object
            $ref: '#/definitions/ReplicationResponseBody'

    put:
      tags:
      # - database
      - replication
      summary: Upsert a replication definition
      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.

        <br>**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.
      parameters:
        - $ref: '#/parameters/db-local'
        - $ref: '#/parameters/replication_id-upsert'
        - $ref: '#/parameters/replication__replication-body'
      responses:
        200:
          description: Replication successfully updated
          schema:
            $ref: '#/definitions/ReplicationResponse'
        201:
          description: Replication successfully inserted
          schema:
            $ref: '#/definitions/ReplicationResponse'
    delete:
      tags:
        # - database
      - replication
      summary: Cancel and delete replication
      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
      parameters:
        - $ref: '#/parameters/db-local'
        - $ref: '#/parameters/replication_id-required'
      response:
        200:
          description: Replication successfully deleted

################################################################################
# Replication Status endpoint
################################################################################

  /{db}/_replicationStatus?{queryString}:
    get:
      tags:
        - replication
      summary: Returns replication status data for  replications matching the criteria
      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

          ```
      parameters:
        # $ref: '#/parameters/replicationStatus__queryString'
        # description: |+

        # replicationStatus-activeOnly:
        - in: query
          name: activeOnly
          type: boolean
          default: false
          required: false
          description: |+
            **Behavior**

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

            **Default**

            false

        # replicationStatus-localOnly:
        - in: query
          name: localOnly
          type: boolean
          default: false
          required: false
          description: |+
            **Behavior**

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

            **Default**

            false

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

        # replicationStatus-includeError:
        - in: query
          name: includeError
          type: boolean
          default: true
          required: false
          description: |+
            **Behavior**

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

            **Default**

            true

            By default the response includes replications in `error` state.

        - in: query
          name: includeConfig
          type: boolean
          default: false
          required: false
          description: |+
            **Behavior**

            When *true* the replication definition is included in the response.

            **Default**

             false


      responses:
        200:
          description: Returns information about the active replications
          schema:
            type: array
            items:
              type: object
              $ref: '#/definitions/ReplicationStatusResponseBody'
              config:
                type: object
                description: Optional response content. Returned only when `includeConfig=true`



  /{db}/_replicationStatus/{replicationID}:
    get:
      tags:
        - replication
      summary: Returns information on specified replication
      description: |+
        Returns the status of the requested (**replicationID**) replication
      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/replication_id-required'
      responses:
        200:
          description: Information about specified replication.
          schema:
            # type: array
            # items:
            type: object
            $ref: '#/definitions/ReplicationStatusResponseBody'

  /{db}/_replicationStatus/{replicationID}?action={action}:
    put:
      tags:
        - replication
      summary: Modify replication status
      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

           ```
           http://localhost:4985/fred/_replicationStatus/{replicationID}?action=start
           ```
      parameters:
        - $ref: '#/parameters/db'
        - $ref: '#/parameters/replication_id-required'
        - $ref: '#/parameters/replicationStatus-action'
        # - in: query
        #   name: action
        #   type: string
        #   default: none
        #   required: true
        #   description: Specifies the status to be set (`start`, `stop` or `reset`)
      responses:
        200:
          description: The required status is successfully set
          schema:
            # type: array
            # items:
            type: object
            $ref: '#/definitions/ReplicationStatusResponseBody'


  /{db}/_revs_diff:
    parameters:
      - $ref: '#/parameters/db'
    post:
      tags:
      - database
      summary: Used by the replicator
      description: Given a set of document/revision IDs, returns the subset of those that do not correspond to revisions stored in the database.
      parameters:
      - in: body
        name: body
        description: Request body
        schema:
          description: A dictionary with document IDs as keys.
          type: object
          additionalProperties:
            description: An array of revision IDs for that document.
            type: array
            items:
              type: string
      responses:
        200:
          description: The request was successful
          schema:
            description: A dictionary with document IDs as keys.
            type: object
            additionalProperties:
              type: object
              properties:
                missing:
                  type: array
                  description: A list of revision IDs for that document (the ones that are not stored in the database).
  /_config:
    get:
      tags:
      - server
      summary: Server configuration
      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.
      responses:
        200:
          description: Sync Gateway configuration of the running instance.
  /_expvar:
    get:
      tags:
      - server
      summary: Debugging/monitoring at runtime
      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](./rest-api-metrics.html)

        **See** : [Sync Gateway Statistics Schema](./../stats-monitoring.html) for more details on the metrics collected and reported by Sync Gateway.

      responses:
        200:
          description: OK - indicates success
          schema:
            $ref: '#/definitions/ExpVars'

  /_logging:
    get:
      tags:
      - server
      summary: Get logging tags
      description: |
        Get logging tags of running instance.
      responses:
        200:
          description: |
            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.
          schema:
            $ref: '#/definitions/LogTags'
    put:
      tags:
      - server
      summary: Set all logging tags
      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.
      parameters:
      - $ref: '#/parameters/level'
      - $ref: '#/parameters/logLevel'
      - $ref: '#/parameters/logtags'
      responses:
        201:
          description: The operation was successful
    post:
      tags:
      - server
      summary: Set individual logging tags
      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.
      parameters:
      - $ref: '#/parameters/level'
      - $ref: '#/parameters/logLevel'
      - $ref: '#/parameters/logtags'
      responses:
        201:
          description: The operation was successful
  /_sgcollect_info:
    get:
      tags:
      - server
      summary: Gets the status of sgcollect_info
      description: |
        Will return information about whether sgcollect_info is currently running or not.
      responses:
        200:
          description: The operation was successful
          schema:
            $ref: '#/definitions/SGCollectInfoStats'
    post:
      tags:
      - server
      summary: Trigger sgcollect_info
      description: |
        Starting in Sync Gateway 2.1, sgcollect_info can be triggered using ths endpoint.
      parameters:
      - $ref: '#/parameters/sgcollect_info'
      responses:
        200:
          description: The request was successful.
    delete:
      tags:
      - server
      summary: Stops any currently running sgcollect_info
      description: |
        sgcollect_info can be cancelled using ths endpoint.
      parameters:
      - $ref: '#/parameters/sgcollect_info'
      responses:
        200:
          description: The request was successful.
  /_post_upgrade:
    post:
      tags:
      - server
      summary: Remove obsolete design documents
      description: |
        Starting in Sync Gateway 2.0, design documents used internally by Sync Gateway will include a version number in their name.<br><br>

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

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

        *TIP:* Use the `preview=true` query string option to check which design documents will be removed.<br><br>

        Typcal use cases for this end point include:<br>

        - After upgrading Sync Gateway -- see ([upgrade guide](upgrade.html#upgrade)).

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

      parameters:
      - $ref: '#/parameters/upgrade_preview'
      responses:
        200:
          description: The request was successful.
  /_replicate:
    post:
      tags:
      - server
      summary: Starts or cancels a database replication operation
      description: |
        <h5>**Deprecated @ 2.8** This API endpoint is now deprecated. It is replaced by the Inter-Sync Gateway Replication (v2) replication endpoint -- see [_replication](#/replication/post__db___replication__replicationID_) endpoint</h5>

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

        <br><br>
        **Canceling replications**

        You can cancel continuous replications by adding the cancel field to the JSON request object and setting the value to true.
        <br>
        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.

        <br><br>

        **Constraints**

        - Use this endpoint only for Inter-Sync Gateway Replication (v1) replications.
        - Users wanting to us Inter-Sync Gateway Replication (v2) replications  should use [_replication](#/replication/post__db___replication__replicationID_) **not** this endpoint.


      parameters:
      - $ref: '#/parameters/replicate__replication-body'
      responses:
        200:
          description: 200 OK
          schema:
            $ref: '#/definitions/ReplicationResponse'
#        type: integer

  /{db}/:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - database
      summary: Database info
      description: |
        This request retrieves information about the database.
      responses:
        200:
          description: Request completed successfully.
          schema:
            $ref: '#/definitions/Database'
        401:
          description: Unauthorized. Login required.
        404:
          description: Not Found. Requested database not found.
    post:
      tags:
      - document
      operationId: post
      summary: Create document
      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.
      parameters:
      - in: body
        name: body
        description: The document body
        schema:
          type: object
      responses:
        201:
          description: The document was written successfully
          schema:
            $ref: '#/definitions/Success'
    put:
      tags:
      - database
      summary: Create database
      description: >
        This request creates a database.

        You can optionally pass the database config as the JSON body. For example:

          {
            "server":"http://localhost:8091",
            "bucket": "todo_app",
            "users": {
              "john": {"password": "pass", "admin_channels": ["*"]}
            }
          }

        Note that if you pass the entire config file it won't work, it must be the database portion only (the database name is specified in the URL path). If the parameters passed are invalid it will create a walrus-backed database with all values set to default.

        By default, the database that is created is brought online immediately. To create the database and keep it offline, include the property `offline` with the value `true` in the database properties for the database that you are posting in the request body.
      responses:
        201:
          description: The database was created successfully.
    delete:
      tags:
      - database
      summary: Delete database
      description: Delete database
      responses:
        200:
          description: Success
          schema:
            $ref: '#/definitions/Success'
  /{db}/_compact:
    parameters:
    - $ref: '#/parameters/db'
    post:
      tags:
      - database
      summary: Compact the database
      description: |
        Use the ```/{db}/_compact``` endpoint to trigger the compaction process, which purges the JSON bodies of non-leaf revisions. 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.

        **Pre-1.5 behavior differed from the above, as follows:**

        1.3-1.4 -- the parent revision is marked with a 5 minute expiry time, thus calling the `/{db}/_compact` endpoint is not necessary.

        1.2 -- obsolete revision bodies have to be cleaned up by calling the `/{db}/_compact` endpoint.

      responses:
        200:
          description: Request completed successfully.
          schema:
            type: object
            properties:
              revs:
                type: integer
                description: Count of the number of revisions that were compacted away.
  /{db}/_config:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - database
      summary: Database configuration
      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.
      responses:
        200:
          description: Sync Gateway configuration of the running instance.
    put:
      tags:
      - database
      summary: Update database configuration
      description: |
        This request updates the configuration for the database specified in the URL.
        NOTE -- Changes made via REST API are not persisted and won’t survive sync gateway restart.
        Make the change in the configuration file if the change is required to persist beyond Sync Gateway restarts.
      parameters:
      - in: body
        name: body
        description: The message body is a JSON document with the same set of properties described in the Database configuration section of the configuration file documentation.
        schema:
          type: object
      responses:
        201:
          description: Created
  /{db}/_design/{ddoc}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/ddoc'
    get:
      tags:
      - query
      summary: Get Views of a design document
      description: |
        Query a design document.
      responses:
        200:
          description: Views for design document
          schema:
            type: object
            properties:
              my_view_name:
                $ref: '#/definitions/View'
    put:
      tags:
      - query
      summary: Update views of a design document
      parameters:
      - in: body
        name: body
        description: The request body
        required: false
        schema:
          $ref: "#/definitions/View"
      responses:
        201:
          description: Successful operation
          schema:
            $ref: '#/definitions/Success'
    delete:
      tags:
      - query
      summary: Delete design document
      description: |
        Delete a design document.
      responses:
        200:
          description: The status
          schema:
            type: object
            items:
              $ref: '#/definitions/Design'
        default:
          description: Unexpected error
          schema:
            $ref: '#/definitions/Error'
  /{db}/_offline:
    parameters:
    - $ref: '#/parameters/db'
    post:
      tags:
      - database
      summary: This request takes the specified database offline.
      description: |
        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](../database-offline.html).
      responses:
        200:
          description: Database brought online
  /{db}/_online:
    parameters:
    - $ref: '#/parameters/db'
    post:
      tags:
      - database
      summary: Bring a database 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 datbases connection to the backing Couchbase Server bucket.
        - Reloads the database configuration, and connects to the backing Cocuhbase 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](../database-offline.html).
      parameters:
      - in: body
        name: body
        description: Optional request body to specify a delay.
        required: false
        schema:
          type: object
          properties:
            delay:
              type: integer
              description: Delay in seconds before bringing the database online.
      responses:
        200:
          description: OK – online request accepted.
        503:
          description: Service Unavailable – Database resync is in progress.
  /{db}/_purge:
    parameters:
    - $ref: '#/parameters/db'
    post:
      tags:
      - document
      summary: Purge document
      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.
      parameters:
      - in: body
        name: body
        description: The message body is a JSON document that contains the following objects.
        schema:
          $ref: '#/definitions/PurgeBody'
      responses:
        200:
          description: OK – The purge operation was successful
          schema:
            type: object
            description: Response object
            properties:
              a_doc_id:
                type: array
                description: Contains one property for each document ID successfully purged, the property key is the "docID" and the property value is a list containing the single entry "*".
                items:
                  type: string
                  description: Revision ID that was purged
  /{db}/_raw/{doc}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/doc'
    get:
      tags:
      - document
      summary: Document with metadata
      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.
      responses:
        200:
          description: hello
          schema:
            $ref: '#/definitions/DocMetadata'
  /{db}/_resync:
    parameters:
    - $ref: '#/parameters/db'
    post:
      tags:
      - database
      summary: Reprocess all documents by the database in the sync function.
      description: |
        This request causes all documents to be reprocessed by the database sync function. The _resync operation should be called if the sync function for a database has been modified in such a way that the channel or access mappings for any existing document would change as a result.

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

        A _resync operation will block until all documents in the database have been processed.
      responses:
        200:
          description: OK – The _resync operation has completed
          schema:
            type: object
            description: The number of documents that were successfully updated.
            properties:
              changes:
                type: integer
                description: The number of documents that were successfully updated
  /{db}/_revtree/{doc}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/doc'
    get:
      produces:
      - text/plain
      tags:
      - document
      summary: Revision Tree structure in Graphviz Dot format | not officially supported
      description: |
        Returns the dot syntax of the revision tree which can be rendered into a PNG image with the [CLI dot tool](http://www.graphviz.org/).

        - 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.
      responses:
        200:
          description: Success and returns the revtree as plain text.
  /{db}/_role:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - role
      summary: Get roles
      description: This request returns all the roles in the specified database.
      responses:
        200:
          description: 200 OK – Returns the list of roles as an array of strings
          schema:
            type: array
            description: 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.
            items:
              type: string
    post:
      tags:
      - role
      summary: Role
      description: This request creates a new role in the specified database.
      parameters:
      - $ref: '#/parameters/role'
      responses:
        201:
          description: 201 OK – The role was created successfully
        409:
          description: 409 Conflict – A role with this name already exists
  /{db}/_role/{name}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/role_name'
    get:
      tags:
      - role
      summary: Get role
      description: Request a specific role by name.
      responses:
        200:
          description: The response contains information about this role.
          schema:
            type: object
            properties:
              name:
                type: string
              admin_channels:
                type: array
                description: |
                  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.
                items:
                  type: string
              all_channels:
                type: array
                description: All the channels that this role has access to.
                items:
                  type: string
    put:
      tags:
      - role
      summary: Creates or updates a role
      description: This request creates or updates a role in the specified database.
      parameters:
      - $ref: '#/parameters/role'
      responses:
        200:
          description: 200 OK – The role was updated successfully
        201:
          description: 201 Created – The role was created successfully
    delete:
      tags:
      - role
      summary: Deletes the role
      description: This request deletes the role with the specified name in the specified database.
      responses:
        200:
          description: 200 OK – The role was successfully deleted
  /{db}/_session:
    parameters:
    - $ref: '#/parameters/db'
    post:
      tags:
      - session
      summary: Creates a new 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.
      parameters:
      - in: body
        name: SessionBody
        description: The message body is a JSON document that contains the following objects.
        schema:
          type: object
          properties:
            name:
              type: string
              description: Username of the user the session will be associated to.
            ttl:
              description: Default is 24 hours (86400 seconds). The TTL (time-to-live) of the session, in seconds. The value must be greater than 0.
              type: integer
              default: 86400
              example: 180
      responses:
        200:
          description: Session successfully created.
          schema:
            type: object
            properties:
              cookie_name:
                type: string
                description: Cookie used for session handling
              expires:
                type: string
                description: Expiration time for session.
              session_id:
                type: string
                description: Session ID.
  /{db}/_session/{sessionid}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/sessionid'
    get:
      tags:
      - session
      summary: Retrieves information about a session
      description: |
        This request retrieves information about a session.
      responses:
        200:
          description: 200 OK – Request completed successfully.
          schema:
            type: object
            properties:
              authentication_handlers:
                type: array
                items:
                  type: object
                  description: List of supported authentication handlers
              ok:
                type: boolean
                description: Success flag
              userCtx:
                type: object
                description: 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)
    delete:
      tags:
      - session
      summary: Deletes a single session
      description: |
        This request deletes a single session.
      responses:
        200:
          description: 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.
  /{db}/_user/{name}/_session:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/name'
    delete:
      tags:
      - session
      summary: Deletes all user sessions
      description: This request delete the session for the specified user.
      responses:
        200:
          description: User session deleted.
  /{db}/_user/{name}/_session/{sessionid}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/name'
    - $ref: '#/parameters/sessionid'
    delete:
      tags:
      - session
      summary: Deletes a specific user session
      description: This request delete the specified session for the specified user.
      responses:
        200:
          description: User session deleted.
  /{db}/_user/:
    parameters:
    - $ref: '#/parameters/db'
    get:
      tags:
      - user
      summary: Retrieves all users
      description: This request returns all the users in the specified database.
      responses:
        200:
          description: 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.
          schema:
            type: array
            items:
              type: string
              description: username
    post:
      tags:
      - user
      summary: Creates a new user
      description: This request creates a new user in the specified database.
      parameters:
      - $ref: '#/parameters/user'
      responses:
        201:
          description: 201 OK – The user was created successfully
        409:
          description: 409 Conflict – A user with this name already exists
  /{db}/_user/{name}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/name'
    get:
      tags:
      - user
      summary: Retrieves a specific user
      description: This request returns information about the specified user.
      responses:
        200:
          description: 200 OK – Returns information about the specified user
          schema:
            $ref: '#/definitions/User'
    put:
      tags:
      - user
      summary: Creates or updates a user
      description: This request creates or updates a user in the specified database.
      parameters:
      - $ref: '#/parameters/user'
      responses:
        200:
          description: 200 OK – The user record was updated successfully
        201:
          description: 201 Created – The user record was created successfully
    delete:
      tags:
      - user
      summary: Deletes a user
      description: This request deletes the user with the specified name in the specified database.
      responses:
        200:
          description: 200 OK – The user was successfully deleted
definitions:
  ActiveTaskResponseBody:
    type: object
    properties:
      source:
        type: string
        description: The URL of the source database (i.e `"http://example.com:4985/source"`).
      target:
        type: string
        description: The URL of the target database (i.e `"http://example.com:4985/target"`).
      continuous:
        type: boolean
        description: Whether the replication is continuously monitoring for changes on the source database to send them to the target.
      replication_id:
        type: string
        description: The replication Id.
      direction:
        type: string
        description: Inter-Sync Gateway Replication (v1) is uni-directional; valid values are **push** or **pull**.
      docs_read:
        type: integer
        description: The number of docs that have been read (fetched) from the source database.
      docs_written:
        type: integer
        description: The number of docs that have been written (pushed) to the target database.
      doc_write_failures:
        type: integer
        description: The number of docs that have failed to be written (pushed) to the target database.  These docs will not be retried.
      end_last_seq:
        type: integer
        description: |+
          *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.
      # start_last_seq:
      #   type: integer
      #   description: Not populated
      is_persistent:
        type: boolean
        description: flag to distinguish between the persistent and adhoc replications
      status:
        type: string
        description: |+
          Stopped / running

          These will be  **adhoc** replications (running) or persistent replications (stopped or running).
      last_seq_push:
        type: integer
        description:  |+
          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.
      last_seq_pull:
        type: integer
        description:  |+
          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.

  DocMetadata:
    type: object
    properties:
      _sync:
        type: object
        properties:
          rev:
            type: string
            description: Revision number of the current revision
          sequence:
            type: integer
            description: Sequence number of this document
          recent_sequences:
            type: array
            items:
              type: integer
              description: Previous sequence numbers
          parents:
            type: array
            items:
              type: integer
              description: N/A
          history:
            type: object
            properties:
              revs:
                type: array
                items:
                  type: string
                  description: N/A
              parents:
                type: array
                items:
                  type: integer
                  description: N/A
              channels:
                type: array
                items:
                  type: string
                  description: N/A
              time_saved:
                type: string
                description: Timestamp of the last operation?
  DocumentResponse:
    type: object
    properties:
      _id:
        type: string
        description: Document identifier
      _rev:
        type: string
        description: Revision identifier
  Error:
    type: object
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string
      fields:
        type: string
  SGCollectInfoStats:
    type: object
    properties:
      status:
        type: string
        description: The current status of sgcollect_info
  all_dbs:
    # type: object
    # properties:
      # db-names:
    type: array
    description: |+
      A string array containing the names of all databases running on this sync gateway node

      For example  ```["db1","db2"]```
    example:
      ["db_1_name", "db_2_name"]

  ExpVars:
    type: object
    properties:
      cmdline:
        type: object
        description: Built-in variables from the Go runtime, lists the command-line arguments
      memstats:
        type: object
        description: Dumps a large amount of information about the memory heap and garbage collector
      cb:
        type: object
        description: Variables reported by the Couchbase SDK (go_couchbase package)
      mc:
        type: object
        description: Variables reported by the low-level memcached API (gomemcached package)
      syncGateway_changeCache:
        type: object
        properties:
          maxPending:
            type: object
            description: Max number of sequences waiting on a missing earlier sequence number
          lag-tap-0000ms:
            type: object
            description: Histogram of delay from doc save till it shows up in Tap feed
          lag-queue-0000ms:
            type: object
            description: Histogram of delay from Tap feed till doc is posted to changes feed
          lag-total-0000ms:
            type: object
            description: Histogram of total delay from doc save till posted to changes feed
          outOfOrder:
            type: object
            description: Number of out-of-order sequences posted
          view_queries:
            type: object
            description: Number of queries to channels view
      syncGateway_db:
        type: object
        properties:
          channelChangesFeeds:
            type: object
            description: Number of calls to db.changesFeed, i.e. generating a changes feed for a single channel.
          channelLogAdds:
            type: object
            description: Number of entries added to channel logs
          channelLogAppends:
            type: object
            description: Number of times entries were written to channel logs using an APPEND operation
          channelLogCacheHits:
            type: object
            description: Number of requests for channel-logs that were fulfilled from the in-memory cache
          channelLogRewrites:
            type: object
            description: Number of times entries were written to channel logs using a SET operation (rewriting the entire log)
          channelLogRewriteCollisions:
            type: object
            description: Number of collisions while attempting to rewrite channel logs using SET
          document_gets:
            type: object
            description: Number of times a document was read from the database
          revisionCache_adds:
            type: object
            description: Number of revisions added to the revision cache
          revisionCache_hits:
            type: object
            description: Number of times a revision-cache lookup succeeded
          revisionCache_misses:
            type: object
            description: Number of times a revision-cache lookup failed
          revs_added:
            type: object
            description: Number of revisions added to the database (including deletions)
          sequence_gets:
            type: object
            description: Number of times the database's lastSequence was read
          sequence_reserves:
            type: object
            description: Number of times the database's lastSequence was incremented
      syncgateway:
        type: object
        description: Monitoring stats
        properties:
          global:
            type: object
            description: Global Sync Gateway stats
            properties:
              resource_utilization:
                type: object
                description: Resource utilization stats
                properties:
                  admin_net_bytes_recv:
                    type: integer
                  admin_net_bytes_sent:
                    type: integer
                  error_count:
                    type: integer
                  go_memstats_heapalloc:
                    type: integer
                  go_memstats_heapidle:
                    type: integer
                  go_memstats_heapinuse:
                    type: integer
                  go_memstats_heapreleased:
                    type: integer
                  go_memstats_pausetotalns:
                    type: integer
                  go_memstats_stackinuse:
                    type: integer
                  go_memstats_stacksys:
                    type: integer
                  go_memstats_sys:
                    type: integer
                  goroutines_high_watermark:
                    type: integer
                  num_goroutines:
                    type: integer
                  process_cpu_percent_utilization:
                    type: integer
                  process_memory_resident:
                    type: integer
                  pub_net_bytes_recv:
                    type: integer
                  pub_net_bytes_sent:
                    type: integer
                  system_memory_total:
                    type: integer
                  warn_count:
                    type: integer
          per_db:
            # type: object
            type: array
            # title: per database statistics [Per DB Per Replication Statistics Schema](./../refer/rest-api-admin-perDbStats.html "target=_blank")
            description: |+
              This array contains stats for all databases declared in the config file -- see the [Sync Gateway Statistics Schema](./../stats-monitoring.html) 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`
            items:
              type: object
              properties:

                cache:
                  type: object

                database:
                  type: object

                per_replication:
                  type: array

                security:
                  type: object
                # $db_name:
              # description: This object contains stats for a given database
              # properties:
                # description: |+
                  # This array element contains stats for the {$db_name} database -- see the data model in [Per DB Per Replication Statistics Schema](./../refer/rest-api-admin-perDbStats.html "target=_blank").

                  # type: object

                # security:
                #   type: object
                #   description: Stats relative to security
                #   properties:
                #     auth_failed_count:
                #       type: integer
                #       description: Number of unsuccessful authentications. Useful to monitor the number of authentication errors.
                #     auth_success_count:
                #       type: integer
                #       description: Number of successful authentications. Useful to monitor the number of authenticated requests.
                #     num_access_errors:
                #       type: integer
                #       description: Count of documents rejected by write access functions (requireAccess/requireRole/requireUser).
                #     num_docs_rejected:
                #       type: integer
                #       description: Count of documents rejected by the sync function. Useful to debug sync function issues and identify unexpected incoming documents.
                #     total_auth_time:
                #       type: integer
                #       description: Total time it took to authenticate the last incoming request.
              # $ref: "#/definitions/perReplicationStats-SGR1"
          per_replication:
            type: array
            summary: Per Replication Statistics (Deprecated)
            description: |+
              An array of stats for each replication declared in the config file

              **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
            items:
              type: object
              description: Stats for a given replication_id
              properties:
                $replication_id:
                  type: object
                  properties:
                    sgr_active:
                      type: boolean
                      description: |+
                        Whether the replication is active at this time.
                        **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                    sgr_docs_checked_sent:
                      type: integer
                      description: |+
                        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.
                    sgr_num_attachments_transferred:
                      type: integer
                      description: |+
                        The total number of attachments transferred since replication started.
                        **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                    sgr_num_attachment_bytes_transferred:
                      type: integer
                      description: |+
                        The total number of attachment bytes transferred since replication started.
                        **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                    sgr_num_docs_failed_to_push:
                      type: integer
                      description: |+
                        The total number of documents that failed to be pushed since replication started.
                        Used by versions 1 and 2.
                    sgr_num_docs_pushed:
                      type: integer
                      description: |+
                        The total number of documents that were pushed since replication started.
                        Used by versions 1 and 2.
  Forbidden:
    type: object
    properties:
      error:
        type: string
        default: conflict
      id:
        type: string
      reason:
        type: string
      status:
        type: integer
        default: 409
  LogTags:
    type: object
    properties:
      Access:
        type: boolean
        description: access() calls made by the sync function
      Attach:
        type: boolean
        description: Attachment processing
      Auth:
        type: boolean
        description: Authentication
      Bucket:
        type: boolean
        description: Sync Gateway interactions with the bucket (verbose logging).
      Cache:
        type: boolean
        description: Interactions with Sync Gateway's in-memory channel cache (Cache+ for verbose logging)
      Changes:
        type: boolean
        description: Processing of _changes requests (Changes+ for verbose logging)
      CRUD:
        type: boolean
        description: Updates made by Sync Gateway to documents (CRUD+ for verbose logging)
      DCP:
        type: boolean
        description: DCP-feed processing (verbose logging)
      Events:
        type: boolean
        description: Event processing (webhooks) (Events+ for verbose logging)
      Feed:
        type: boolean
        description: Server-feed processing (Feed+ for verbose logging)
      HTTP:
        type: boolean
        description: 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.
  PurgeBody:
    type: object
    description: Document ID
    properties:
      a_doc_id:
        type: array
        description: Only possible value is `["*"]`. It permanently removes all revisions for that document ID.
        items:
          type: string
          description: Only possible value is `"*"`. It permanently removes all revisions for that document ID.
          enum: ["*"]
  BulkDocsSuccess:
    type: object
    properties:
      id:
        type: string
        description: Design document identifier
      rev:
        type: string
        description: Revision identifier
  Success:
    type: object
    properties:
      id:
        type: string
        description: Design document identifier
      rev:
        type: string
        description: Revision identifier
      ok:
        type: boolean
        description: Indicates whether the operation was successful
  User:
    type: object
    properties:
      name:
        type: string
        description: 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.
      password:
        type: string
        description: Password of the user that will be created. Required, unless the `allow_empty_password` Sync Gateway per-database configuration value is set to `true`, in which case the password can be omitted.
      admin_channels:
        type: array
        description: The channels that the user is explicitly granted access to through the Admin REST API.
        items:
          type: string
          description: Channel name
      admin_roles:
        type: array
        description: The roles that the user is explicitly granted access to through the Admin REST API.
        items:
          type: string
          description: Role name
      all_channels:
        type: array
        description: Like the `admin_channels` property, but also includes channels the user is given access to by other documents via a sync function. This is a derived property and changes to it are ignored.
        items:
          type: string
          description: Channel name
      email:
        type: string
        description: Email of the user that will be created.
      disabled:
        type: boolean
        description: This property is usually not included. If the value is set to `true`, access for the account is disabled and the user will not be able to login.
      roles:
        type: array
        description: Like the `admin_roles` property, but also includes roles the user is given access to by other documents via a sync function. This is a derived property and changes to it are ignored. It contains an array of role name strings.
        items:
          type: string
          description: Role name
  ChangesFeedRow:
    type: object
    properties:
      changes:
        type: array
        description: List of the document’s leafs. Each leaf object contains one field, rev.
        items:
          type: object
          properties:
            rev:
              type: string
              description: Identifier of the document revision that changed.
      id:
        type: string
        description: Document identifier
      seq:
        type: integer
        description: Update sequence number
  InvalidJSON:
    description: The request provided invalid JSON data
  View:
    type: object
    properties:
      _rev:
        type: string
        description: Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)
      views:
        type: object
        description: List of views to save on this design document.
        properties:
          my_view_name:
            type: object
            description: The view's map/reduce functions.
            properties:
              map:
                type: string
                description: Inline JavaScript definition for the map function
              reduce:
                type: string
                description: Inline JavaScript definition for the reduce function
  QueryRow:
    type: object
    properties:
      id:
        type: string
        description: The ID of the document.
      key:
        type: object
        description: The key in the output row.
      value:
        type: object
        description: The value in the output row.
      doc:
        type: object
        description: The document body. This is only returned if `include_docs=true` is specified in the URL.
  Design:
    type: object
    properties:
      offset:
        type: integer
        format: int32
        description: Position in pagination.
      limit:
        type: integer
        format: int32
        description: Number of items to retrieve (100 max).
      count:
        type: integer
        format: int32
        description: Total number of items available.
  AllDocs:
    type: object
    properties:
      keys:
        type: array
        description: List of identifiers of the documents to retrieve
        items:
          type: string
          description: Document ID
  Changes:
    type: object
    properties:
      last_seq:
        type: object
        description: Last change sequence number
      results:
        type: array
        description: List of changes to the database. See the following table for a list of fields in this object.
        items:
          $ref: '#/definitions/ChangesFeedRow'
  Database:
    type: object
    properties:
      db_name:
        type: string
        description: Name of the database
      db_uuid:
        type: integer
        description: Database identifier
      disk_format_version:
        type: integer
        description: Database schema version
      disk_size:
        type: integer
        description: Total amount of data stored on the disk (in bytes)
      instance_start_time:
        type: string
        description: Date and time the database was opened (in microseconds since 1 January 1970)
      state:
        type: string
        description: 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.
      update_seq:
        type: string
        description: Number of updates to the database
  Document:
    type: object
    properties:
      _id:
        type: string
        description: The document ID.
      _rev:
        type: string
        description: Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)
      _exp:
        type: string
        description: |
          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.
      _revisions:
        type: object
        properties:
          start:
            type: integer
            description: Prefix number for the latest revision.
          ids:
            type: array
            description: Array of valid revision IDs, in reverse order (latest first).
            items:
              type: string
              description: A revision ID.
      _attachments:
        type: object
        properties:
          attachment_name:
            type: object
            properties:
              content_type:
                type: string
                description: The content type of the attachment.
#
  QueryResult:
    type: object
    properties:
      offset:
        type: string
        description: Starting index of the returned rows.
      rows:
        type: array
        items:
          $ref: '#/definitions/QueryRow'
      total_rows:
        type: integer
        description: Number of documents in the database. This number is not the number of rows returned.

#
  ReplicationResponse:
    type: object
    properties:
      ok:
        type: boolean
        description: Indicates whether the replication operation was successful
      session_id:
        type: string
        description: Session identifier
#
# REPLICATIONBODY at 2.8
  ReplicationPathPutPost:
    type: object
    properties:
      tags:
      # - database
      - replication
      summary: Start a database replication operation
      description: |
        **About**

        The `_replication` endpoint** is used to manage both ad hoc (`adhoc=true`) and persistent replications.

        You can cancel continuous replications by adding the `cancel` parameter 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.
        This means that for a `continuous` replication, the cancellation request must also contain the `continuous` setting, since the default value is `false`.

      parameters:
      - $ref: '#/parameters/db'
      - $ref: '#/parameters/replication_id-upsert'
      - $ref: '#/parameters/replication__replication-body'
      responses:
        200:
          description: Replication successfully updated
          schema:
            $ref: '#/definitions/ReplicationResponse'
        201:
          description: Replication successfully inserted
          schema:
            $ref: '#/definitions/ReplicationResponse'

# REPLICATIONSTATUS new at 2.8
  ReplicationStatusResponseBody:
    type: object
    properties:
      replication_id:
        type: string
        description: The replication Id.
      # continuous:
      #   type: boolean
#        description: Whether the replication is continuously monitoring for changes on the source database to send them to the target.
#      direction:
#        type: string
#        description: |
#          The direction* property determines the direction of the replications.
#          valid values are
#            - push
#            - pull
#            - pushAndPull
      # source:
      #   type: string
      #   description: |
      #     ** Not used for Inter-Sync Gateway Replication (v2) replications -- ignore**
      #     The URL of the source database (i.e `"http://example.com:4985/source"`).
      # target:
      #   type: string
      #   description: |
      #     The URL of the remote database (i.e `"http://example.com:4985/target"`).
      #     ** For Inter-Sync Gateway Replication (v2) replications -- this is always the remote database; whether it is a source or target is determined by the *direction* property.
      docs_read:
        type: integer
        description: The number of docs that have been read (fetched) from the source database.
      docs_written:
        type: integer
        description: The number of docs that have been written (pushed) to the target database.
      docs_purged:
        type: integer
        description: The number of docs that have been purged.
      doc_write_failures:
        type: integer
        description: The number of docs that have failed to be written (pushed) to the target database.  These docs will not be retried.
      doc_write_conflict:
        type: integer
        description: The number of docs that were in conflict.
      status:
        type: string
        description: |+
          The status of the replication.

          Valid values are:
          - Starting
          - Started
          - Stopping
          - Stopped
          - Error
      rejected_by_remote:
        type: integer
        description: 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
      rejected_by_local:
        type: integer
        description: 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
      last_seq_pull:
        type: string
        description: |+
          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.
      last_seq_push:
        type: string
        description: |+
          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.
      error_message:
        type: string
        description: A message describing the reason for the latest error. It is reset each Sync Gateway restart.
      delta_sent:
        type: integer
        description: |+
          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.

      delta_recv:
        type: integer
        description: The number of delta-sync changes sent
      delta_requested:
        type: integer
        description: |+
          The number of delta-sync changes requested.

          This should always be non-zero when delta_sync.enabled is true.
      config:
        type: object
        description: |+
          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.
        # schema:
        #   $ref: '#/definitions/ReplicationResponseBody'
        # delta_enabled:
      #   type: boolean
      #   description: Flag indicating whether the replication is using delta sync
#
#
  Server:
    type: object
    properties:
      couchdb:
        type: string
        description: Contains the string 'Welcome' (this is required for compatibility with CouchDB)
      vendor/name:
        type: string
        description: The server type ('Couchbase Sync Gateway)
      vendor/version:
        type: string
        description: The server version
      version:
        type: string
        description: Sync Gateway version number

  Session:
    type: object
    properties:
      authentication_handlers:
        type: array
        description: List of authentication methods.
        items:
          type: string
      ok:
        type: boolean
        description: Always true if the operation was successful.
      userCtx:
        $ref: '#/definitions/UserContext'
  UserContext:
    type: object
    description: Context for this user.
    properties:
      channels:
        type: object
        description: Key-value pairs with a channel name as the key and the sequence number that granted the user access to the channel as value.Note that `!` is the public channel and every user has access to it.
      name:
        type: string
        description: The user's name.

  ReplicationStatusResponse-Success:
    type: object
    # description: Successful response body
    # responses:
    200:
      description: The request was successful.
      schema:
      type: array
      items:
        type: object
        $ref: '#/definitions/ReplicationStatusResponseBody'


  ReplicationResponseBody:
    type: object
    description: This is the replication definition set returned in response to a `GET` request.
    properties:
      this_rep:
        type: object
        description:
        properties:
          adhoc:
            type: boolean
            default: false
            description: |+
              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).

          batch_size:
            type: integer
            default: 200
            description: |+
              **About**

              The `batch_size` property specifies the number of changes to be included in a single batch during replication.

          conflict_resolution_type:
            type: string
            default: default
            description: |+
              **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`.


          continuous:
            type: boolean
            default: false
            description: |+
              **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

          custom_conflict_resolver:
            type: string
            default: none
            description: |+
              **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.


          direction:
            type: string
            description: |+
              **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.


          enable_delta_sync:
            type: boolean
            default: false
            description: |+
              **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`


          filter:
            type: string
            description: |+
              **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)


          max_backoff_time:
            type: integer
            default: 5
            description: |+
              **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.


          password:
            type: string
            default: Mandatory
            description: |+
                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 `****`.

          perf_tuning_params:
            type: array
            description: |+
              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
            items:
              type: string


          purge_on_removal:
            type: boolean
            default: false
            description: |+
              **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**

              Replications created prior to version 2.8 *must* be run with `purge_on_removal=false`.


          query_params:
            type: array
            description: |+
              **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**

              ```json
                "filter":"sync_gateway/bychannel",
                "query_params": {
                  "channels":["channel.user1"]
                },
              ```

              **Constraints**

              OPTIONAL for stops and removes (even if defined during creation)

            items:
              type: string


          remote:
            type: string
            description: |+
              **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


          replication_id:
            type: string
            description: |+
              **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.

          initial_state:
            type: string
            default: Running
            description: |+
              **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'.

          username:
            type: string
            default: Mandatory
            description: |+

                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.

  block-rep-cancel-text:
    description: |+
      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.

# END: Define sync-gateway replications

  ReplicationStatistics-SGR1:
    type: array
    description: This is the replication definition set returned in response to an ExpVars `GET` request.
    properties:
      replname:
        type: object
        description: |+
          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.
        properties:
          sgr_active:
            type: boolean
            description: |+
              Whether the replication is active at this time.
              **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

          sgr_docs_checked_sent:
              type: integer
              description: |+
                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.

          sgr_num_attachments_transferred:
              type: integer
              description: |+
                The total number of attachments transferred since replication started.
                **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

          sgr_num_attachment_bytes_transferred:
              type: integer
              description: |+
                The total number of attachment bytes transferred since replication started.
                **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

          sgr_num_docs_failed_to_push:
              type: integer
              description: |+
                The total number of documents that failed to be pushed since replication started.

                Used by versions 1 and 2.
          sgr_num_docs_pushed:
              type: integer
              description: |+
                The total number of documents that were pushed since replication started.

                Used by versions 1 and 2.


  perReplicationStats-SGR1:
            # $ref: "#/definitions/perReplicationStats-SGR1"
            per_replication:
              type: array
              description: |+
                An array of stats for each replication declared in the config file

                **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
              items:
                type: object
                description: Stats for a given replication_id
                properties:
                  $replication_id:
                    type: object
                    properties:
                      sgr_active:
                        type: boolean
                        description: |+
                          Whether the replication is active at this time.
                          **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                      sgr_docs_checked_sent:
                        type: integer
                        description: |+
                          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.
                      sgr_num_attachments_transferred:
                        type: integer
                        description: |+
                          The total number of attachments transferred since replication started.
                          **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                      sgr_num_attachment_bytes_transferred:
                        type: integer
                        description: |+
                          The total number of attachment bytes transferred since replication started.
                          **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.
                      sgr_num_docs_failed_to_push:
                        type: integer
                        description: |+
                          The total number of documents that failed to be pushed since replication started.
                          Used by versions 1 and 2.
                      sgr_num_docs_pushed:
                        type: integer
                        description: |+
                          The total number of documents that were pushed since replication started.
                          Used by versions 1 and 2.


  perReplicationStats-SGR2:
      type: array
      description: This is the replication definition set returned in response to an ExpVars `GET` request.
      items:
          type: object
          properties:
            replname:
              type: object
              description: |+
                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.
              properties:
                sgr_active:
                  type: boolean
                  description: |+
                    Whether the replication is active at this time.
                    **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

                sgr_docs_checked_sent:
                    type: integer
                    description: |+
                      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.

                sgr_num_attachments_transferred:
                    type: integer
                    description: |+
                      The total number of attachments transferred since replication started.
                      **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

                sgr_num_attachment_bytes_transferred:
                    type: integer
                    description: |+
                      The total number of attachment bytes transferred since replication started.
                      **Deprecated @ 2.8**: used only by inter-sync-gateway replications version 1.

                sgr_num_docs_failed_to_push:
                    type: integer
                    description: |+
                      The total number of documents that failed to be pushed since replication started.

                      Used by versions 1 and 2.
                sgr_num_docs_pushed:
                    type: integer
                    description: |+
                      The total number of documents that were pushed since replication started.

                      Used by versions 1 and 2.

                sgr_delta_pull_replication_count:
                    type: integer
                    description: |+
                      The total number documents with deltas pulled

                sgr_delta_push_doc_count:
                    type: integer
                    description: |+
                      The total number of documents with deltas pushed

                sgr_deltas_sent:
                    type: integer
                    description: |+
                      The total number of deltas sent

                sgr_deltas_requested:
                    type: integer
                    description: |+
                      The total number of deltas requested

                sgr_conflict_detected:
                    type: integer
                    description: |+
                      The total number of documents where conflicts were detected

                sgr_conflict_resolved:
                    type: integer
                    description: |+
                      The total number of conflicting documents that were resolved successfully (by the active node)

                sgw_conflict_skipped_error:
                    type: integer
                    description: |+
                        The total number of documents that were skipped during sync because of an error in conflict resolution
parameters:
  access:
    name: access
    in: query
    description: 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.
    type: boolean
    default: false
  active_only:
    name: active_only
    in: query
    description: 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.
    type: boolean
    default: false
  attachment:
    in: path
    name: attachment
    description: 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](https://www.urlencoder.org/)).
    type: string
    required: true
  attachments:
    in: query
    name: attachments
    description: Default is false. Include attachment bodies in response.
    type: boolean
    default: false
  atts_since:
    name: atts_since
    in: query
    description: Include attachments only since specified revisions. Does not include attachments for specified revisions.
    type: array
    items:
      type: string
    required: false
  body:
    name: body
    in: body
    description: The request body
    schema:
      type: string
      format: binary
  bulkget:
    in: body
    name: BulkGetBody
    description: 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.
    schema:
      type: object
      properties:
        docs:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
                description: Document ID.
  channels:
    in: query
    name: channels
    description: 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.)
    type: boolean
    default: false
  channels_list:
    in: query
    name: channels
    description: 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.)
    type: string
    required: false
  content_type:
    in: header
    name: Content-Type
    description: Attachment Content-Type
    type: string
  db:
    name: db
    in: path
    description: Database name
    type: string
    required: true
  db-local:
    name: db
    in: path
    summary: Local database
    description: Name of the local database
    type: string
    required: true
  ddoc:
    name: ddoc
    in: path
    description: Design document name
    type: string
    required: true
  descending:
    name: descending
    in: query
    description: Default is false. Return documents in descending order.
    type: boolean
    required: false
  doc:
    name: doc
    in: path
    description: Document ID
    type: string
    required: true
  doc_ids:
    in: query
    name: doc_ids
    description: 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.
    type: array
    items:
      type: string
  endkey:
    name: endkey
    in: query
    description: If this parameter is provided, stop returning records when the specified key is reached.
    type: string
    required: false
  feed:
    in: query
    name: feed
    description: Default is 'normal'. Specifies type of change feed. Valid values are normal, continuous, longpoll, websocket.
    type: string
    default: 'normal'
  group:
    in: query
    name: group
    description: Group the results using the reduce function to a group or single row.
    type: boolean
    default: false
  group_level:
    in: query
    name: group_level
    description: Specify the group level to be used.
    type: integer
    required: false
  heartbeat:
    in: query
    name: heartbeat
    description: 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.
    type: integer
    default: 0
  include_docs:
    in: query
    name: include_docs
    description: Default is false. Indicates whether to include the associated document with each result. If there are conflicts, only the winning revision is returned.
    type: boolean
    default: false
  keys:
    in: query
    name: keys
    description: |
      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 \ 'http://localhost:4985/test_db/_all_docs?keys=[%22keyid1%22,%22keyid4%22]' \ -H 'Accept: application/json'```
    type: array
    items:
      type: string
    required: false
  limit:
    in: query
    name: limit
    description: Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1.
    type: integer
  local_doc:
    in: path
    name: local_doc
    description: Local document IDs begin with _local/.
    type: string
    required: true
  new_edits:
    name: new_edits
    in: query
    description: 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.
    type: boolean
    default: true
  open_revs:
    name: open_revs
    in: query
    description: |
      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](glossary.html) 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.
    type: array
    items:
      type: string
    required: false

  replication__replication-body:
    in: body
    name: ReplicationBody
    summary: Basic replication body (json)
    description: |+
      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.
    schema:
      type: object
      properties:
        # changes_feed_limit:
        #   type: integer
        #   default: 50
        #   description: |+
        #     The **changes_feed_limit** property is now deprecated.
        #     It was previously used to define the maximum number of change entries pulled in each loop of a continuous changes feed.

        #     NOTE -- Removed. This item is replaced by the 'perf-tuning-params' at version 2.8.

        adhoc:
          type: boolean
          default: false
          description: |+
            **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.

        batch_size:
          type: integer
          default: 200
          description: |+
            **About**

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

        cancel:
          type: boolean
          default: false
          description: |+
            **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.

        conflict_resolution_type:
          type: string
          default: default
          description: |+
            **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`.


        continuous:
          type: boolean
          default: false
          description: |+
            **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

        custom_conflict_resolver:
          type: string
          default: none
          description: |+
            **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.

        direction:
          type: string
          description: |+
            **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](rest-api-admin.html#database-this_db-replications-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.

        enable_delta_sync:
          type: boolean
          default: false
          description: |+
            **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
        filter:
          type: string
          description: |+
            **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)


        max_backoff_time:
          type: integer
          default: 5
          description: |+
            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.

        password:
          type: string
          default: mandatory
          description: |+
            **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.

        perf_tuning_params:
          type: array
          description: |+
            The perf_tuning_params are not available in this release.

            NOTE -- This property replaces the 'changes_feed_limit' at version 2.8
          items:
            type: string

        purge_on_removal:
          type: boolean
          default: false
          description: |+
            **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**

            Replications created prior to version 2.8 *must* be run with `purge_on_removal=false`.

        query_params:
          type: array
          description: |+
            **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**

            ```json
              "filter":"sync_gateway/bychannel",
              "query_params": {
                "channels":["channel.user1"]
              },
            ```

            **Constraints**

            OPTIONAL for stops and removes (even if defined during creation)

          items:
            type: string

        remote:
          type: string
          description: |+
            **About**

            The **remote** property represents the endpoint of s 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.

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

            ```json
            "remote": "http://www.example.com:4984/sample-database",
            ```

        replication_id:
          type: string
          description: |+
            **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.


        initial_state:
          type: string
          default: Running
          description: |+
            **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'.

        username:
          type: string
          default: Mandatory
          description: |+
            **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.


# END: Define sync-gateway replications
#




  # replication_id:
  #   in: path
  #   type: string
  #   name: replicationID
  #   description: If supplied, the **replicationID** parameter must be a valid replication id. If it is not supplied for a *new replication*, then a random UUID is generated.

  replication_id-upsert:
    in: path
    type: string
    name: replicationID
    description: |+
      <p>If supplied, the <i>replicationID</i> parameter must be a valid replication id.</p>
      <p>If it is not supplied for a <i>new</i> replication*, then a random UUID is generated.</p>

  # replication_id-get:
  #   in: path
  #   type: string
  #   name: replicationID
  #   description: |+
  #     The *replicationID* parameter specifies the required replication.

  # replication_id-delete:
  #   in: path
  #   type: string
  #   name: replicationID
  #   description: |+
  #     The *replicationID* parameter specifies the replication to be deleted.

  replication_id-required:
    in: path
    type: string
    name: replicationID
    required: true
    description: |+
      The {replicationID} parameter identifies the target replication.

  replicationStatus-action:
    in: query
    name: action
    type: string
    default: none
    required: true
    description: |+
      The value of the {action} parameter specifies the value you want the selected replication's status set to.

      <p>Valid values are:</p>

      - **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.
  rev:
    name: rev
    in: query
    description: Revision identifier of the parent revision the new one should replace. (Not used when creating a new document.)
    type: string
    required: false
  rev_get:
    name: rev
    in: query
    description: 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.
    type: string
    required: false
  rev_put:
    name: rev
    in: query
    description: Revision identifier of the revision to update. It must be the last revision in the history.
    type: string
    required: true
  rev_delete:
    name: rev
    in: query
    description: Revision identifier of the revision to delete. It must be the identifier of the latest revision in the history.
    type: string
    required: true
  revs:
    in: query
    name: revs
    description: 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.
    type: boolean
    default: false
  role:
    in: body
    name: role
    description: The message body is a JSON document that contains the following objects.
    schema:
      type: object
      properties:
        name:
          type: string
          description: Name of the role that will be created
        admin_channels:
          type: array
          description: Array of channel names to give the role access to
          items:
            type: string
  role_name:
    in: path
    name: name
    description: |
      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](https://en.wikipedia.org/wiki/Percent-encoding).

      When passing a role name in a URL path it must be escaped again using percent encoding e.g. 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"
    type: string
    required: true
  sessionid:
    name: sessionid
    in: path
    description: Session id
    type: string
    required: true
  startkey:
    name: startkey
    in: query
    description: Returns records starting with the specified key.
    type: string
    required: false
  since:
    in: query
    name: since
    description: 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.
    type: integer
    required: false
  style:
    in: query
    name: style
    description: 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.
    type: string
    default: 'main_only'
  timeout:
    in: query
    name: timeout
    description: 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.
    type: integer
    default: 300000
  update_seq:
    in: query
    name: update_seq
    description: Default is false. Indicates whether to include the update_seq (document sequence ID) property in the response.
    type: boolean
    default: false
  view:
    name: view
    in: path
    description: View name
    type: string
    required: true
  bulkdocs:
    in: body
    name: BulkDocsBody
    description: The request body
    schema:
      properties:
        docs:
          description: 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.
          type: array
          items:
            type: object
            $ref: '#/definitions/Document'
        new_edits:
          description: Indicates whether to assign new revision identifiers to new edits.
          type: boolean
          default: true
  batch:
    in: query
    name: batch
    description: Stores the document in batch mode. To use, set the value to ok.
    type: string
    required: false
  changes_body:
    in: body
    name: ChangesBody
    description: The request body
    schema:
      properties:
        limit:
          description: Limits the number of result rows to the specified value. Using a value of 0 has the same effect as the value 1.
          type: integer
        style:
          description: 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.
          type: string
          default: 'main_only'
        active_only:
          description: 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.
          type: boolean
          default: false
        include_docs:
          description: Default is false. Indicates whether to include the associated document with each result. If there are conflicts, only the winning revision is returned.
          type: boolean
          default: false
        filter:
          description: Indicates that the returned documents should be filtered. The valid values are sync_gateway/bychannel and _doc_ids.
          type: string
        channels:
          description: 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.)
          type: string
        doc_ids:
          description: 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.)
          type: array
          items:
            type: string
        feed:
          description: Default is 'normal'. Specifies type of change feed. Valid values are normal, continuous, longpoll, websocket.
          type: string
          default: 'normal'
        since:
          description: 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.
          type: object
        heartbeat:
          description: 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.
          type: integer
          default: 0
        timeout:
          description: 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.
          type: integer
          default: 300000
  filter:
    in: query
    name: filter
    description: Indicates that the reported documents should be filtered. The valid values are sync_gateway/bychannel and _doc_ids.
    type: string
    required: false
  logtags:
    in: body
    name: log_keys
    description: |
      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}`
    schema:
      type: object
      properties:
        All:
          type: boolean
          description: |
            Use the wildcard character `*` to set all log keys
            For example ```{"*":true}```
        none:
          type: boolean
          description: |
            Use "none" or "" as the key to disable all log keys.
            For example ```{"none":true}```
        Admin:
          type: boolean
          description: Admin processes in Sync Gateway.
        Access:
          type: boolean
          description: Anytime an access() call is made in the sync function.
        Auth:
          type: boolean
          description: Authentication.
        Bucket:
          type: boolean
          description: Sync Gateway interactions with the bucket (trace level only).
        Cache:
          type: boolean
          description: Interactions with Sync Gateway's in-memory channel cache.
        Changes:
          type: boolean
          description: Processing of /{db}/_changes requests.
        CRUD:
          type: boolean
          description: Updates made by Sync Gateway to documents.
        DCP:
          type: boolean
          description: DCP-feed processing.
        Events:
          type: boolean
          description: Event processing (webhooks).
        gocb:
          type: boolean
          description: All logging emitted by the GoCB SDK
        HTTP:
          type: boolean
          description: All requests made to the Sync Gateway REST APIs.
        HTTP+:
          type: boolean
          description: Additional information about HTTP requests (response times, status codes).
        Import:
          type: boolean
          description: 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.
        Javascript:
          type: boolean
          description: All logging from Javascript. This includes -- sync function, import filters, webhook filter function, and the custom ISGR conflict resolvers
        Migrate:
          type: boolean
          description: Logs messages thhat show when old inline document metdata is upgraded to xattrs
        Query:
          type: boolean
          description: Query is used for Sync Gateway code related to N1QL queries
        Replicate:
          type: boolean
          description: |
            Log messages related to replications between Sync Gateways (using sg-replicate). This tag cannot be used for replications initiated by Couchbase Lite.
        SGCluster:
          type: boolean
          description: Log messages related to the sharded import and HA sg-replicate
        Sync:
          type: boolean
          description: Activity which relates to synchronization between Couchbase Lite and Sync Gateway
        SyncMsg:
          type: boolean
          description: Can be used for additional Sync logging output
        WS:
          type: boolean
          description: Websocket replication log messages
        WSFrame:
          type: boolean
          description: Can be used for additional WS logging output
  level:
    in: query
    name: level
    description: |
      **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
    type: integer
  logLevel:
    in: query
    name: logLevel
    description: |
      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`.

    type: string
  sgcollect_info:
    in: body
    name: sgcollect_info
    description: Options that can be specified to use in an sgcollect_info run
    schema:
      type: object
      properties:
        redact_level:
          type: string
          description: Can be set to `none` or `partial` for redaction of collected logs.
          default: none
        redact_salt:
          type: string
          description: If set, use this salt when redacting logs.
          required: false
        output_dir:
          type: string
          description: Where to store the collected zip.
          default: configured `LogFilePath` location (e.g. `/home/sync_gateway/logs`)
        upload:
          type: boolean
          description: Whether to upload the collected logs.
          default: false
        upload_host:
          type: string
          description: s3 URL for upload.
          default: https://uploads.couchbase.com
        customer:
          type: string
          description: Customer name to use when uploading logs.
          required: true if upload is set
        ticket:
          type: string
          description: Zendesk ticket number to use when uploading logs.
          required: false
  name:
    in: path
    name: name
    description: |
      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](https://en.wikipedia.org/wiki/Percent-encoding).

      When passing a user name in a URL path it must be escaped again using percent encoding e.g. 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"
    type: string
    required: true
  replicate__replication-body:
    in: body
    name: ReplicationBody
    description: The request message body is a JSON document that contains the following objects.
    schema:
      type: object
      properties:
        source:
          type: string
          description: 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.
        target:
          type: string
          description: Identifies the database to copy revisions to. Same format and interpretation as source.
        continuous:
          type: boolean
          description: Specifies whether the replication should be in continuous mode.
        filter:
          type: string
          description: 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.
        query_params:
          type: object
          description: 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).
        replication_id:
          type: string
          description: 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.

        cancel:
          type: boolean
          description: 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.
        changes_feed_limit:
          type: integer
          description: The maximum number of change entries to pull in each loop of a continuous changes feed.
          default: 50
  revs_limit:
    in: query
    name: revs_limit
    description: The number of revisions to include in the response from the document history. This parameter is only honoured if the `revs=true` querystring parameter is also sent in the request. If `revs=true` is specified and `revs_limit` isn't, the full revision history is returned.
    type: integer
    required: false
  show_exp:
    in: query
    name: show_exp
    description: Whether to show the _exp property in the response.
    type: boolean
    default: false
    required: false
  user:
    in: body
    name: body
    description: Request body
    schema:
      type: object
      properties:
        name:
          type: string
          description: |
            Name of the user that will be created, 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](https://en.wikipedia.org/wiki/Percent-encoding).

            When passing a user name in a URL path it must be escaped again using percent encoding e.g. 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"
        password:
          type: string
          description: Password of the user that will be created. Required, unless the `allow_empty_password` Sync Gateway per-database configuration value is set to true, in which case the password can be omitted. All active sessions for the user are invalidated when the password is changed.
        admin_channels:
          type: array
          description: Array of channel names to give the user access to
          items:
            type: string
            description: Channel name
        admin_roles:
          type: array
          description: Array of role names to assign to this user
          items:
            type: string
            description: Role name
        email:
          type: string
          description: Email of the user that will be created.
        disabled:
          type: boolean
          description: Boolean property to disable this user. The user will not be able to login if this property is set to true.
  upgrade_preview:
    in: query
    name: preview
    description: Lists the design documents to be removed if the request is sent without this paramter.
    type: boolean
    default: false
    required: false
tags:
  - name: attachment
    description: Groups all endpoints for attachment activities
  - name: auth
    description: Groups all endpoints for authentication activities
  - name: database
    description: Groups all endpoints for database activities
  - name: document
    description: Groups all endpoints for document-based activities
  - name: query
    description: Groups all endpoints for query-based activities
  - name: replication
    description: Groups all endpoints for sync and replication activities
  - name: role
    description: Groups all endpoints for role-based activities
  - name: server
    description: Groups all endpoints for server activities
  - name: session
    description: Groups all endpoints for session activities
  - name: user
    description: Groups all endpoints for user-based activities