swagger: '2.0'
info:
  title: Sync Gateway
  description: |+
    This yaml API spec documents the Sync Gateway Public REST API.

    The swagger spec isn't officially supported or actively maintained.
    It is offered as a convenient starting point for developers.
  version: '2.0'
# the domain of the service
host: localhost:4984
# array of all schemes that your API supports
schemes:
- http
- https
# Security schemes available
securityDefinitions:
  basicAuth:
    type: basic
    description: HTTP Basic Authentication
  apiKey:
    name: Cookie
    type: apiKey
    in: header
# Security schemes applied for the API as a whole
security:
- apiKey: []
# will be prefixed to all paths
basePath: /
produces:
- application/json

# TAGS
tags:
  - name: Attachment
    description: Work with attachments
  - name: Authentication
    description: Work with authentication
  - name: Database
    description: Work with databases
  - name: Document
    description: Work with documents
  - name: 'Document (local)'
    description: Work with local documents
  - name: Server
    description: Work with the server
  - name: Session
    description: Work with sessions
################################################################################
#                                   Parameters                                 #
################################################################################
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
  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: |+
      The `heartbeat` defines the interval (in milliseconds) at which an empty line (CRLF) is written to the response. It helps prevent Sync Gateway from deciding the socket is idle and closing it.

      The `heartbeat` value overrides any `timeout` value, to keep the feed alive indefinitely.

      Setting `heartbeat=0` results in no heartbeat.

      **Default:** 0, which is no heartbeat

      **Constraints:**

      - Applies ONLY where `feed=longpoll` or `feed=continuous`.

      - Minimum: 25000 (25 seconds)

      - Maximum: None -- unless you define one in your configuration file using `MaxHeartbeat`

    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.
    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
  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
  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: string
    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
    type: integer
    default: 300000
    description: |+
      The `timeout` value defines the maximum period (in milliseconds) to wait for a change, before sending a response. This wait applies even when there are no results.

      Setting `timeout=0` results in no timeout.

      **Default:** 300000 (5 minutes/300 seconds)

      **Constraints:**

      - Applies ONLY where `feed=longpoll` or `feed=continuous`.

      - Minimum: 0, no timeout

      - Maximum: 1500000 (15 minutes)

  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: |+
            The `heartbeat` defines the interval (in milliseconds) at which an empty line (CRLF) is written to the response. It helps prevent Sync Gateway from deciding the socket is idle and closing it.

            The `heartbeat` value overrides any `timeout` value, to keep the feed alive indefinitely.

            Setting `heartbeat=0` results in no heartbeat.

            **Default:** 0, which is no heartbeat

            **Constraints:**

            - Applies ONLY where `feed=longpoll` or `feed=continuous`

            - Minimum: 25000 (25 seconds)

            - Maximum: None -- unless you define one in your configuration file using `MaxHeartbeat`

          type: integer
          default: 0
        timeout:
          type: integer
          default: 300000
          description: |+
            The `timeout` value defines the maximum period (in milliseconds) to wait for a change, before sending a response. This wait applies even when there are no results.

            Setting `timeout=0` results in no timeout.

            **Default:** 300000 (5 minutes/300 seconds)

            **Constraints:**

            - Applies ONLY where `feed=longpoll` or `feed=continuous`

            - Minimum: 0, no timeout

            - Maximum: 1500000 (15 minutes)


  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: body
    description: Log keys to enable or disable.
    schema:
      type: object
      properties:
        '*':
          type: boolean
          description: Enabling log key "*" enables all logging tags automatically
        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.
  loglevel:
    in: query
    name: level
    description: |
      Verbosity of the logging. The default value is 1 which is regular logging. level=2 enables warnings and
      panics logging and level=3 will log panics only.
    type: integer
  name:
    in: path
    name: name
    description: User's name
    type: string
    required: true
  replication:
    in: body
    name: ReplicationBody
    description: The request message body is a JSON document that contains the following objects.
    schema:
      type: object
      properties:
        create_target:
          type: boolean
          description: Indicates whether to create the target database
        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
        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.
################################################################################
#                                   Paths                                      #
################################################################################
paths:
  /{db}/{doc}/{attachment}:
    parameters:
    - $ref: '#/parameters/db'
    - $ref: '#/parameters/doc'
    - $ref: '#/parameters/attachment'
    get:
      operationId: GetAttachment
      tags:
      - Attachment
      summary: Get Specific 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:
      operationId: UpdateAttachment
      tags:
      - Attachment
      summary: Create or Update Specific 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.
  /{db}/_bulk_docs:
    parameters:
    - $ref: '#/parameters/db'
    post:
      operationId: UpdateDocsInBulk
      tags:
      - Database
      summary: Create, Update or Delete 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:
              properties:
                id:
                  type: string
                  description: Design document identifier
                rev:
                  type: string
                  description: Revision identifier

        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:
      operationId: GetServerInfo
      tags:
      - Server
      summary: Get Server Data
      description: |
        Returns meta-information about the server.
      responses:
        200:
          description: Meta-information about the server.
          schema:
            $ref: '#/definitions/ServerData_model'
  /{db}/_bulk_get:
    parameters:
    - $ref: '#/parameters/db'
    post:
      operationId: GetDocsInBulk
      tags:
      - Database
      summary: Get Bulk Documents
      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:
      operationId: GetLocalDoc
      tags:
      - 'Document (local)'
      summary: Get Specific Local Document
      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 local documents mostly 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:
      operationId: AddOrUpdateLocalDoc
      tags:
      - 'Document (local)'
      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:
      operationId: DeleteLocalDoc
      tags:
      - 'Document (local)'
      summary: Delete Specific 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:
      operationId: GetChanges
      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: Get Changes Feed (query parameters)
      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:
      operationId: GetChangesWithParametersInBody
      tags:
      - Database
      parameters:
      - $ref: '#/parameters/changes_body'
      summary: Get Changes Feed (body parameters)
      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:
      operationId: GetDocument
      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 Specific 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:
      operationId: AddOrUpdateDocument
      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 Specific 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 behavior of the expiry feature changes in the following way: when the expiry value is reached, instead of getting purged, the **active** revision of the document is tombstoned.
        If there is another non-tombstoned revision for this document (i.e a conflict) it will become the active revision.
        The tombstoned revision will be purged when the server's metadata purge interval is reached.
      responses:
        200:
          description: The response is a JSON document that contains the following objects
          schema:
            $ref: '#/definitions/Success'
    delete:
      operationId: DeleteDocument
      tags:
      - Document
      parameters:
      - $ref: '#/parameters/rev_delete'
      summary: Delete Specific 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}/_all_docs:
    parameters:
    - $ref: '#/parameters/db'
    get:
      operationId: GetAllDocs
      tags:
      - Database
      summary: Get 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:
      operationId: GetAllDocsWithParametersInBody
      tags:
      - Database
      summary: Get All Specified Documents
      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:
      operationId: GetOpenID
      tags:
      - Authentication
      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:
      operationId: GetOpenIDAuthCallBack
      tags:
      - Authentication
      summary: Get OIDC 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:
      operationId: GetOpenIDAuth
      tags:
      - Authentication
      summary: Get OIDC 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:
      operationId: GetOpenIDRefreshToken
      tags:
      - Authentication
      summary: Get OIDC 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.
  /{db}/_facebook:
    parameters:
      - $ref: '#/parameters/db'
    post:
      operationId: AuthenticationViaFacebook
      tags:
      - Authentication
      summary: Get Facebook Authenticated Session
      description: |+
        Sync Gateway allows users to authenticate using a Facebook account.

        Your application is responsible for generating a Facebook token; this generally needs to be done by running the Facebook login flow inside a web-view and capturing the generated token.
        This endpoint can be used to check the validity of the access token.
        To allow Facebook Login with Sync Gateway, it must be explicitly enabled in the Sync Gateway configuration file by setting the [facebook.register](config-properties.html#facebook-register) property to `true`.
      parameters:
        - in: body
          name: body
          description: Request body
          schema:
            type: object
            properties:
              access_token:
                type: string
                description: The access token for the user to authenticate
      responses:
        200:
          description: Session successfully created. The Set-Cookie response header contains the session credentials.
          schema:
            $ref: '#/definitions/Session'
        401:
          #name: Unauthorized
          description: Facebook verification server status <Facebook status code>
        502:
          #name: Bad Gateway
          description:  Invalid response from Facebook verifier
  /{db}/_google:
    parameters:
      - $ref: '#/parameters/db'
    post:
      operationId: AuthenticationViaGoogle
      tags:
      - Authentication
      summary: Get Google Authenticated Session
      description: |+
        Sync Gateway allows users to authenticate using a Google account.

        Your application is responsible for generating a Google token; this generally needs to be done by running the Google login flow inside a web-view and capturing the generated token.
        This endpoint can be used to check the validity of the access token.
        To allow Google Login with Sync Gateway, it must be explicitly enabled in the Sync Gateway configuration file by setting the [google.register](config-properties.html#google-register) property to `true` and setting the [google.app_client_id](config-properties.html#google-app_client_id) property with a Google app client ID.
      parameters:
        - in: body
          name: body
          description: Request body
          schema:
            type: object
            properties:
              id_token:
                type: string
                description: The access token for the user to authenticate
      responses:
        200:
          description: Session successfully created. The Set-Cookie response header contains the session credentials.
          schema:
            $ref: '#/definitions/Session'
        401:
          #name: Unauthorized
          description: Returns the Google response's ErrorDescription
        502:
          #name: Bad Gateway
          description:  Invalid response from Google token verifier
  /{db}/_revs_diff:
    parameters:
    - $ref: '#/parameters/db'
    post:
      operationId: GetRevisionIds
      tags:
      - Database
      summary: Get Revision ID Diff
      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).
                  items:
                    type: string
  /{db}/:
    parameters:
    - $ref: '#/parameters/db'
    get:
      operationId: GetDatabaseInfo
      tags:
      - Database
      summary: Get Database Data
      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:
      operationId: AddDocument
      tags:
      - Document
      summary: Create New 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'
  /{db}/_session:
    parameters:
    - $ref: '#/parameters/db'
    post:
      operationId: AddUserSession
      tags:
      - Session
      summary: Create User 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.
            password:
              type: string
              description: User password.
      responses:
        200:
          description: Session successfully created. The Set-Cookie response header contains the session credentials.
          schema:
            $ref: '#/definitions/Session'
    delete:
      operationId: DeleteUserSession
      tags:
      - Session
      summary: Delete User Session
      description: |
        This request deletes the session that currently authenticates the requests.
      parameters:
      - in: header
        name: cookie
        description: The cookie of the logged-in session.
        type: string
      responses:
        200:
          description: The session was successfully removed.
################################################################################
#                                 Definitions                                  #
################################################################################
definitions:
  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
  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
  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: ["*"]
  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: Name of the user that will be created
      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: 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
      all_channels:
        type: array
        description: Array of channel names the user is given access to
        items:
          type: string
          description: Channel 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.
      roles:
        type: array
        description: Array of role names the user is given access to
        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
      deleted:
        type: boolean
        description: Indicate whether the row is deleted
        default: false
      doc:
        type: object
  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.
  Replication:
    type: object
    properties:
      ok:
        type: boolean
        description: Indicates whether the replication operation was successful
      session_id:
        type: string
        description: Session identifier
  ServerData_model:
    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. `!` is the public channel and every user has access to it.
      name:
        type: string
        description: The user's name.
