IBM Cloud API Docs

Introduction

IBM® Cloudant® for IBM Cloud® is a document-oriented database as a service (DBaaS). It stores data as documents in JSON format. It is built with scalability, high availability, and durability in mind. It comes with a wide variety of indexing options that include MapReduce, IBM Cloudant Query, and full-text indexing. The replication capabilities make it easy to keep data in sync between database clusters, desktop PCs, and mobile devices.

Detailed documentation is also available such as a Getting started tutorial, API overview documentation, tutorials, and guides.

If you intend to store sensitive information in an IBM® Cloudant® for IBM Cloud® database you must use client-side encryption to render data unreadable to Cloudant operators. For example for PCI DSS compliance you must encrypt the Primary Account Number (PAN) before sending a document containing it to the database.

This documentation describes the SDKs and examples. To see usage information and examples in your preferred SDK, select the language tab in the right pane.

This documentation describes the Java SDK and examples. To see usage information and examples in your preferred SDK, select the language tab in the right pane.

This documentation describes the Node SDK and examples. To see usage information and examples in your preferred SDK, select the language tab in the right pane.

This documentation describes the Python SDK and examples. To see usage information and examples in your preferred SDK, select the language tab in the right pane.

This documentation describes the Go SDK and examples. To see usage information and examples in your preferred SDK, select the language tab in the right pane.

The code examples on this tab use the IBM Cloudant SDK for Java&trade.

Gradle

implementation 'com.ibm.cloud:cloudant:0.+'

Maven

GitHub

The code examples on this tab use the IBM Cloudant SDK for Node.js.

Installation

npm install --save @ibm-cloud/cloudant

GitHub

The code examples on this tab use the IBM Cloudant SDK for Python.

Installation

pip3 install ibmcloudant

GitHub

The code examples on this tab use the IBM Cloudant SDK for Go.

Installation

go get -u github.com/IBM/cloudant-go-sdk/cloudantv1

GitHub

Endpoint URLs

The IBM Cloudant API uses an instance-specific endpoint URL for all regions. You can find your external endpoint by following these steps:

  1. Go to the IBM Cloud dashboard and open an instance.
  2. Click the Service credentials tab.
  3. Click the chevron next to the service credentials to open the credentials pane.
  4. Copy the value from the host field and prefix it with the https:// protocol. This value is the external endpoint.

For more information, see the Locating your service credentials tutorial.

Or you can copy your external endpoint by following these steps:

  1. Go to the IBM Cloud dashboard and open an instance.
  2. Under the Manage tab on the Overview page, see the External endpoint in the table.
  3. Click Copy to copy the External endpoint. Paste the endpoint where you need your credentials.

A public endpoint looks something like these examples:

https://5lll032-dd12-536e-09b3-432fg9f07e78-bluemix.cloudantnosqldb.appdomain.cloud

or

https://5lll032-dd12-536e-09b3-432fg9f07e78-bluemix.cloudant.com

A private endpoint is one that is only accessible through a non-public network, like IBM's internal network. Private endpoints are available to customers who have the Dedicated Hardware plan.

Authentication

You can access IBM Cloudant with IBM Cloud® Identity and Access Management (IAM) or IBM Cloudant legacy access controls. The choice between Use only IAM and Use both legacy credentials and IAM access control affects how credentials are delivered to your application when you bind and generate service credentials.

The Use only IAM option is preferred. Review Must I use Use only IAM or Use both legacy credentials and IAM? to help with making a decision.

IAM authentication

Access to IBM Cloudant is centrally controlled by IBM Cloud® Identity and Access Management (IAM), which provides a unified approach to managing user identities, and access control across your IBM Cloud® services and applications using the same set of credentials.

To work with the API, authenticate your application or service by including your IBM Cloud® IAM access token in API requests.

Cloudant legacy authentication

Legacy access controls are unique to IBM Cloudant, which means that accessing each service instance requires its own set of credentials. These credentials can be used with HTTP basic and cookie authentication. IBM Cloudant legacy API keys authenticate identically to username and password credentials but are generated and assigned differently. For more information, see the documentation about IBM Cloudant legacy API keys.

Additional authentication resources

  • IBM Cloudant client libraries provide full integration with IAM's access controls and automatically retrieve an IAM access token when an appropriate IAM configuration is provided (for example, an IAM API key or IAM profile ID).
  • View IBM Cloudant authentication documentation.

Security scheme

Authentication to this API's methods uses one of the following security schemes.

Basic

Valid only for IBM Cloudant legacy authentication (including legacy IBM Cloudant API keys).

Authenticates with a Authorization: Basic {credentials} header where credentials is the Base64 encoding of your username and password joined by a single colon :.

Value
  • HTTP
  • Basic

Cookie

Valid only for IBM Cloudant legacy authentication (including legacy IBM Cloudant API keys).

Login session cookies can be created via the POST /_session endpoint and returned in the standard Set-Cookie header. This AuthSession cookie can be stored and returned to the server in the Cookie header on subsequent requests. This process is handled automatically by IBM Cloudant's SDKs and other cookie aware HTTP clients like browsers.

Value
  • API Key
  • Cookie
  • AuthSession

IAM

Valid only for Cloud Identity and Access Management authentication.

Authenticates with a Authorization: Bearer {access_token} header where access_token is calculated from an appropriate IAM configuration (for example from an IAM API key, or IAM profile ID). This process is handled automatically by IBM Cloudant's SDKs.

Value
  • HTTP
  • JWT
  • Bearer

Authentication with external configuration

In this scenario, the configuration is defined with an external credentials file and an authenticator that is constructed by SDK's authenticator factory during client initialization. Using the external credentials file avoids hardcoded credentials within the application code.

The default name of the credentials file is ibm-credentials.env. It is expected to be located in either the current directory or in the user's home directory. The path and name of the file can be controlled by using the IBM_CREDENTIALS_FILE environment variable.

Cloudant configuration properties start with a chosen service name prefix that identifies your service. By default it is CLOUDANT.

If you would like to rename your Cloudant service from CLOUDANT, or use multiple services at the same time you must use your defined service name as the prefix for all of your Cloudant related configuration properties. You also must use the same service name at instantiating your service.

This way, each configuration property includes both the name of the service and the specific attribute, combined in a format like CLOUDANT_APIKEY.

It is not necessary to use a .env file. These properties can be set by using environment variables with the same name in the environment where the application is run.

Variable guide for the authentication code samples

Table 1. Variable signing guide
Attribute name Description
{apikey} IAM API key
{username} Cloudant username
{password} Cloudant password
{url} URL of Cloudant instance
{service-name} Chosen service name of your Cloudant instance.
Same as the prefix of your configuration properties.
Default value is CLOUDANT.

SDK managing the IAM token. Replace {apikey} and {url}.

{service-name}_URL={url}
{service-name}_APIKEY={apikey}
import com.ibm.cloud.cloudant.v1.Cloudant;

Cloudant service = Cloudant.newInstance("{service-name}");
import { CloudantV1 } from '@ibm-cloud/cloudant';

const service = CloudantV1.newInstance({
    serviceName: '{service-name}'
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance(service_name="{service-name}")
import (
    "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

service, err := cloudantv1.NewCloudantV1UsingExternalConfig(
    &cloudantv1.CloudantV1Options{
        ServiceName: "{service-name}",
    },
)

SDK managing session cookie.

{service-name}_AUTH_TYPE=COUCHDB_SESSION
{service-name}_URL={url}
{service-name}_USERNAME={username}
{service-name}_PASSWORD={password}
import com.ibm.cloud.cloudant.v1.Cloudant;

Cloudant service = Cloudant.newInstance("{service-name}");
import { CloudantV1 } from '@ibm-cloud/cloudant';

const service = CloudantV1.newInstance({
    serviceName: '{service-name}'
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance(service_name="{service-name}")
import (
    "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

service, err := cloudantv1.NewCloudantV1UsingExternalConfig(
    &cloudantv1.CloudantV1Options{
        ServiceName: "{service-name}",
    },
)

Basic authentication.

{service-name}_AUTH_TYPE=BASIC
{service-name}_URL={url}
{service-name}_USERNAME={username}
{service-name}_PASSWORD={password}
import com.ibm.cloud.cloudant.v1.Cloudant;

Cloudant service = Cloudant.newInstance("{service-name}");
import { CloudantV1 } from '@ibm-cloud/cloudant';

const service = CloudantV1.newInstance({
    serviceName: '{service-name}'
});
from ibmcloudant.cloudant_v1 import CloudantV1

service = CloudantV1.new_instance(service_name="{service-name}")
import (
    "github.com/IBM/cloudant-go-sdk/cloudantv1"
)

service, err := cloudantv1.NewCloudantV1UsingExternalConfig(
    &cloudantv1.CloudantV1Options{
        ServiceName: "{service-name}",
    },
)

Programmatic authentication

In this scenario, authentication is configured by constructing an authenticator instance, supplying the configuration attributes programmatically, and then passing this instance to a client constructor.

If you are using the IBM Cloud App Service, IBM Cloud® Continuous Delivery or IBM Cloud starter kits then you can programmatically configure your SDK using the IBMCloudEnv tool to obtain the configuration information from bound services. The IBMCloudEnv tool is available for Go, Java&trade (Spring), Node.js, and Python.

SDK managing the IAM token.

import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.sdk.core.security.IamAuthenticator;

IamAuthenticator authenticator = new IamAuthenticator.Builder()
    .apikey("{apikey}")
    .build();

Cloudant service = new Cloudant(Cloudant.DEFAULT_SERVICE_NAME, authenticator);

service.setServiceUrl("{url}");
import { CloudantV1 } from '@ibm-cloud/cloudant';
import { IamAuthenticator } from 'ibm-cloud-sdk-core';

const authenticator = new IamAuthenticator({
    apikey: '{apikey}'
});

const service = new CloudantV1({
    authenticator: authenticator
});

service.setServiceUrl('{url}');
from ibmcloudant.cloudant_v1 import CloudantV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

authenticator = IAMAuthenticator('{apikey}')

service = CloudantV1(authenticator=authenticator)

service.set_service_url('{url}')
import (
    "github.com/IBM/cloudant-go-sdk/cloudantv1"
    "github.com/IBM/go-sdk-core/core"
)

authenticator := &core.IamAuthenticator{
    ApiKey: "{apikey}",
}

service, err := cloudantv1.NewCloudantV1(
    &cloudantv1.CloudantV1Options{
        URL:           "{url}",
        Authenticator: authenticator,
    },
)
if err != nil {
    panic(err)
}

SDK managing session cookie.

import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.sdk.core.security.Authenticator;
import com.ibm.cloud.cloudant.security.CouchDbSessionAuthenticator;

Authenticator authenticator = CouchDbSessionAuthenticator.newAuthenticator("{username}", "{password}");

Cloudant service = new Cloudant(Cloudant.DEFAULT_SERVICE_NAME, authenticator);

service.setServiceUrl("{url}");
import { CloudantV1, CouchdbSessionAuthenticator } from '@ibm-cloud/cloudant';

const authenticator = new CouchdbSessionAuthenticator({
    username: '{username}',
    password: '{password}'
});

const service = new CloudantV1({
    authenticator: authenticator
});

service.setServiceUrl('{url}');
from ibmcloudant.cloudant_v1 import CloudantV1
from ibmcloudant import CouchDbSessionAuthenticator

authenticator = CouchDbSessionAuthenticator('{username}', '{password}')

service = CloudantV1(authenticator=authenticator)

service.set_service_url('{url}')
import (
    "github.com/IBM/cloudant-go-sdk/cloudantv1"
    "github.com/IBM/cloudant-go-sdk/auth"
)

authenticator, err := auth.NewCouchDbSessionAuthenticator(
    "{username}",
    "{password}",
)
if err != nil {
    panic(err)
}

service, err := cloudantv1.NewCloudantV1(
    &cloudantv1.CloudantV1Options{
        URL:           "{url}",
        Authenticator: authenticator,
    },
)
if err != nil {
    panic(err)
}

Basic authentication.

import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.sdk.core.security.BasicAuthenticator;

BasicAuthenticator authenticator = new BasicAuthenticator.Builder()
    .username("{username}")
    .password("{password}")
    .build();

Cloudant service = new Cloudant(Cloudant.DEFAULT_SERVICE_NAME, authenticator);

service.setServiceUrl("{url}");
import { CloudantV1 } from '@ibm-cloud/cloudant';
import { BasicAuthenticator } from 'ibm-cloud-sdk-core';

const authenticator = new BasicAuthenticator({
    username: '{username}',
    password: '{password}'
});

const service = new CloudantV1({
    authenticator: authenticator
});

service.setServiceUrl('{url}');
from ibmcloudant.cloudant_v1 import CloudantV1
from ibm_cloud_sdk_core.authenticators import BasicAuthenticator

authenticator = BasicAuthenticator('{username}', '{password}')

service = CloudantV1(authenticator=authenticator)

service.set_service_url('{url}')
import (
    "github.com/IBM/cloudant-go-sdk/cloudantv1"
    "github.com/IBM/go-sdk-core/core"
)

authenticator, err := core.NewBasicAuthenticator(
    "{username}",
    "{password}",
)
if err != nil {
    panic(err)
}

service, err := cloudantv1.NewCloudantV1(
    &cloudantv1.CloudantV1Options{
        URL:           "{url}",
        Authenticator: authenticator,
    },
)
if err != nil {
    panic(err)
}

Error handling

IBM Cloudant operation uses standard HTTP response codes to indicate the status of the operation. HTTP response codes in the 2xx range indicate success. A 4xx range indicates a failure, and a 5xx range usually indicates an internal system error. More detailed error information is available in the body of the response.

For some HTTP requests, for example bulk operations, a 2xx response may indicate overall request success, but individual actions may have failed. For these cases the HTTP status code is insufficient to indicate success or failure and the caller must inspect the response body contents.

List of HTTP status codes and meanings
HTTP Code Meaning
200 - OK Request completed successfully.
201 - Created Resource created or updated successfully. The resource could be a database or a document, for example.
202 - Accepted Request accepted, but failed to meet the quorum for the operation.
206 - Partial Content Request was successful and the body contains the ranges of data, as described in the Range header of the request.
304 - Not Modified The requested content has not changed. The ETag system that identifies the version of information returned uses this code.
400 - Bad Request Bad request structure. The error can indicate an error with the request URL, path, or headers. Differences in the supplied MD5 hash and content also trigger this error, as this error might indicate message corruption.
401 - Unauthorized The item requested was not available with the supplied authorization, or authorization was not supplied.
402 - Payment required Either the account is in arrears or the amount of data exceeds the plan quota. You can delete data, upgrade plan, or bring the account up to date.
403 - Forbidden The server forbids access to the requested item or operation.
404 - Not Found The requested resource does not exist or is not visible. The content includes further information as a JSON object, if available. The structure contains two keys, error and reason, similar to the following example: { "error":"not_found", "reason":"no_db_file" }
405 - Resource Not Allowed A request was made by using an invalid HTTP request type for the URL requested. For example, you requested a PUT when a POST is expected. Errors of this type can also be triggered by invalid URL strings.
406 - Not Acceptable The requested response content type is not supported by the server.
408 - Request Timeout Timeout during reading client request.
410 - Gone The requested resource is no longer available.
409 - Conflict Request resulted in an update conflict. The two most common causes are firstly, trying to update or delete a document without providing a revision and secondly, that the latest revision of the document on the server changed between a fetch and an update.
412 - Precondition Failed The request headers from the client and the capabilities of the server do not match. Alternatively, a request to create a database was denied because the database exists.
413 - Request Entity Too Large The request size exceeded the limit for the IBM Cloudant API.
415 - Bad Content Type The content type of the request is not supported by the server.
416 - Requested Range Not Satisfiable The server cannot satisfy the range specified in the request header.
429 - Too Many Requests The user sent too many requests in a specific amount of time. More information is available in the corresponding RFC 6585.
500 - Internal Server Error The server could not complete the request. It could be due to an internal error or sometimes invalid data in the request.
502 - Bad Gateway The server while acting as a gateway or proxy, received an invalid response from the upstream server.
503 - Service Unavailable The service is not available for the request. Seeing this response might indicate a misspelled IBM Cloudant account name.
504 - Gateway Timeout Timeout when the server is acting as a gateway and cannot get a response in time.

IBM Cloudant HTTP API requests may also fail due to external factors, for example, network errors. These kinds of errors may prevent the server receiving the request or the client receiving the HTTP response. As a result the error format is different in these cases.

Error response

General error response body properties
Name Description
error string the error message returned in the response
reason string a more detailed description about the cause of the failure
caused_by (optional) string the cause of the error
Error response body properties specific to /_api/v2 endpoints
Name Description
code integer HTTP error code
error string a more detailed description about the cause of the failure code
Alternative error response body properties specific to some /_api/v2 endpoints
Name Description
message string detailed description about the cause of the failure

The HTTP response headers may contain additional information useful for tracing errors.

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET 'https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products'

Error response

{
  "error": "not_found",
  "reason": "Database does not exist."
}

Error Responses specific to /_api/v2/ endpoints

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" 'https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/_api/v2/db/products/_security'
{
  "code": 400,
  "error": "No DB products belonging to 00000000-0000-0000-0000-000000000000-bluemix"
}
curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -d '' 'https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/_api/v2/user/capacity/throughput'
{
    "message": "The method is not allowed for the requested URL."
}

Error response

When the Go SDK receives an error response from the server endpoint it returns a standard Go error. The Error() function of the error returns either the HTTP response error message or a generic error message.

In addition to an error SDK operations may also return a DetailedResponse with methods to retrieve additional information.

Fields and methods available from a DetailedResponse
Field Method Description
StatusCode GetStatusCode HTTP response status code.
Result GetResultAsMap JSON error response object unmarshalled as map[string]interface{}.
RawResult GetRawResult Raw error response body as []byte.
Additional information available from the DetailedResponse Result map
Key Value description
message Human readable and printable error message of error and reason.
error Error type, for example not_found.
reason Error reason, for example Database does not exist.
caused_by Additional error cause information if available.
trace Trace UUID from the X-Request-ID or X-Couch-Request-ID response header.

Other errors

HTTP API requests may also fail with other error conditions, for example, validation or networking issues.

For errors unrelated to the HTTP status code the SDK still returns a standard Go error. However, the DetailedResponse information is absent or limited.

An example would be an HTTP request that the server terminates when it exceeds a timeout. In this case the request returns a DetailedResponse with only a StatusCode. The Result and RawResult elements are nil.

Argument validation prevents some invalid values and the SDK does not send the request. This results in Result and RawResult being nil, and a returned error message with no status code or reason.

In all other cases, DetailedResponse is nil because there is no JSON error response from the IBM Cloudant Service.

Example error handling

import (
	"encoding/json"
	"fmt"

	"github.com/IBM/cloudant-go-sdk/cloudantv1"
	"github.com/IBM/go-sdk-core/v5/core"
)

func errorHandlingExample() {
	service, err := cloudantv1.NewCloudantV1(
		&cloudantv1.CloudantV1Options{},
	)
	if err != nil {
		panic(err)
	}

	getDatabaseInformationOptions := service.NewGetDatabaseInformationOptions(
		"products",
	)

	var response core.DetailedResponse
	databaseInformation, response, err := service.GetDatabaseInformation(getDatabaseInformationOptions)
	if err != nil {
		// Use the DetailedResponse to check the HTTP status code
		if response.StatusCode == 404 {
			// Handle database not existing, maybe create it
		} else {
			fmt.Println("Error: ", err.Error())
			fmt.Println("Error status code: ", response.StatusCode)
			// Handle other errors
			errorMap, ok := response.GetResultAsMap()
			if ok {
				// Get the request UUID for what went wrong
				fmt.Println("Trace request UUID: ", errorMap["trace"])
			} else {
				// For example to handle non-JSON response bodies
				fmt.Println("Raw error response: ", response.RawResult)
			}
		}
	}

	b, _ := json.MarshalIndent(databaseInformation, "", "  ")
	fmt.Println(string(b))
}

Error response

When the Java SDK receives an error response from the server endpoint it throws a RuntimeException. Specifically a subclass of ServiceResponseException from the com.ibm.cloud.sdk.core.service.exception package. The specific subclass depends on the error encountered.

ServiceResponseException types
Exception class Description including HTTP status code where applicable
ServiceResponseException Super class for all service response exceptions.
BadRequestException 400 Bad Request.
UnauthorizedException 401 Unauthorized.
ForbiddenException 403 Forbidden.
NotFoundException 404 Not Found.
NotAcceptableException 406 Not Acceptable.
ConflictException 409 Conflict.
RequestTooLargeException 413 Request Entity Too Large.
UnsupportedException 415 Unsupported media type.
TooManyRequestsException 429 Too Many Requests.
InternalServerErrorException 500 Internal server error.
ServiceUnavailableException 503 Service Unavailable.
InvalidServiceResponseException Could not process the response body. Most commonly caused when the server truncates a long running query that exceeded the time limit.

All ServiceResponseException types have methods to retrieve additional error information.

Methods available for ServiceRuntimeException types
Method Description
getStatusCode() HTTP response status code.
getMessage() Human readable and printable error message.
getDebuggingInfo() JSON error response body as a Map<String, Object>
getHeaders() HTTP response headers.
getResponseBody() Raw error response body as String.
Additional information available from the Map returned by getDebuggingInfo()
Key Value description
message Human readable and printable error message of error and reason.
error Error type, for example not_found.
reason Error reason, for example Database does not exist.
caused_by Additional error cause information if available.
trace Trace UUID from the X-Request-ID or X-Couch-Request-ID response header.

Other errors

HTTP API requests may also fail with other error conditions, for example, validation or networking issues.

For errors unrelated to the HTTP status code the SDK throws other RuntimeException types.

For example for many networking errors the SDK throws an IOException wrapped in a RuntimeException.

Argument validation prevents some invalid values and the SDK does not send the request. For these cases the SDK throws an IllegalArgumentException.

Other RuntimeException types
Exception class Description
RuntimeException Use getCause() to identify the underlying cause. Typically an IOException caused by networking issues.
IllegalArgumentException Invalid argument passed to the method.
IllegalStateException The operation cannot be performed, for example starting a changes follower that is already started.

Example error handling

import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.DatabaseInformation;
import com.ibm.cloud.cloudant.v1.model.GetDatabaseInformationOptions;
import com.ibm.cloud.sdk.core.service.exception.NotFoundException;
import com.ibm.cloud.sdk.core.service.exception.ServiceResponseException;

public class ErrorHandlingExample {

    public static void main() {
        Cloudant service = Cloudant.newInstance();

        GetDatabaseInformationOptions databaseInfoOptions =
                new GetDatabaseInformationOptions.Builder().db("products").build();

        try {
            DatabaseInformation response =
                    service.getDatabaseInformation(databaseInfoOptions).execute().getResult();
            System.out.println(response);
        } catch (NotFoundException e) {
            // Handle database not existing, maybe create it
        } catch (ServiceResponseException e) {
            System.out.println("Error: " + e.getMessage());
            System.out.println("Error status code: " + e.getStatusCode());
            System.out.println("Trace UUID: " + e.getDebuggingInfo().getOrDefault("trace", "No trace available"));
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }
}

Error response

When the Node SDK receives an error response from the server endpoint it creates an Error that contains either the HTTP response error message or a generic error message. The Promise returned from the SDK operation rejects with this Error.

For HTTP response errors the properties of the of Error include additional information.

Error properties for HTTP response errors
Property Description
status HTTP response status code.
statusText Text description of the status code.
message Human readable and printable error message.
result Error JSON response body as an object.
body Raw error response body as a string.
Additional information available from the result for JSON error bodies
Key Value description
error Error type, for example not_found.
reason Error reason, for example Database does not exist.
caused_by Additional error cause information if available.
trace Trace UUID from the X-Request-ID or X-Couch-Request-ID response header.

Other errors

HTTP API requests may also fail with other error conditions, for example, validation or networking issues.

For errors unrelated to the HTTP status code the SDK still rejects with an Error. However, the available error properties may be more limited.

For these errors message still provides a summary of the problem. There is no status defined since there is no HTTP response status code. The statusText or body contain additional information.

When an error prevents the request reaching the service the Error code property may be useful.

An example is argument validation that prevents some invalid values and the SDK does not send the request. Invalid argument values reject with an Error object containing a code field with the value ERR_INVALID_ARG_VALUE.

Error properties for other errors
Property Description
message Human readable and printable error message.
statusText Text description of the status code.
body Raw error response body as a string.
code Code for some errors that occur before sending a request.

Example error handling

import { CloudantV1 } from '@ibm-cloud/cloudant';

function errorHandlingExample() {
  const service = CloudantV1.newInstance({});

  return service.getDatabaseInformation({ db: "products"})
    .then(response => {
      console.log(response.result);
    }).catch((error) => {
      console.log(`Error message:      ${error.message}`);
      console.log(`Error status text:  ${error.statusText}`);
      if (error.status) {
        if (error.status === 404) {
          // Handle database not existing, maybe create it
        } else {
          console.log(`Error status code:  ${error.status}`);
          console.log(`Trace request UUID: ${error?.result?.trace}`);
        }
      } else if (error.code) {
        console.log(`Error code:         ${error.code}`);
      } else {
        console.log(`Error body:         ${error.body}`);
      }
    });
}

await errorHandlingExample();

Error response

When the Python SDK receives an error response from the server endpoint it raises a standard Python Exception. For HTTP response errors the subclass is ApiException from the ibm_cloud_sdk_core module. The ApiException includes more information about the cause of the failure.

Attributes of ApiException for HTTP response errors
Attribute Description
code HTTP response status code
message Human readable and printable error message.
http_response Raw requests.response object for the HTTP response body.

Use the json() method of the http_response attribute to obtain even more detailed error information.

Additional information available from http_response.json() dict for JSON error bodies
Key Value description
error Error type, for example not_found.
reason Error reason, for example Database does not exist.
caused_by Additional error cause information if available.
trace Trace UUID from the X-Request-ID or X-Couch-Request-ID response header.

Other errors

HTTP API requests may also fail with other error conditions, for example, validation or networking issues.

For errors unrelated to the HTTP status code the SDK still raises an Exception. However, the available error properties are different.

Networking errors and issues like timeouts raise a requests.RequestException. Consult the requests documentation for details of the available subclasses for specific connection related error conditions.

Argument validation prevents some invalid values and the request is not sent. Invalid argument values raise a ValueError exception.

Example error handling

from ibmcloudant.cloudant_v1 import CloudantV1
from ibm_cloud_sdk_core import ApiException
from requests import RequestException

service = CloudantV1.new_instance()

try:
    response = service.get_database_information(db="products").get_result()
    print(response)
except ApiException as ae:
    print("Error message: " + ae.message)
    if ae.status_code == 404:
        # Handle database not existing, maybe create it
        pass
    else:
        print(f'Error status code: {ae.status_code}')
        if 'trace' in (debugInfo := ae.http_response.json()):
            print(f'Trace request UUID: {debugInfo["trace"]}')
except (RequestException, ValueError) as err:
    print(err)

Auditing

You can monitor API activity within your account by using the IBM Cloud® Activity Tracker service. An event is generated for most of the API endpoints when they are called, and you can then track and audit from within Activity Tracker. The specific event type is listed for each individual method. For methods that don't list any events, no events are generated.

For more information about how to track IBM Cloudant activity, see Audit logging.

Additional headers

IBM Cloudant uses HTTP. Set the correct HTTP request headers and process the response headers inline with the HTTP specification. This course of action ensures that you get the correct format and encoding. Different environments and clients are more or less strict on the effect of these HTTP headers, especially when they are not present. To reduce the likelihood of problems or unexpected behavior, be as specific as possible for your client environment.

IBM Cloudant SDKs handle required headers automatically. The SDKs also allow for setting some headers as part of the request options without needing to use custom header code.

You can pass additional request header parameters in all requests or in a single request to the service.

To pass header parameters in a single curl request, use the -H option.

To pass header parameters with every request, use the SetDefaultHeaders method of the service object.

To pass header parameters in a single request, use SetHeaders to include the headers in the options struct before calling the operation.

You can pass request header parameters in all requests or in a single request to the service.

To pass header parameters with every request, use the setDefaultHeaders method of the service object.

To pass header parameters in a single request, use the addHeader method as a modifier before you execute the request.

You can pass request header parameters in all requests or in a single request to the service.

To pass header parameters with every request, specify the set_default_headers method of the service object.

To pass header parameters in a single request, include headers as a dict in the request.

You can pass request header parameters in all requests or in a single request to the service.

To pass header parameters with every request, specify the set_default_headers method of the service object.

To pass header parameters in a single request, include headers as a dict in the request.

Example header parameter in a request

curl -H 'Custom-Header:custom_value' -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud

Example header parameter in all requests

customHeaders := http.Header{}
customHeaders.Add("Custom-Header", "custom_value")
service.SetDefaultHeaders(customHeaders)

Example header parameter in a request

options := service.NewGetServerInformationOptions()

customHeaders := make(map[string]string)
customHeaders["Custom-Header"] = "custom_value"

options.SetHeaders(customHeaders)

serverInformation, response, err := service.GetServerInformation(options)

Example header parameter in all requests

Map<String, String> headers = new HashMap<String, String>();
headers.put("Customer-Header", "custom_value");

service.setDefaultHeaders(headers);

Example header parameter in a request

ServerInformation response = service.getServerInformation()
        .addHeader("Custom-Header", "custom_value")
        .execute();

Example header parameter in all requests

const service = CloudantV1.newInstance({
  headers: {
    'Custom-Header': 'custom_value',
  },
});

Example header parameter in a request

service.getServerInformation({
  headers: {
    'Custom-Header': 'custom_value'
  }
}).then(response => {
  console.log(response.result);
});

Example header parameter in all requests

headers = {
    'Custom-Header': 'custom_value'
}

service.set_default_headers(headers)

Example header parameter in a request

response = service.get_server_information(
    headers = {
        'Custom-Header': 'custom_value'
    })

Request headers

Additional supported HTTP request headers are:

  • Accept
  • Accept-Encoding
  • Content-Type
  • Content-Encoding
  • If-None-Match
  • Range
  • X-Request-ID

Accept

The Accept header specifies the list of potential data types returned by the server that the client accepts. The format is a list of one or more MIME types, separated by colons.

For the most requests, the accepted list must include JSON data (application/json).

For attachments, you can either specify the MIME type explicitly, or use */* to specify that the client accepts any type.

If the Accept header is not supplied, then the server assumes the */* MIME type, which means that the client accepts all formats.

The use of Accept in queries to IBM Cloudant is not required, but is highly recommended as it helps to ensure that the client can process the data returned.

If you specify a data type that uses the Accept header, IBM Cloudant honors the specified type in the Content-Type header field of responses. For example, if you explicitly request application/json in the Accept of a request, the returned HTTP headers use this value in the returned Content-Type field.

IBM Cloudant SDKs set this header automatically except for requests where the user controls the content type, for example, attachments.

Example of sending a request without an explicit Accept header, or when you specify */*.

GET /recipes HTTP/1.1
Host: username.cloudant.com
Accept: */*

Example of a returned header when the client accepts all formats.

The returned content type is text/plain even though the information returned by the request is in JSON format.

Server: CouchDB/1.0.2 (Erlang OTP/R14B)
Date: Thu, 13 Jan 2011 13:39:34 GMT
Content-Type: text/plain;charset=utf-8
Content-Length: #7
Cache-Control: must-revalidate

Example request that explicitly specifies the Accept header.

GET /recipes HTTP/1.1
Host: username.cloudant.com
Accept: application/json

Example of the headers returned in response, including the application/json content type.

Server: CouchDB/1.0.2 (Erlang OTP/R14B)
Date: Thu, 13 Jan 2011 13:40:11 GMT
Content-Type: application/json
Content-Length: #7
Cache-Control: must-revalidate

Accept-Encoding

The Accept-Encoding header specifies the server encoding of the response body the client accepts. The supported values are:

  • gzip
  • identity

Content-Encoding

The Content-Encoding header specifies the encoding of the request body. The supported value is gzip. If the header is used, the request body must be encoded with the corresponding format.

IBM Cloudant SDKs set this header and compress request bodies automatically.

You can also send compressed request bodies using gzip and curl.

Example creating a gzipped document.

echo '{"foo":"bar"}' | gzip > doc.gzip

Example using the gzipped document in a curl request.

curl "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/db/doc" \
	-X PUT \
	-T doc.gzip \
	-H "Content-Encoding: gzip"

Content-Type

The Content-Type header specifies the content type of the HTTP request body. The specification uses MIME type specifications. For most requests, the content type is JSON (application/json).

For some settings, the MIME type is plain text.

In particular, when you upload attachments the type must be the corresponding MIME type for the attachment or binary (application/octet-stream).

The use of the Content-Type on a request is highly recommended.

If-None-Match

The If-None-Match header is optional. You might send it to determine whether a document changed since it was last read or updated. The value of the If-None-Match header must match the last Etag value received. If the value matches the current revision of the document, the server sends a 304 Not Modified status code, and the response itself has no body.

If the document changed, you get a normal 200 response, provided the document still exists and no other errors occurred.

Range

The Range header specifies the parts of an attachment that the server should return. Several parts can be requested at the same time in one Range header, and the server may send back these ranges in a multipart document. If the server sends back ranges, it uses the status line 206 Partial Content for the response.

X-Request-ID

Assign a UUIDv4 (random) to a request for tracing. If the supplied X-Request-ID header value is a valid UUIDv4 it is also returned in the response X-Request-ID header. If the X-Request-ID is not set on a request or the supplied value is not a valid UUIDv4 then the server generates a valid value and returns it in the response X-Couch-Request-ID header.

Response headers

The server returns response headers when you receive content. They include a number of different fields. Many of the fields are standard HTTP response headers and have no significance regarding how IBM Cloudant operates. The supported HTTP response headers that are important to IBM Cloudant are:

  • Cache-Control
  • Content-Encoding
  • Content-Length
  • Content-Range
  • Content-Type
  • Etag
  • Via
  • X-Cloudant-Action
  • X-Cloudant-Backend
  • X-Cloudant-Request-Class
  • X-Content-Type-Options
  • X-Couch-Request-ID
  • X-Frame-Options
  • X-Request-ID

You can access response headers returned by IBM Cloudant operations to retrieve metadata such as request IDs for tracing and debugging.

The examples show how to retrieve the X-Couch-Request-ID header from a response.

To view response headers in a curl request, use the -i or --include option.

Access the Headers field of the DetailedResponse returned by operations.

Access the Headers object from the Response returned by operations.

Access the headers field of the response object returned by operations.

Access headers using the get_headers() method of the DetailedResponse returned by operations.

Cache-Control

The Cache-Control HTTP response header provides a suggestion for the client cache mechanisms on how to treat the returned information. IBM Cloudant typically returns the must-revalidate value, which indicates that the information must be revalidated if possible. Revalidation ensures that the dynamic nature of the content is correctly updated.

Content-Encoding

Indicates the encoding of the response body as negotiated by the Accept-Encoding request header.

Content-Length

The Content-Length header reports the length in bytes of the returned content.

Content-Range

The Content-Range header specifies where in the full document's attachment a partial content belongs. The value is in the form of bytes <range>/<total content length>. The Range request header is required to specify the partial content to be returned.

Content-Type

The Content-Type header specifies the MIME type of the returned data. For most request, the returned MIME type is text/plain. All text is encoded in Unicode (UTF-8), which is explicitly stated in the returned Content-Type as text/plain;charset=utf-8.

Etag

The Etag header is used to show the revision for a document, or the response from a show function. For documents, the value is identical to the revision of the document. The value can be used with an If-None-Match request header to get a 304 Not Modified response if the revision is still current.

ETags cannot currently be used with views or lists, since the ETags returned from those requests are random numbers that change on every request.

Via

A name of an individual reverse proxy server that processed the request.

X-Cloudant-Action

An auditing event's action name generated for the request.

X-Cloudant-Backend

A name of an individual backend server that processed the request.

X-Cloudant-Request-Class

A request class assigned to the request that count toward the instance's throughput capacity's budget.

X-Content-Type-Options

The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should be followed and not be changed. This is a security feature to block content sniffing that could transform non-executable MIME types into executable MIME types. By default Cloudant returns X-Content-Type-Options: nosniff that blocks a request if the request destination is of type style and the MIME type is not text/css, or of type script and the MIME type is not a JavaScript MIME type.

X-Couch-Request-ID

A unique identifier generated by the server if the request did not have a valid X-Request-ID header.

X-Frame-Options

The X-Frame-Options is a response header that controls whether an HTTP response can be embedded in a <frame>, <iframe> or <object>. This is a security feature to help against clickjacking. Cloudant returns X-Frame-Options: DENY by default.

X-Request-ID

This header contains a UUIDv4 value matching the one supplied on the request. If a value was not supplied then the server assigns a UUIDv4 in the X-Couch-Request-ID response header.

Example showing response headers

curl -i -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products/1000042

The response includes headers such as X-Couch-Request-ID:

HTTP/1.1 200 OK
X-Couch-Request-ID: 00000000-0000-0000-0000-000000000000
Content-Type: application/json
...

Example retrieving response headers

getDocumentOptions := service.NewGetDocumentOptions(
    "products",
    "1000042",
)

document, response, err := service.GetDocument(getDocumentOptions)
if err != nil {
    panic(err)
}

// Access response headers
responseHeaders := response.GetHeaders()
couchRequestID := responseHeaders.Get("X-Couch-Request-ID")
fmt.Printf("X-Couch-Request-ID: %s\n", couchRequestID)

Example retrieving response headers

GetDocumentOptions getDocumentOptions = new GetDocumentOptions.Builder()
    .db("products")
    .docId("1000042")
    .build();

Response<Document> response = service.getDocument(getDocumentOptions).execute();

// Access response headers
Headers responseHeaders = response.getHeaders();
String couchRequestId = responseHeaders.values("X-Couch-Request-ID").get(0);
System.out.println("X-Couch-Request-ID: " + couchRequestId);

Example retrieving response headers

service.getDocument({
  db: 'products',
  docId: '1000042'
}).then(response => {
  // Access response headers
  const couchRequestId = response.headers['x-couch-request-id'];
  console.log('X-Couch-Request-ID: ' + couchRequestId);
});

Example retrieving response headers

response = service.get_document(
    db='products',
    doc_id='1000042'
)

# Access response headers
response_headers = response.get_headers()
couch_request_id = response_headers.get('X-Couch-Request-ID')
print(f'X-Couch-Request-ID: {couch_request_id}')

Pagination

Pagination is a best-practice to break apart large queries into multiple server requests. For performance reasons, if you are displaying large amounts of data, you must consider using pagination. It is essential when dealing with large result sets or API endpoints that impose a limit on results returned. Advantages of using pagination include:

  • Keeps requests within server imposed limits, for example
    • 200 max results for text search
    • 2000 max results for partitioned queries
  • Fetches only the necessary data, for example
    • User finds required result on first page, no need to continue fetching results
  • Reduces the duration of any individual query
    • Reduces the risk of a query running for longer than the server timeout limit
    • Reduces the risk of network request timeouts

Different request types in IBM Cloudant use different pagination approaches. In all cases use the limit parameter to control number of results returned, which is the page size. The chosen page size for an application depends on service limits, document size, latency demands, memory consumption, and other tradeoffs.

The IBM Cloudant SDKs provide built-in pagination to correctly paginate different request types.

Do not use the skip parameter or offset value to paginate. It is not recommended for two reasons. Firstly, entries added or removed from the index between requests can result in missed or duplicated results. Secondly, performance will degrade with increasing skip values. Use the pagination recipes outlined in this section or the built-in pagination of the SDKs instead.

Index key pagination

The primary (document ID) index and IBM Cloudant Views use the index key from the last entry of the previous page to identify the start position of the next page of the query.

For details of how to paginate these request types visit the sections:

Bookmark pagination

Imagine you're creating a web application that shows a set of search results, whether they be books, actors, or products in your store. As the user scrolls through the search results, another page of matches is appended at the end. This behavior is known as an "infinite scroll" design pattern. It allows the user to endlessly scroll through a large data set with ease, while they fetch only smaller batches of data from the database each time.

It's this sort of access pattern that IBM Cloudant bookmarks are built for. Here's how it works:

  • Your application runs a search on an IBM Cloudant database, for example, find me the first 10 cities where the country is "US".
  • IBM Cloudant provides an array of 10 documents and a bookmark, an opaque key that represents a pointer to the next documents in the result set.
  • When the next set of results is required, the search is repeated. However, the query is sent, with the bookmark from the first response, to IBM Cloudant in the request.
  • IBM Cloudant replies with the second set of documents and another bookmark, which can be used to get a third page of results.
  • Repeat!

IBM Cloudant Query and IBM Cloudant Search provide a bookmark in the response. When passed to the next request the bookmark identifies the next page of results.

For details of how to paginate these request types visit the sections:

The IBM Cloudant database changes feed is similar, but uses a sequence identifier instead of a bookmark. For details of how to paginate changes visit the section:

The SDK pagination feature accepts options for a single operation and automatically creates the multiple requests to the server necessary to page through the results a fixed number at a time.

SDK pagination is a beta feature available in newer SDK releases.

For simplicity the examples shown here demonstrate only iterating the result rows. The SDK pagination feature provides multiple alternative pagination options, for full details and examples visit the SDK repository pagination documentation SDK repository pagination documentation SDK repository pagination documentation SDK repository pagination documentation

Paging on all documents

The all documents pagination recipe applies to these endpoints:

Primary indexes based on the document ID have unique keys. To paginate you need to calculate a value of start_key, which means the next ID after the last _id in the result set.

There are two options to either get or calculate the next start_key.

Option 1 - Fetch one document too many

Instead of fetching five documents limit=5, fetch 5+1 limit=6, but hide the sixth document from your users. The _id of the sixth document becomes the start_key of your request for the next page of results.

This option always works, but you end up fetching n+1 documents when only n are required.

Option 2 - The \u0000 trick

If you're determined to fetch only n documents each time, then you need to calculate a value of start_key. For example, if the last document in the first page of results is "example", what must the start_key of the next call to _all_docs be? It can't be "example", otherwise you get the same document ID again. It turns out that you can append \u0000 to the end of a key string to indicate the "next key" because it is the earliest sorting value.

The \u0000 trick does not work in a descending direction because it is the first sort.

\u0000 is a Unicode null character, which can be placed in a URL as-is or with the percent code %00.

The SDK pagination feature is the recommended method to page results on these endpoints.

  • The known limitations:
    • Cannot reverse direction during pagination.
    • No pagination for key option. There is no need to paginate as IDs are unique and this returns only a single row. This is better achieved with a single document get request.
    • No pagination for keys option.

Example of fetch one document too many

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_all_docs?limit=6"

{
  "total_rows": 11,
  "offset": 0,
  "rows": [
    { "id": "4eee973603bf77f30b1f880ed83df76a" ....},
    { "id": "4eee973603bf77f30b1f880ed83f469a" ....},
    { "id": "65fa623a384648740ec1f39b495d591c" ....},
    { "id": "d7404903579d6d5880514c22ad983529" ....},
    { "id": "example" ....},
    { "id": "mydoc" ....} // <-- This is the 6th result we use as the start_key of the next request
   ]
}

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_all_docs?limit=6&start_key=\"mydoc\""

{
  "total_rows": 11,
  "offset": 5,
  "rows": [
    { "id": "mydoc" ....},
    { "id": "order00057" ....},
    ...
   ]
}

Example of the \u0000 trick

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_all_docs?limit=5"

{
  "total_rows": 11,
  "offset": 0,
  "rows": [
    { "id": "4eee973603bf77f30b1f880ed83df76a" ....},
    { "id": "4eee973603bf77f30b1f880ed83f469a" ....},
    { "id": "65fa623a384648740ec1f39b495d591c" ....},
    { "id": "d7404903579d6d5880514c22ad983529" ....},
    { "id": "example" ....} // <-- append \u0000 to this to get the start_key of the next request
   ]
}

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_all_docs?limit=5&start_key=\"example\u0000\""

{
  "total_rows": 11,
  "offset": 5,
  "rows": [
    { "id": "mydoc" ....},
    { "id": "order00057" ....},
    ...
    { "id": "order00067" ....} <-- append \u0000 to this to get the start_key of the next request
   ]
}

Example of paging on all documents

import java.util.List;
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.DocsResultRow;
import com.ibm.cloud.cloudant.v1.model.PostAllDocsOptions;
import com.ibm.cloud.cloudant.features.pagination.Pager;
import com.ibm.cloud.cloudant.features.pagination.Pagination;
// Initialize service
Cloudant service = Cloudant.newInstance();
// Setup options
PostAllDocsOptions options = new PostAllDocsOptions.Builder()
  .db("orders") // example database name
  .limit(50) // limit option sets the page size
  .startKey("abc") // start from example doc ID abc
  .build();
// Create pagination
Pagination<PostAllDocsOptions, DocsResultRow> pagination = Pagination.newPagination(service, options);
// pagination can be reused without side-effects as a factory for iterables, streams or pagers
// options are fixed at pagination creation time
// Option: iterate rows
// Ideal for using an enhanced for loop with each row.
// The Iterable returned from rows() is reusable in that
// calling iterator() returns a new iterator each time.
// The returned iterators, however, are single use.
for (DocsResultRow row : pagination.rows()) {
  // Do something with row
}
import { CloudantV1, Pagination, PagerType } from '@ibm-cloud/cloudant';
import { Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
// Initialize service
const client = CloudantV1.newInstance();
// Setup params
const paginationParams = {
  db: 'orders', // Required: the database name.
  limit: 50, // Optional: limit parameter sets the page size. Default and max is 200.
  startKey: 'abc', // start from example doc ID abc
};
// Create pagination
// pagination can be reused without side-effects as a factory for async iterables, streams or pagers
const pagination = Pagination.newPagination(
  client, // Required: the Cloudant service client instance.
  PagerType.POST_ALL_DOCS, // Required: Pager type
  paginationParams // Required: pagination configuration params are fixed at pagination creation time
);
// Option: iterate rows with for await...of statement
(async () => {
  for await (const row of pagination.rows()) {
    // Do something with row
  }
})();
// Note: Alternatively to for await....of the iterator protocol functions and properties:
// `next()`, `done`, value`, can be also used on rows().
// As `next(`)` returns with a Promise, make sure using `await` or `.then()` on it.
from ibmcloudant import Pager, Pagination, PagerType
from ibmcloudant.cloudant_v1 import CloudantV1
# Initialize service
service = CloudantV1.new_instance()
# Setup options
opts = {
    'db': 'orders',  # example database name
    'limit': 50,  # limit option sets the page size,
    'start_key':  'abc' # start from example doc ID abc
}
# Create pagination
pagination = Pagination.new_pagination(
    service, PagerType.POST_ALL_DOCS, **opts)
# pagination can be reused without side-effects as a factory for iterables or pagers
# options are fixed at pagination creation time
# Option: iterate rows
# Ideal for using a for loop with each row.
# Each call to rows() returns a fresh iterator that can be traversed once.
for row in pagination.rows():
    # Do something with row
    pass
import (
	"github.com/IBM/cloudant-go-sdk/cloudantv1"
	"github.com/IBM/cloudant-go-sdk/features"
)
// Initialize service
service, err := cloudantv1.NewCloudantV1UsingExternalConfig(
	&cloudantv1.CloudantV1Options{},
)
if err != nil {
	panic(err)
}
// Setup options
opts := service.NewPostAllDocsOptions("orders")
opts.SetLimit(50)
opts.SetStartKey("abc")
// Create pagination
// pagination can be reused without side-effects as a factory for iterators or pagers
// options are fixed at pagination creation time
pagination := features.NewAllDocsPagination(service, opts)
// Option: iterate rows
// Ideal for using a for/range loop with each row.
// The iter.Seq2 returned from Rows() has an error as a second element.
for row, err := range pagination.Rows() {
	// Break on err != nil
	// Do something with row
}

Paging on view queries

MapReduce views are secondary indexes defined by key-value pairs produced from user-supplied JavaScript functions. This view pagination approach applies to these endpoints:

Querying MapReduce views is similar to all documents and view pagination methods also work for all documents. However, unlike the primary index, where every _id is unique, the secondary index might have entries with the same key. For example, lots of entries that include the key "fulfilled". This situation makes pagination by using only start_key/end_key tricky, so you can use other parameters to help: start_key_doc_id/end_key_doc_id.

The best way to paginate view is to fetch one result more than necessary and use that extra result to determine the next page start_key and start_key_doc_id. Instead of fetching five results with limit=5, fetch 5+1 with limit=6, but hide the sixth document from your users. The key of the sixth result becomes the start_key and the _id becomes the start_key_doc_id of your request for the next page of results.

The start_key_doc_id parameter works only if a start_key is supplied and where all index entries share a key. If they don't share a key, then pagination can be achieved with manipulation of start_key/end_key parameters only. Also, the start_key_doc_id parameter is not JSON encoded.

The SDK pagination feature is the recommended method to page results on these endpoints.

  • The known limitations:
    • Cannot reverse direction during pagination.
    • No pagination for key option. Pass the same key as a start and end key instead.
    • No pagination for keys option.
    • Views that emit multiple identical keys (with the same or different values) from the same document cannot paginate if those key rows with the same ID span a page boundary. The pagination feature detects this condition and an error occurs. It may be possible to workaround using a different page size.

Example of paging on view queries with the \u0000 trick

# get first page of fulfilled orders
curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_design/allClients/_view/getStatus?limit=3&start_key=\"fulfilled\"&end_key=\"fulfilled\""

{
  "total_rows": 10,
  "offset": 2,
  "rows": [
    {
      "id": "order00057",
      "key": "fulfilled",
      "value": 1
    },
    {
      "id": "order00058",
      "key": "fulfilled",
      "value": 1
    },
    {
      "id": "order00067", // <-- append \u0000 to the start_key_doc_id to of the next request
      "key": "fulfilled",
      "value": 1
    }
  ]
}

# get next page of fulfilled orders
curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud//orders/_design/allClients/_view/getStatus?limit=3&start_key=\"fulfilled\"&end_key=\"fulfilled\"&start_key_doc_id=order00067%00"

{
  "total_rows": 10,
  "offset": 5,
  "rows": [
    {
      "id": "order00077",
      "key": "fulfilled",
      "value": 1
    }
  ]
}

Example of paging on view queries

import java.util.List;
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.ViewResultRow;
import com.ibm.cloud.cloudant.v1.model.PostViewOptions;
import com.ibm.cloud.cloudant.features.pagination.Pager;
import com.ibm.cloud.cloudant.features.pagination.Pagination;
// Initialize service
Cloudant service = Cloudant.newInstance();
// Setup options
PostViewOptions options = new PostViewOptions.Builder()
  .db("shoppers") // example database name
  .limit(50) // limit option sets the page size
  .ddoc("allUsers") // use the allUsers design document
  .view("getVerifiedEmails") // the view to use
  .build();
// Create pagination
Pagination<PostViewOptions, ViewResultRow> pagination = Pagination.newPagination(service, options);
// pagination can be reused without side-effects as a factory for iterables, streams or pagers
// options are fixed at pagination creation time
// Option: iterate rows
// Ideal for using an enhanced for loop with each row.
// The Iterable returned from rows() is reusable in that
// calling iterator() returns a new iterator each time.
// The returned iterators, however, are single use.
for (ViewResultRow row : pagination.rows()) {
  // Do something with row
}
import { CloudantV1, Pagination, PagerType } from '@ibm-cloud/cloudant';
import { Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
// Initialize service
const client = CloudantV1.newInstance();
// Setup params
const paginationParams = {
  db: 'shoppers', // Required: the database name.
  limit: 50, // Optional: limit parameter sets the page size. Default and max is 200.
  ddoc: 'allUsers', // use the allUsers design document
  view: 'getVerifiedEmails', // the view to use
};
// Create pagination
// pagination can be reused without side-effects as a factory for async iterables, streams or pagers
const pagination = Pagination.newPagination(
  client, // Required: the Cloudant service client instance.
  PagerType.POST_VIEW, // Required: Pager type
  paginationParams // Required: pagination configuration params are fixed at pagination creation time
);
// Option: iterate rows with for await...of statement
(async () => {
  for await (const row of pagination.rows()) {
    // Do something with row
  }
})();
// Note: Alternatively to for await....of the iterator protocol functions and properties:
// `next()`, `done`, value`, can be also used on rows().
// As `next(`)` returns with a Promise, make sure using `await` or `.then()` on it.
from ibmcloudant import Pager, Pagination, PagerType
from ibmcloudant.cloudant_v1 import CloudantV1
# Initialize service
service = CloudantV1.new_instance()
# Setup options
opts = {
    'db': 'shoppers',  # example database name
    'limit': 50,  # limit option sets the page size
    'ddoc': 'allUsers',  # use the allUsers design document
    'view': 'getVerifiedEmails' # the view to use
}
# Create pagination
pagination = Pagination.new_pagination(
    service, PagerType.POST_VIEW, **opts)
# pagination can be reused without side-effects as a factory for iterables or pagers
# options are fixed at pagination creation time
# Option: iterate rows
# Ideal for using a for loop with each row.
# Each call to rows() returns a fresh iterator that can be traversed once.
for row in pagination.rows():
    # Do something with row
    pass
import (
	"github.com/IBM/cloudant-go-sdk/cloudantv1"
	"github.com/IBM/cloudant-go-sdk/features"
)
// Initialize service
service, err := cloudantv1.NewCloudantV1UsingExternalConfig(
	&cloudantv1.CloudantV1Options{},
)
if err != nil {
	panic(err)
}
// Setup options
opts := service.NewPostViewOptions("shoppers", "allUsers", "getVerifiedEmails")
opts.SetLimit(50)
// Create pagination
// pagination can be reused without side-effects as a factory for iterators or pagers
// options are fixed at pagination creation time
pagination := features.NewViewPagination(service, opts)
// Option: iterate rows
// Ideal for using a for/range loop with each row.
// The iter.Seq2 returned from Rows() has an error as a second element.
for row, err := range pagination.Rows() {
	// Break on err != nil
	// Do something with row
}

Paging on selector syntax queries

The following endpoints' responses contain a bookmark - a token that IBM Cloudant uses to determine where to resume from when later queries are made. To get the next set of query results, add the bookmark that was received in the previous response to your next request.

To get the next set of query results for IBM Cloudant Query, add the bookmark that was received in the previous response to your next request. Remember to keep the selector and sort the same, otherwise you receive unexpected results.

The presence of a bookmark doesn’t guarantee more results. You can test whether you are at the end of the result set by comparing the number of results that are returned with the page size requested. If the results returned are less than limit, no more results are available in the result set.

When supplied an incorrect bookmark IBM Cloudant responds with an HTTP 400 Bad Request { error: 'invalid_bookmark'} response.

The SDK pagination feature is the recommended method to page results on these endpoints.

  • The known limitations:
    • Cannot reverse direction during pagination.

Example of paging on selector syntax queries

curl -X POST      -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"      -H 'Content-type: application/json'      -d '{"selector":{"country":{"$eq": "US"}},"limit":5}'      "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/cities/_find"

{
  "docs":[
    {"_id":"10104153","_rev":"1-32aab6258c65c5fc5af044a153f4b994","name":"Silver Lake","latitude":34.08668,"longitude":-118.27023,"country":"US","population":32890,"timezone":"America/Los_Angeles"},
    {"_id":"10104154","_rev":"1-125f589bf4e39d8e119b4b7b5b18caf6","name":"Echo Park","latitude":34.07808,"longitude":-118.26066,"country":"US","population":43832,"timezone":"America/Los_Angeles"},
    {"_id":"4046704","_rev":"1-2e4b7820872f108c077dab73614067da","name":"Fort Hunt","latitude":38.73289,"longitude":-77.05803,"country":"US","population":16045,"timezone":"America/New_York"},
    {"_id":"4048023","_rev":"1-744baaba02218fd84b350e8982c0b783","name":"Bessemer","latitude":33.40178,"longitude":-86.95444,"country":"US","population":27456,"timezone":"America/Chicago"},
    {"_id":"4048662","_rev":"1-e95c97013ece566b37583e451c1864ee","name":"Paducah","latitude":37.08339,"longitude":-88.60005,"country":"US","population":25024,"timezone":"America/Chicago"}
  ],
  "bookmark": "g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxiYWJiZGYGkOWDSyBJZAPCBD58"
}

curl -X POST      -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"      -H 'Content-type: application/json'      -d '{"selector":{"country":{"$eq": "US"}},"limit":5,"bookmark":"g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxiYWJiZGYGkOWDSyBJZAPCBD58"}'      "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/cities/_find"

{
  "docs":[
    {"_id":"4049979","_rev":"1-1fa2591477c774a07c230571568aeb66","name":"Birmingham","latitude":33.52066,"longitude":-86.80249,"country":"US","population":212237,"timezone":"America/Chicago"},
    {"_id":"4054378","_rev":"1-a750085697685e7bc0e49d103d2de59d","name":"Center Point","latitude":33.64566,"longitude":-86.6836,"country":"US","population":16921,"timezone":"America/Chicago"},
    {"_id":"4058219","_rev":"1-9b4eb183c9cdf57c19be660ec600330c","name":"Daphne","latitude":30.60353,"longitude":-87.9036,"country":"US","population":21570,"timezone":"America/Chicago"},
    {"_id":"4058553","_rev":"1-56100f7e7742028facfcc50ab6b07a04","name":"Decatur","latitude":34.60593,"longitude":-86.98334,"country":"US","population":55683,"timezone":"America/Chicago"},
    {"_id":"4059102","_rev":"1-612ae37d982dc71eeecf332c1e1c16aa","name":"Dothan","latitude":31.22323,"longitude":-85.39049,"country":"US","population":65496,"timezone":"America/Chicago"}
  ],
  "bookmark": "g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxiYWhoaGIGkOWDSyBJZAO9qD40"
}

Example of paging on selector syntax queries

import java.util.Collections;
import java.util.List;
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.Document;
import com.ibm.cloud.cloudant.v1.model.PostFindOptions;
import com.ibm.cloud.cloudant.features.pagination.Pager;
import com.ibm.cloud.cloudant.features.pagination.Pagination;
// Initialize service
Cloudant service = Cloudant.newInstance();
// Setup options
PostFindOptions options = new PostFindOptions.Builder()
  .db("shoppers") // Database name
  .limit(50) // limit option sets the page size
  .fields(List.of("_id", "type", "name", "email")) // return these fields
  .selector(Collections.singletonMap("email_verified", "true")) // select docs with verified emails
  .sort(Collections.singletonList(Collections.singletonMap("email", "desc"))) // sort descending by email
  .build();
// Create pagination
Pagination<PostFindOptions, Document> pagination = Pagination.newPagination(service, options);
// pagination can be reused without side-effects as a factory for iterables, streams or pagers
// options are fixed at pagination creation time
// Option: iterate rows
// Ideal for using an enhanced for loop with each row.
// The Iterable returned from rows() is reusable in that
// calling iterator() returns a new iterator each time.
// The returned iterators, however, are single use.
for (Document row : pagination.rows()) {
  // Do something with row
}
import { CloudantV1, Pagination, PagerType } from '@ibm-cloud/cloudant';
import { Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
// Initialize service
const client = CloudantV1.newInstance();
// Setup params
const paginationParams = {
  db: 'shoppers', // Required: the database name.
  limit: 50, // Optional: limit parameter sets the page size. Default and max is 200.
  fields: ['_id', 'type', 'name', 'email'], // return these fields
  selector: { email_verified: { '$eq': true } }, // select docs with verified emails
  sort: [{ email: 'desc' }],
};
// Create pagination
// pagination can be reused without side-effects as a factory for async iterables, streams or pagers
const pagination = Pagination.newPagination(
  client, // Required: the Cloudant service client instance.
  PagerType.POST_FIND, // Required: Pager type
  paginationParams // Required: pagination configuration params are fixed at pagination creation time
);
// Option: iterate rows with for await...of statement
(async () => {
  for await (const row of pagination.rows()) {
    // Do something with row
  }
})();
// Note: Alternatively to for await....of the iterator protocol functions and properties:
// `next()`, `done`, value`, can be also used on rows().
// As `next(`)` returns with a Promise, make sure using `await` or `.then()` on it.
from ibmcloudant import Pager, Pagination, PagerType
from ibmcloudant.cloudant_v1 import CloudantV1
# Initialize service
service = CloudantV1.new_instance()
# Setup options
opts = {
    'db': 'shoppers',  # example database name
    'limit': 50,  # limit option sets the page size
    'fields': ['_id', 'type', 'name', 'email'],  # return these fields
    'selector': {'email_verified': True},  # select docs with verified emails
    'sort': [{'email': 'desc'}]  # sort descending by email
}
# Create pagination
pagination = Pagination.new_pagination(
    service, PagerType.POST_FIND, **opts)
# pagination can be reused without side-effects as a factory for iterables or pagers
# options are fixed at pagination creation time
# Option: iterate rows
# Ideal for using a for loop with each row.
# Each call to rows() returns a fresh iterator that can be traversed once.
for row in pagination.rows():
    # Do something with row
    pass
import (
	"github.com/IBM/cloudant-go-sdk/cloudantv1"
	"github.com/IBM/cloudant-go-sdk/features"
)
// Initialize service
service, err := cloudantv1.NewCloudantV1UsingExternalConfig(
	&cloudantv1.CloudantV1Options{},
)
if err != nil {
	panic(err)
}
// Setup options
opts := service.NewPostFindOptions("shoppers", map[string]any{"email_verified": true})
opts.SetLimit(50)
opts.SetFields([]string["_id", "type", "name", "email"])
opts.SetSort([]map[string]string{map[string]string{"email": "desc"}})
// Create pagination
// pagination can be reused without side-effects as a factory for iterators or pagers
// options are fixed at pagination creation time
pagination := features.NewFindPagination(service, opts)
// Option: iterate rows
// Ideal for using a for/range loop with each row.
// The iter.Seq2 returned from Rows() has an error as a second element.
for row, err := range pagination.Rows() {
	// Break on err != nil
	// Do something with row
}

Paging on search index queries

IBM Cloudant Search queries use bookmarks for pagination. Pass the bookmark parameter in the URL for GET requests or in the JSON body for POST requests. You must keep the same query (the same "q" in IBM Cloudant Search) to get the next page of results. If you change the query, you might get an empty result set in reply.

See the documentation about query parameters for further details.

The SDK pagination feature is the recommended method to page results on these endpoints.

  • The known limitations:
    • Cannot reverse direction during pagination.
    • No pagination of grouped results.
    • No pagination of faceted counts or ranges results.

Example of paging on search index queries

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/cities/_search/search/_search/freetext?q=country:US&limit=5"

{
  "total_rows": 65,
  "rows":[
    {"_id":"10104153","_rev":"1-32aab6258c65c5fc5af044a153f4b994","name":"Silver Lake","latitude":34.08668,"longitude":-118.27023,"country":"US","population":32890,"timezone":"America/Los_Angeles"},
    {"_id":"10104154","_rev":"1-125f589bf4e39d8e119b4b7b5b18caf6","name":"Echo Park","latitude":34.07808,"longitude":-118.26066,"country":"US","population":43832,"timezone":"America/Los_Angeles"},
    {"_id":"4046704","_rev":"1-2e4b7820872f108c077dab73614067da","name":"Fort Hunt","latitude":38.73289,"longitude":-77.05803,"country":"US","population":16045,"timezone":"America/New_York"},
    {"_id":"4048023","_rev":"1-744baaba02218fd84b350e8982c0b783","name":"Bessemer","latitude":33.40178,"longitude":-86.95444,"country":"US","population":27456,"timezone":"America/Chicago"},
    {"_id":"4048662","_rev":"1-e95c97013ece566b37583e451c1864ee","name":"Paducah","latitude":37.08339,"longitude":-88.60005,"country":"US","population":25024,"timezone":"America/Chicago"}
  ],
  "bookmark": "g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxiYWJiZGYGkOWDSyBJZAPCBD58"
}

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/cities/_search/search/_search/freetext?q=country:US&limit=5&bookmark=g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxiYWJiZGYGkOWDSyBJZAPCBD58"

{
  "total_rows": 65,
  "rows":[
    {"_id":"4049979","_rev":"1-1fa2591477c774a07c230571568aeb66","name":"Birmingham","latitude":33.52066,"longitude":-86.80249,"country":"US","population":212237,"timezone":"America/Chicago"},
    {"_id":"4054378","_rev":"1-a750085697685e7bc0e49d103d2de59d","name":"Center Point","latitude":33.64566,"longitude":-86.6836,"country":"US","population":16921,"timezone":"America/Chicago"},
    {"_id":"4058219","_rev":"1-9b4eb183c9cdf57c19be660ec600330c","name":"Daphne","latitude":30.60353,"longitude":-87.9036,"country":"US","population":21570,"timezone":"America/Chicago"},
    {"_id":"4058553","_rev":"1-56100f7e7742028facfcc50ab6b07a04","name":"Decatur","latitude":34.60593,"longitude":-86.98334,"country":"US","population":55683,"timezone":"America/Chicago"},
    {"_id":"4059102","_rev":"1-612ae37d982dc71eeecf332c1e1c16aa","name":"Dothan","latitude":31.22323,"longitude":-85.39049,"country":"US","population":65496,"timezone":"America/Chicago"}
  ],
  "bookmark": "g1AAAAA-eJzLYWBgYMpgSmHgKy5JLCrJTq2MT8lPzkzJBYqzmxiYWhoaGIGkOWDSyBJZAO9qD40",
}

Example of paging on search index queries

import java.util.List;
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.SearchResultRow;
import com.ibm.cloud.cloudant.v1.model.PostSearchOptions;
import com.ibm.cloud.cloudant.features.pagination.Pager;
import com.ibm.cloud.cloudant.features.pagination.Pagination;
// Initialize service
Cloudant service = Cloudant.newInstance();
// Setup options
PostSearchOptions options = new PostSearchOptions.Builder()
  .db("shoppers") // example database name
  .limit(50) // limit option sets the page size
  .ddoc("allUsers") // use the allUsers design document
  .index("activeUsers") // search in this index
  .query("name:Jane* AND active:True") // Lucene search query
  .build();
// Create pagination
Pagination<PostSearchOptions, SearchResultRow> pagination = Pagination.newPagination(service, options);
// pagination can be reused without side-effects as a factory for iterables, streams or pagers
// options are fixed at pagination creation time
// Option: iterate rows
// Ideal for using an enhanced for loop with each row.
// The Iterable returned from rows() is reusable in that
// calling iterator() returns a new iterator each time.
// The returned iterators, however, are single use.
for (SearchResultRow row : pagination.rows()) {
  // Do something with row
}
import { CloudantV1, Pagination, PagerType } from '@ibm-cloud/cloudant';
import { Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
// Initialize service
const client = CloudantV1.newInstance();
// Setup params
const paginationParams = {
  db: 'shoppers', // Required: the database name.
  limit: 50, // Optional: limit parameter sets the page size. Default and max is 200.
  ddoc: 'allUsers', // use the allUsers design document
  index: 'activeUsers', // search in this index
  query: 'name:Jane* AND active:True', // Lucene search query
};
// Create pagination
// pagination can be reused without side-effects as a factory for async iterables, streams or pagers
const pagination = Pagination.newPagination(
  client, // Required: the Cloudant service client instance.
  PagerType.POST_SEARCH, // Required: Pager type
  paginationParams // Required: pagination configuration params are fixed at pagination creation time
);
// Option: iterate rows with for await...of statement
(async () => {
  for await (const row of pagination.rows()) {
    // Do something with row
  }
})();
// Note: Alternatively to for await....of the iterator protocol functions and properties:
// `next()`, `done`, value`, can be also used on rows().
// As `next(`)` returns with a Promise, make sure using `await` or `.then()` on it.
from ibmcloudant import Pager, Pagination, PagerType
from ibmcloudant.cloudant_v1 import CloudantV1
# Initialize service
service = CloudantV1.new_instance()
# Setup options
opts = {
    'db': 'shoppers',  # example database name
    'limit': 50,  # limit option sets the page size
    'ddoc': 'allUsers',  # use the allUsers design document
    'index': 'activeUsers',  # search in this index
    'query': 'name:Jane* AND active:True'  # Lucene search query
}
# Create pagination
pagination = Pagination.new_pagination(
    service, PagerType.POST_SEARCH, **opts)
# pagination can be reused without side-effects as a factory for iterables or pagers
# options are fixed at pagination creation time
# Option: iterate rows
# Ideal for using a for loop with each row.
# Each call to rows() returns a fresh iterator that can be traversed once.
for row in pagination.rows():
    # Do something with row
    pass
import (
	"github.com/IBM/cloudant-go-sdk/cloudantv1"
	"github.com/IBM/cloudant-go-sdk/features"
)
// Initialize service
service, err := cloudantv1.NewCloudantV1UsingExternalConfig(
	&cloudantv1.CloudantV1Options{},
)
if err != nil {
	panic(err)
}
// Setup options
opts := service.NewPostSearchOptions("shoppers", "allUsers", "activeUsers", "name:Jane* AND active:True")
opts.SetLimit(50)
// Create pagination
// pagination can be reused without side-effects as a factory for iterators or pagers
// options are fixed at pagination creation time
pagination := features.NewSearchPagination(service, opts)
// Option: iterate rows
// Ideal for using a for/range loop with each row.
// The iter.Seq2 returned from Rows() has an error as a second element.
for row, err := range pagination.Rows() {
	// Break on err != nil
	// Do something with row
}

Paging the changes feed

Sending a request to /_changes endpoint returns a list of changes that were made to documents in the database, including insertions, updates, and deletions. The _changes endpoint has a limit parameter to control how many changes you would like to receive. The since parameter gets a list of changes that occurred after a specified sequence identifier.

The changes feed supplies result rows at least once and callers must expect potential duplicates.

Use limit and since to paginate the changes feed. To get the since parameter for the next page use the last_seq from the previous page of results.

If the since identifier is 0 (the default), or omitted, the request returns all changes. If the since identifier is now, the request asks for changes that are made after the current time.

The SDK provides a changes feed follower utility. This helper utility connects to the _changes endpoint and returns the individual change items. It removes some complexity of using the _changes endpoint by setting some options automatically and providing error suppression and retries.

The page size is not configurable in the SDK changes followers. It is set to an appropriate value for reasonable response sizes.

The limit parameter controls the total number of changes received by the SDK changes follower using multiple pages if necessary.

Example of paging on the changes feed

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_changes?limit=5" -H "Content-Type: application/json"

{
    "results": [
        {"seq": "1-g1AAAA...", "id": "4eee973603bf77f30b1f880ed83df76a", "changes": [{"rev": "1-9d0c2..."}]},
        {"seq": "2-g1AAAA...", "id": "4eee973603bf77f30b1f880ed83f469a", "changes": [{"rev": "1-b1f67..."}]},
        ...
    ],
    "last_seq": "6-g1AAAA...",  // <-- This is the sequence we use as the since parameter of the next request
    "pending": 2998
}

curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_changes?limit=5&since=6-g1AAAA..." -H "Content-Type: application/json"

{
    "results": [
        {"seq": "6-g1AAAA...", "id": "65fa623a384648740ec1f39b495d591c", "changes": [{"rev": "1-00203..."}]},
        {"seq": "7-g1AAAA...", "id": "d7404903579d6d5880514c22ad983529", "changes": [{"rev": "1-9410b..."}]},
        ...
    ],
    "last_seq": "10-g1AAAA...",
    "pending": 2993
}

Example of paging with changes follower

import java.util.stream.Stream;
import com.ibm.cloud.cloudant.features.ChangesFollower;
import com.ibm.cloud.cloudant.v1.Cloudant;
import com.ibm.cloud.cloudant.v1.model.Change;
import com.ibm.cloud.cloudant.v1.model.ChangesResultItem;
import com.ibm.cloud.cloudant.v1.model.PostChangesOptions;

public class StartOneOffAndProcess {
    public static void main(String[] args) {

        Cloudant client = Cloudant.newInstance();

        // Start from a perviously persisted seq
        // Normally this would be read by the app from persistent storage
        // e.g. String previouslyPersistedSeq = yourAppPersistenceReadFunction();
        String previouslyPersistedSeq = "3-g1AG3...";
        PostChangesOptions options = new PostChangesOptions.Builder("example")
            .since(previouslyPersistedSeq)
            .build();
        ChangesFollower changesFollower = new ChangesFollower(client, options);
        Stream<ChangesResultItem> changesItems = changesFollower.startOneOff();
        changesItems.forEach(changesItem -> {
            // do something with changes
            System.out.println(changesItem.getId());
            for (Change change : changesItem.getChanges()) {
                System.out.println(change.getRev());
            }
            // when change item processing is complete app can store seq
            String seq = changesItem.getSeq();
            // write seq to persistent storage for use as since if required to resume later
            // e.g. call yourAppPersistenceWriteFunction(seq);
        });
        // Note: java.util.Stream terminal operations are blocking, code here will be unreachable
        // until all changes are processed (or another stop condition is reached).
    }
}
const client = CloudantV1.newInstance();
// Start from a previously persisted seq
// Normally this would be read by the app from persistent storage
// e.g. previouslyPersistedSeq = yourAppPersistenceReadFunc()
const previouslyPersistedSeq = '3-g1AG3...';
const changesParams = {
  db: 'example',
  since: previouslyPersistedSeq
};
const changesFollower = new ChangesFollower(client, changesParams);
const changesItemsStream = changesFollower.startOneOff();

const destinationStream = new Writable({
  objectMode: true,
  write(changesItem, _, callback) {
    // do something with change item
    console.log(changesItem.id);
    for (const change of changesItem.changes) {
      console.log(change.rev);
    }
    // when change item processing is complete app can store seq
    const seq = changesItem.seq;
    // write seq to persistent storage for use as since if required to resume later
    // e.g. yourAppPersistenceWriteFunc()
    callback();
  }
});

pipeline(changesItemsStream, destinationStream)
  .then(() => {
    console.log('All changes done');
  })
  .catch((err) => {
    console.log(err);
  });

// use for-async-loop feature for stream
/*
getChangesFromFollower(changesItemsStream);
async function getChangesFromFollower(changesItemsStream) {
  for await (const changesItem of changesItemsStream) {
    // do something with change item
    // write seq to persistent storage for use as since
    console.log(changesItem.id);
    for (const change of changesItem.changes) {
      console.log(change.rev);
    }
    // when change item processing is complete app can store seq
    seq = changesItem.seq;
    // write seq to persistent storage for use as since if required to resume later
    // e.g. yourAppPersistenceWriteFunc();
  }
}
*/
import ChangesFollower
from ibmcloudant.cloudant_v1 import CloudantV1

client = CloudantV1.new_instance()

# Start from a previously persisted seq
# Normally this would be read by the app from persistent storage
# e.g. previously_persisted_seq = your_app_persistence_read_func()
previously_persisted_seq = '3-g1AG3...'
changes_follower = ChangesFollower(
    service=client,
    **{'db': 'example', 'since': previously_persisted_seq})

changes_items = changes_follower.start_one_off()
for changes_item in changes_items:
    # do something with changes
    print(changes_item.id)
    for change in changes_item.changes:
        print(change.rev)
    # when change item processing is complete app can store seq
    seq = changes_item.seq
    # write seq to persistent storage for use as since if required to resume later
    # e.g. your_app_persistence_write_func(seq)

# Note: iterator above is blocking, code here will be unreachable
# until all changes are processed (or another stop condition is reached).
package main

import (
	"fmt"

	"github.com/IBM/cloudant-go-sdk/cloudantv1"
	"github.com/IBM/cloudant-go-sdk/features"
)

func main() {
	client, err := cloudantv1.NewCloudantV1UsingExternalConfig(
		&cloudantv1.CloudantV1Options{},
	)
	if err != nil {
		panic(err)
	}

	postChangesOptions := client.NewPostChangesOptions("example")

	// Start from a previously persisted seq
	// Normally this would be read by the app from persistent storage
	// e.g. prevSeq = yourAppPersistenceReadFunc()
	prevSeq := "3-g1AG3..."
	postChangesOptions.SetSince(prevSeq)

	follower, err := features.NewChangesFollower(client, postChangesOptions)
	if err != nil {
		panic(err)
	}

	changesCh, err := follower.StartOneOff()
	if err != nil {
		panic(err)
	}

	for changesItem := range changesCh {
		// changes item structure returns an error on failed requests
		item, err := changesItem.Item()
		if err != nil {
			panic(err)
		}

		// do something with changes
		fmt.Printf("%s\n", *item.ID)
		for _, change := range item.Changes {
			fmt.Printf("%s\n", *change.Rev)
		}

		// when change item processing is complete app can store seq
		seq := *item.Seq
		// write seq to persistent storage for use as since if required
		// to resume later, e.g. yourAppPersistenceWriteFunc(seq)
	}

	// Note: iterating the returned channel above is blocking, code here
	// will be unreachable until all changes are processed
	// or another stop condition is reached.
}

Rate limiting

Rate limits for API requests are enforced on a per-service-instance basis. If the number of requests for a particular request class (read, write or global query) reaches the limit within the given time window, no further requests of that class are accepted until the next time window.

You can view your usage by using the Retrieve the current provisioned throughput capacity consumption API or the IBM Cloudant dashboard. IBM Cloudant does return an x-cloudant-request-class response header related to limiting.

x-cloudant-request-class response header returns the following request classes: read, write, global query, or unlimited.

If you want to learn more about these request classes, see the Request classes documentation.

A 429 HTTP status code indicates that the rate limit has been exceeded.

The number of allowed requests varies by request class. The reference information for each endpoint and method specifies the request class that applies to the request. The rate limit for each request class is determined by the account plan.

Most requests and responses to and from IBM® Cloudant® for IBM Cloud® use JavaScript Object Notation (JSON) for formatting the content and structure of the data and responses.

In IBM Cloudant databases, the JSON object is used to represent various structures, including all documents in a database.

Parsing JSON into a JavaScript object is supported through the JSON.parse() function in JavaScript, or through various libraries that perform the parsing of the content into a JavaScript object for you. Libraries for parsing and generating JSON are available for many major programming languages.

JSON is used because it's the simplest and easiest solution for working with data that uses a web browser. As a result, JSON structures can be evaluated and used as JavaScript objects within the web browser environment. JSON also integrates with the server-side JavaScript used within IBM Cloudant. JSON documents are always UTF-8 encoded.

Be careful to follow these guidelines:

  • Your JSON structures are valid.
  • You normalize strings in JSON documents retrieved from IBM Cloudant.

JSON supports the same basic types that are supported by JavaScript: numbers, strings, Booleans, arrays, and objects.

Numbers

Numbers can be integer or floating point values.

Example of a number in JSON format

123

Strings

Strings must be enclosed by double quotation marks. Strings support Unicode characters and escaping a backslash.

Example of a string in JSON format

"A String"

Booleans

A true or false value.

Example of a boolean in JSON format

{
  "value": true
}

Arrays

A list of values enclosed in brackets. The values that are enclosed can be any valid JSON.

Example of an array in JSON format

[
    "one",
    2,
    "three",
    [],
    true,
    {
        "foo":
        "bar"
    }
]

Example of an array in JSON format (linear)

[ "one", 2, "three", [], true, { "foo": "bar" } ]

Objects

A set of key-value pairs, such as an associative array, or a hash. The key must be a string, but the value can be any of the supported JSON values.

Example of a JSON object

{
    "servings" : 4,
    "subtitle" : "Easy to make in advance, and then cook when ready",
    "cooktime" : 60,
    "title" : "Chicken Coriander"
}

Logging

The SDK provides a logging facility with levels Error, Info, Warn, and Debug. By default this logger outputs messages to the standard error stream. The default logging level is Error. With Debug level enabled HTTP messages and retry attempts become visible.

The Go SDK's core library also defines a Logger interface, where you can supply your own logging implementation. For example, you can direct the log messages to a file instead of the console. To use this advanced feature, implement the Logger interface and then call the SetLogger(yourLogger) function to set your implementation to handle the log messages.

The SDK uses the java.util.logging framework for logging messages. You can configure the logging framework to create and configure loggers, handlers (for example ConsoleHandler or FileHandler) and formatters. Configuring a ConsoleHandler for the com.ibm.cloud.sdk.core package outputs SDK logging messages to the standard error stream.

Configuring the level for your logger controls the message visibility. You can use the standard java.util.logging.Level value constants: OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL.

For additional HTTP activity logging configure com.ibm.cloud.sdk.core.http.HttpConfigOptions and call configureClient(options) with it. The logging detail levels are: NONE, BASIC, HEADERS,BODY. To view these messages both set the logger and handler levels for com.ibm.cloud.sdk.core.http to FINE or below.

You can also define the configuration in a file, then supply the name of the file to the logging framework when you run your application. To use a particular configuration file when running your java application, specify the name of the configuration file with the java.util.logging.config.file system property, like this

java -jar myapp.jar -Djava.util.logging.config.file=logging.properties mypackage.MyMainClass

The SDK uses the debug package for logging. To see the log output, enable debug with string built up of ibm-cloud-sdk-core: followed by the wanted log level. The available levels are: error, warning, info, verbose, and debug. To see messages from all available levels you can use * like ibm-cloud-sdk-core*. To configure debug logger for more than one library use a comma-separated string like ibm-cloud-sdk-core:debug,cloudant-node-sdk:debug. For example to obtain maximum logging you can set the environment variable DEBUG='ibm-cloud-sdk-core*,cloudant-node-sdk*'.

The debug package logs to the standard error stream. To change output you must override the log or the stderr stream.

The Python SDK uses Python's built-in logging module to perform logging messages with levels of: CRITICAL, ERROR, WARNING, INFO and DEBUG. To enable logging, import the logging package then set the preferred log level.

With DEBUG level enabled HTTP messages and retry attempts become visible.

By default the basic configuration outputs messages to the standard error stream.

Example of logging to the standard error stream

// Enable Debug logging
core.SetLoggingLevel(core.LevelDebug)
import java.util.logging.Logger;
import java.util.logging.ConsoleHandler;
import com.ibm.cloud.sdk.core.http.HttpConfigOptions;

// Set logger on core with FINE level
Logger sdkLogger = Logger.getLogger("com.ibm.cloud.sdk.core");
sdkLogger.setLevel(Level.FINE);

// Configure the logging output to the standard error stream with FINE level
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);

// Set the HTTP logging level to BASIC
HttpConfigOptions options =
    new HttpConfigOptions.Builder()
        .loggingLevel(HttpConfigOptions.LoggingLevel.BASIC)
    .build();

service.configureClient(options);
import debug from 'debug'

// Enable debug logs on ibm-cloud-sdk-core and error logs on @ibm-cloud/cloudant packages
debug.enable('ibm-cloud-sdk-core:debug,cloudant-node-sdk:error');

// You must use dynamic imports (`await import(...)`) for monitored packages
// to ensure they load only after debug has been enabled.
const { CloudantV1 } = await import('@ibm-cloud/cloudant');
const { BasicAuthenticator } = await import('ibm-cloud-sdk-core');
import logging

# Enable DEBUG logging level which writes with a handler that display messages on the console
logging.basicConfig(level=logging.DEBUG)

Example of logging to a file

// Enable custom file logger
type FileLogger struct {
	logLevel core.LogLevel // use log levels defined in core
	logFile *os.File
}
func NewFileLogger(level core.LogLevel, filename string) *FileLogger {
	logFile, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
        log.Fatalf("Failed to open log file: %v", err)
    }
	return &FileLogger{
		logLevel: level,
		logFile: logFile,
	}
}

// Implement the Log function of FileLogger from the Logger interface
func (l *FileLogger) Log(level core.LogLevel, format string, inserts ...interface{}) {
	if l.IsLogLevelEnabled(level) {
		logger := log.New(l.logFile, "", log.LstdFlags)
		logger.Printf(format, inserts...)
	}
}

// Implement all the other functions from the Logger interface for FileLogger
// func (l *FileLogger) Error(format string, inserts ...interface{}) { ... }
// func (l *FileLogger) Warn(format string, inserts ...interface{}) { ... }
// func (l *FileLogger) Info(format string, inserts ...interface{}) { ... }
// func (l *FileLogger) Debug(format string, inserts ...interface{}) { ... }
// func (l *FileLogger) SetLogLevel(level core.LogLevel) { ... }
// func (l *FileLogger) GetLogLevel() core.LogLevel { ... }
// func (l *FileLogger) IsLogLevelEnabled(level core.LogLevel) bool { ... }

// Create a new file logger with debug level
yourLogger := NewFileLogger(core.LevelDebug, "your_log_file.log")
core.SetLogger(yourLogger)
import java.util.logging.Logger;
import java.util.logging.FileHandler;
import com.ibm.cloud.sdk.core.http.HttpConfigOptions;

// Set logger on core with FINE level
Logger sdkLogger = Logger.getLogger("com.ibm.cloud.sdk.core");
sdkLogger.setLevel(Level.FINE);

// Use FileHandler if the target of logging is a file
FileHandler handler = new FileHandler("your_log_file.log")
handler.setLevel(Level.FINE);

// Set the HTTP logging level to BODY
HttpConfigOptions options =
    new HttpConfigOptions.Builder()
        .loggingLevel(HttpConfigOptions.LoggingLevel.BODY)
    .build();

service.configureClient(options);
import fs from 'fs';
import debug from 'debug';

// Create a writable stream for the log file
const logStream = fs.createWriteStream('./your_log_file.log', { flags: 'a' });
// Namespace for all kind of logs on ibm-cloud-sdk-core package
const namespace = 'ibm-cloud-sdk-core*';

// Override global log method of the debug package
Object.getPrototypeOf(debug(namespace)).log = (...args) => {
    logStream.write(args.join(' ') + '\n');
};
// Enable namespace
debug.enable(namespace);

// You must use dynamic imports (`await import(...)`) for monitored packages
// to ensure they load only after debug has been enabled.
const { CloudantV1 } = await import('@ibm-cloud/cloudant');
const { BasicAuthenticator } = await import('ibm-cloud-sdk-core');
import logging

# Enable DEBUG logging level and use filename parameter when the target of logging is a file
logging.basicConfig(level=logging.DEBUG, filename='your_log_file.log')

Methods

Retrieve server instance information

When you access the root of an instance, IBM Cloudant returns meta-information about the instance. The response includes a JSON structure that contains information about the server, including a welcome message and the server's version.

Tip: The authentication for this endpoint is only enforced when using IAM.

When you access the root of an instance, IBM Cloudant returns meta-information about the instance. The response includes a JSON structure that contains information about the server, including a welcome message and the server's version.

Tip: The authentication for this endpoint is only enforced when using IAM.

When you access the root of an instance, IBM Cloudant returns meta-information about the instance. The response includes a JSON structure that contains information about the server, including a welcome message and the server's version.

Tip: The authentication for this endpoint is only enforced when using IAM.

When you access the root of an instance, IBM Cloudant returns meta-information about the instance. The response includes a JSON structure that contains information about the server, including a welcome message and the server's version.

Tip: The authentication for this endpoint is only enforced when using IAM.

When you access the root of an instance, IBM Cloudant returns meta-information about the instance. The response includes a JSON structure that contains information about the server, including a welcome message and the server's version.

Tip: The authentication for this endpoint is only enforced when using IAM.

GET /
(cloudant *CloudantV1) GetServerInformation(getServerInformationOptions *GetServerInformationOptions) (result *ServerInformation, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) GetServerInformationWithContext(ctx context.Context, getServerInformationOptions *GetServerInformationOptions) (result *ServerInformation, response *core.DetailedResponse, err error)
ServiceCall<ServerInformation> getServerInformation()
getServerInformation(params)
get_server_information(
        self,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.account-meta-info.read

Request

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

WithContext method only

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    getServerInformationOptions := service.NewGetServerInformationOptions()
    
    serverInformation, response, err := service.GetServerInformation(getServerInformationOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(serverInformation, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.ServerInformation;
    
    Cloudant service = Cloudant.newInstance();
    
    ServerInformation response =
        service.getServerInformation().execute().getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.getServerInformation().then(response => {
        console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.get_server_information().get_result()
    
    print(response)
    

Response

Schema for information about the server instance.

Schema for information about the server instance.

Schema for information about the server instance.

Schema for information about the server instance.

Schema for information about the server instance.

Status Code

  • HTTP response for / style operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example ServerInformation response.

    {
      "couchdb": "Welcome",
      "features": [
        "access-ready",
        "iam",
        "partitioned",
        "pluggable-storage-engines",
        "scheduler"
      ],
      "features_flags": [
        "partitioned"
      ],
      "vendor": {
        "name": "IBM Cloudant",
        "variant": "paas",
        "version": "8162"
      },
      "version": "2.1.1"
    }
  • Example ServerInformation response.

    {
      "couchdb": "Welcome",
      "features": [
        "access-ready",
        "iam",
        "partitioned",
        "pluggable-storage-engines",
        "scheduler"
      ],
      "features_flags": [
        "partitioned"
      ],
      "vendor": {
        "name": "IBM Cloudant",
        "variant": "paas",
        "version": "8162"
      },
      "version": "2.1.1"
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Retrieve provisioned throughput capacity information

View the amount of provisioned throughput capacity that is allocated to an IBM Cloudant instance and what is the target provisioned throughput capacity.

View the amount of provisioned throughput capacity that is allocated to an IBM Cloudant instance and what is the target provisioned throughput capacity.

View the amount of provisioned throughput capacity that is allocated to an IBM Cloudant instance and what is the target provisioned throughput capacity.

View the amount of provisioned throughput capacity that is allocated to an IBM Cloudant instance and what is the target provisioned throughput capacity.

View the amount of provisioned throughput capacity that is allocated to an IBM Cloudant instance and what is the target provisioned throughput capacity.

GET /_api/v2/user/capacity/throughput
(cloudant *CloudantV1) GetCapacityThroughputInformation(getCapacityThroughputInformationOptions *GetCapacityThroughputInformationOptions) (result *CapacityThroughputInformation, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) GetCapacityThroughputInformationWithContext(ctx context.Context, getCapacityThroughputInformationOptions *GetCapacityThroughputInformationOptions) (result *CapacityThroughputInformation, response *core.DetailedResponse, err error)
ServiceCall<CapacityThroughputInformation> getCapacityThroughputInformation()
getCapacityThroughputInformation(params)
get_capacity_throughput_information(
        self,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.account-capacity-throughput.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.account-capacity-throughput.read

Request

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

WithContext method only

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

No Request Parameters

This method does not accept any request parameters.

  • ibmcloud cloudant capacity
  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/_api/v2/user/capacity/throughput"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    getCapacityThroughputInformationOptions := service.NewGetCapacityThroughputInformationOptions()
    
    capacityThroughputInformation, response, err := service.GetCapacityThroughputInformation(getCapacityThroughputInformationOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(capacityThroughputInformation, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.CapacityThroughputInformation;
    
    Cloudant service = Cloudant.newInstance();
    
    CapacityThroughputInformation response =
        service.getCapacityThroughputInformation().execute().getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.getCapacityThroughputInformation().then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.get_capacity_throughput_information().get_result()
    
    print(response)
    

Response

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Status Code

  • HTTP response for getCapacityThroughputInformation.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example CapacityThroughputInformation response.

    {
      "current": {
        "throughput": {
          "blocks": 5,
          "query": 25,
          "read": 500,
          "write": 250
        }
      },
      "target": {
        "throughput": {
          "blocks": 10,
          "query": 50,
          "read": 1000,
          "write": 500
        }
      }
    }
  • Example CapacityThroughputInformation response.

    {
      "current": {
        "throughput": {
          "blocks": 5,
          "query": 25,
          "read": 500,
          "write": 250
        }
      },
      "target": {
        "throughput": {
          "blocks": 10,
          "query": 50,
          "read": 1000,
          "write": 500
        }
      }
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Update the target provisioned throughput capacity

Sets the target provisioned throughput capacity for an IBM Cloudant instance. When target capacity is changed, the current capacity asynchronously changes to meet the target capacity.

Sets the target provisioned throughput capacity for an IBM Cloudant instance. When target capacity is changed, the current capacity asynchronously changes to meet the target capacity.

Sets the target provisioned throughput capacity for an IBM Cloudant instance. When target capacity is changed, the current capacity asynchronously changes to meet the target capacity.

Sets the target provisioned throughput capacity for an IBM Cloudant instance. When target capacity is changed, the current capacity asynchronously changes to meet the target capacity.

Sets the target provisioned throughput capacity for an IBM Cloudant instance. When target capacity is changed, the current capacity asynchronously changes to meet the target capacity.

PUT /_api/v2/user/capacity/throughput
(cloudant *CloudantV1) PutCapacityThroughputConfiguration(putCapacityThroughputConfigurationOptions *PutCapacityThroughputConfigurationOptions) (result *CapacityThroughputInformation, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PutCapacityThroughputConfigurationWithContext(ctx context.Context, putCapacityThroughputConfigurationOptions *PutCapacityThroughputConfigurationOptions) (result *CapacityThroughputInformation, response *core.DetailedResponse, err error)
ServiceCall<CapacityThroughputInformation> putCapacityThroughputConfiguration(PutCapacityThroughputConfigurationOptions putCapacityThroughputConfigurationOptions)
putCapacityThroughputConfiguration(params)
put_capacity_throughput_configuration(
        self,
        blocks: int,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.account-capacity-throughput.configure

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.account-capacity-throughput.configure

Request

Instantiate the PutCapacityThroughputConfigurationOptions struct and set the fields to provide parameter values for the PutCapacityThroughputConfiguration method.

Use the PutCapacityThroughputConfigurationOptions.Builder to create a PutCapacityThroughputConfigurationOptions object that contains the parameter values for the putCapacityThroughputConfiguration method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

HTTP request body for putCapacityThroughputConfiguration.

Examples:

Example CapacityThroughputConfiguration request.

{
  "blocks": 10
}

WithContext method only

The PutCapacityThroughputConfiguration options.

The putCapacityThroughputConfiguration options.

parameters

  • A number of blocks of throughput units. A block consists of 100 reads/sec, 50 writes/sec, and 5 global queries/sec of provisioned throughput capacity. Not available for some plans.

    Possible values: 1 ≤ value ≤ 100

    Examples:

parameters

  • A number of blocks of throughput units. A block consists of 100 reads/sec, 50 writes/sec, and 5 global queries/sec of provisioned throughput capacity. Not available for some plans.

    Possible values: 1 ≤ value ≤ 100

    Examples:
  • ibmcloud cloudant capacity-update --blocks 10
  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X PUT -H "Content-Type: application/json" "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/_api/v2/user/capacity/throughput" --data '{"blocks": 1}'
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    putCapacityThroughputConfigurationOptions := service.NewPutCapacityThroughputConfigurationOptions(
      1,
    )
    
    capacityThroughputConfiguration, response, err := service.PutCapacityThroughputConfiguration(putCapacityThroughputConfigurationOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(capacityThroughputConfiguration, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.CapacityThroughputInformation;
    import com.ibm.cloud.cloudant.v1.model.PutCapacityThroughputConfigurationOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    PutCapacityThroughputConfigurationOptions options =
        new PutCapacityThroughputConfigurationOptions.Builder()
            .blocks(1)
            .build();
    
    CapacityThroughputInformation response =
        service.putCapacityThroughputConfiguration(options).execute().getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.putCapacityThroughputConfiguration({
      blocks: 1,
    }).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.put_capacity_throughput_configuration(
      blocks=1
    ).get_result()
    
    print(response)
    

Response

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Schema for information about the currently provisioned and target throughput capacity.

Status Code

  • HTTP response for getCapacityThroughputInformation.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for unsupported media type.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example CapacityThroughputInformation response.

    {
      "current": {
        "throughput": {
          "blocks": 5,
          "query": 25,
          "read": 500,
          "write": 250
        }
      },
      "target": {
        "throughput": {
          "blocks": 10,
          "query": 50,
          "read": 1000,
          "write": 500
        }
      }
    }
  • Example CapacityThroughputInformation response.

    {
      "current": {
        "throughput": {
          "blocks": 5,
          "query": 25,
          "read": 500,
          "write": 250
        }
      },
      "target": {
        "throughput": {
          "blocks": 10,
          "query": 50,
          "read": 1000,
          "write": 500
        }
      }
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Retrieve one or more UUIDs

Requests one or more Universally Unique Identifiers (UUIDs) from the instance. The response is a JSON object that provides a list of UUIDs.

Tip: The authentication for this endpoint is only enforced when using IAM.

Requests one or more Universally Unique Identifiers (UUIDs) from the instance. The response is a JSON object that provides a list of UUIDs.

Tip: The authentication for this endpoint is only enforced when using IAM.

Requests one or more Universally Unique Identifiers (UUIDs) from the instance. The response is a JSON object that provides a list of UUIDs.

Tip: The authentication for this endpoint is only enforced when using IAM.

Requests one or more Universally Unique Identifiers (UUIDs) from the instance. The response is a JSON object that provides a list of UUIDs.

Tip: The authentication for this endpoint is only enforced when using IAM.

Requests one or more Universally Unique Identifiers (UUIDs) from the instance. The response is a JSON object that provides a list of UUIDs.

Tip: The authentication for this endpoint is only enforced when using IAM.

GET /_uuids
(cloudant *CloudantV1) GetUuids(getUuidsOptions *GetUuidsOptions) (result *UuidsResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) GetUuidsWithContext(ctx context.Context, getUuidsOptions *GetUuidsOptions) (result *UuidsResult, response *core.DetailedResponse, err error)
ServiceCall<UuidsResult> getUuids(GetUuidsOptions getUuidsOptions)
getUuids(params)
get_uuids(
        self,
        *,
        count: Optional[int] = None,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.cluster-uuids.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.cluster-uuids.read

Rate limit

This operation consumes one read request.

Request

Instantiate the GetUuidsOptions struct and set the fields to provide parameter values for the GetUuids method.

Use the GetUuidsOptions.Builder to create a GetUuidsOptions object that contains the parameter values for the getUuids method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Query Parameters

  • Query parameter to specify the number of UUIDs to return.

    Possible values: 0 ≤ value ≤ 1000

    Default: 1

WithContext method only

The GetUuids options.

The getUuids options.

parameters

  • Query parameter to specify the number of UUIDs to return.

    Possible values: 0 ≤ value ≤ 1000

    Default: 1

parameters

  • Query parameter to specify the number of UUIDs to return.

    Possible values: 0 ≤ value ≤ 1000

    Default: 1

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/_uuids?count=10"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    getUuidsOptions := service.NewGetUuidsOptions()
    getUuidsOptions.SetCount(10)
    
    uuidsResult, response, err := service.GetUuids(getUuidsOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(uuidsResult, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.GetUuidsOptions;
    import com.ibm.cloud.cloudant.v1.model.UuidsResult;
    
    Cloudant service = Cloudant.newInstance();
    
    GetUuidsOptions uuidsOptions = new GetUuidsOptions.Builder()
        .count(10)
        .build();
    
    UuidsResult response =
        service.getUuids(uuidsOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    const uuidsParams: CloudantV1.GetUuidsParams = {
      count: 10
    };
    
    service.getUuids(uuidsParams).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.get_uuids(count=10).get_result()
    
    print(response)
    

Response

Schema for a set of uuids generated by the server.

Schema for a set of uuids generated by the server.

Schema for a set of uuids generated by the server.

Schema for a set of uuids generated by the server.

Schema for a set of uuids generated by the server.

Status Code

  • HTTP response for /_uuids style operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example UuidsResult response.

    {
      "uuids": [
        "75480ca477454894678e22eec6002413",
        "75480ca477454894678e22eec600250b",
        "75480ca477454894678e22eec6002c41",
        "75480ca477454894678e22eec6003b90",
        "75480ca477454894678e22eec6003fca",
        "75480ca477454894678e22eec6004bef",
        "75480ca477454894678e22eec600528f",
        "75480ca477454894678e22eec6005e0b",
        "75480ca477454894678e22eec6006158",
        "75480ca477454894678e22eec6006161"
      ]
    }
  • Example UuidsResult response.

    {
      "uuids": [
        "75480ca477454894678e22eec6002413",
        "75480ca477454894678e22eec600250b",
        "75480ca477454894678e22eec6002c41",
        "75480ca477454894678e22eec6003b90",
        "75480ca477454894678e22eec6003fca",
        "75480ca477454894678e22eec6004bef",
        "75480ca477454894678e22eec600528f",
        "75480ca477454894678e22eec6005e0b",
        "75480ca477454894678e22eec6006158",
        "75480ca477454894678e22eec6006161"
      ]
    }
  • Example error response for a bad request for too many UUIDs.

    {
      "error": "bad_request",
      "reason": "count parameter too large"
    }
  • Example error response for a bad request for too many UUIDs.

    {
      "error": "bad_request",
      "reason": "count parameter too large"
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Query a list of all database names in the instance

Query to retrieve a list of database names from the instance.

Query to retrieve a list of database names from the instance.

Query to retrieve a list of database names from the instance.

Query to retrieve a list of database names from the instance.

Query to retrieve a list of database names from the instance.

GET /_all_dbs
(cloudant *CloudantV1) GetAllDbs(getAllDbsOptions *GetAllDbsOptions) (result []string, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) GetAllDbsWithContext(ctx context.Context, getAllDbsOptions *GetAllDbsOptions) (result []string, response *core.DetailedResponse, err error)
ServiceCall<List<String>> getAllDbs(GetAllDbsOptions getAllDbsOptions)
getAllDbs(params)
get_all_dbs(
        self,
        *,
        descending: Optional[bool] = None,
        end_key: Optional[str] = None,
        limit: Optional[int] = None,
        skip: Optional[int] = None,
        start_key: Optional[str] = None,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.account-all-dbs.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.account-all-dbs.read

Request

Instantiate the GetAllDbsOptions struct and set the fields to provide parameter values for the GetAllDbs method.

Use the GetAllDbsOptions.Builder to create a GetAllDbsOptions object that contains the parameter values for the getAllDbs method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Query Parameters

  • Query parameter to specify whether to return rows in descending by key order.

    Default: false

  • Query parameter to specify to stop returning records when the specified key is reached. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify the number of records before starting to return the results.

    Possible values: 0 ≤ value ≤ 9007199254740991

    Default: 0

  • Query parameter to specify to start returning records from the specified key. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

WithContext method only

The GetAllDbs options.

The getAllDbs options.

parameters

  • Query parameter to specify whether to return rows in descending by key order.

    Default: false

  • Query parameter to specify to stop returning records when the specified key is reached. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^.+$/

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify the number of records before starting to return the results.

    Possible values: 0 ≤ value ≤ 9007199254740991

    Default: 0

  • Query parameter to specify to start returning records from the specified key. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^.+$/

parameters

  • Query parameter to specify whether to return rows in descending by key order.

    Default: false

  • Query parameter to specify to stop returning records when the specified key is reached. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^.+$/

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify the number of records before starting to return the results.

    Possible values: 0 ≤ value ≤ 9007199254740991

    Default: 0

  • Query parameter to specify to start returning records from the specified key. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^.+$/

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/_all_dbs"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    getAllDbsOptions := service.NewGetAllDbsOptions()
    
    result, response, err := service.GetAllDbs(getAllDbsOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(result, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    
    import java.util.List;
    
    Cloudant service = Cloudant.newInstance();
    
    List<String> response =
        service.getAllDbs().execute().getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.getAllDbs().then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.get_all_dbs().get_result()
    
    print(response)
    

Response

Response type: []string

Response type: List<String>

Response type: string[]

Response type: List[str]

Schema for a list of database names.

Status Code

  • HTTP response for /_all_dbs style operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example AllDbs response.

    [
      "events",
      "orders",
      "products",
      "stores",
      "users"
    ]
  • Example AllDbs response.

    [
      "events",
      "orders",
      "products",
      "stores",
      "users"
    ]
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Query information about multiple databases

This operation enables you to request information about multiple databases in a single request, instead of issuing multiple GET /{db} requests. It returns a list that contains an information object for each database specified in the request.

This operation enables you to request information about multiple databases in a single request, instead of issuing multiple GET /{db} requests. It returns a list that contains an information object for each database specified in the request.

This operation enables you to request information about multiple databases in a single request, instead of issuing multiple GET /{db} requests. It returns a list that contains an information object for each database specified in the request.

This operation enables you to request information about multiple databases in a single request, instead of issuing multiple GET /{db} requests. It returns a list that contains an information object for each database specified in the request.

This operation enables you to request information about multiple databases in a single request, instead of issuing multiple GET /{db} requests. It returns a list that contains an information object for each database specified in the request.

POST /_dbs_info
(cloudant *CloudantV1) PostDbsInfo(postDbsInfoOptions *PostDbsInfoOptions) (result []DbsInfoResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostDbsInfoWithContext(ctx context.Context, postDbsInfoOptions *PostDbsInfoOptions) (result []DbsInfoResult, response *core.DetailedResponse, err error)
ServiceCall<List<DbsInfoResult>> postDbsInfo(PostDbsInfoOptions postDbsInfoOptions)
postDbsInfo(params)
post_dbs_info(
        self,
        keys: List[str],
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.account-dbs-info.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.account-dbs-info.read

Request

Instantiate the PostDbsInfoOptions struct and set the fields to provide parameter values for the PostDbsInfo method.

Use the PostDbsInfoOptions.Builder to create a PostDbsInfoOptions object that contains the parameter values for the postDbsInfo method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

HTTP request body for postDbsInfo.

Examples:

Example DbsInfoQuery request.

{
  "keys": [
    "products",
    "users",
    "orders"
  ]
}

WithContext method only

The PostDbsInfo options.

The postDbsInfo options.

parameters

  • A list of database names.

    Possible values: 0 ≤ number of items ≤ 100, 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

    Examples:

parameters

  • A list of database names.

    Possible values: 0 ≤ number of items ≤ 100, 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

    Examples:
  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X POST "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/_dbs_info" -H "Content-Type: application/json" --data '{
      "keys":  ["products", "users", "orders"]
    }'
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    postDbsInfoOptions := service.NewPostDbsInfoOptions([]string{
      "products",
      "users",
      "orders",
    })
    
    dbsInfoResult, response, err := service.PostDbsInfo(postDbsInfoOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(dbsInfoResult, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.DbsInfoResult;
    import com.ibm.cloud.cloudant.v1.model.PostDbsInfoOptions;
    
    import java.util.Arrays;
    import java.util.List;
    
    Cloudant service = Cloudant.newInstance();
    
    PostDbsInfoOptions dbsInfoOptions =
        new PostDbsInfoOptions.Builder()
            .keys(Arrays.asList("products", "users", "orders"))
            .build();
    
    List<DbsInfoResult> response =
        service.postDbsInfo(dbsInfoOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.postDbsInfo({
      keys: ['products', 'users', 'orders']
    }).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.post_dbs_info(
      keys=['products', 'users', 'orders']
    ).get_result()
    
    print(response)
    

Response

Response type: []DbsInfoResult

Response type: List<DbsInfoResult>

Response type: DbsInfoResult[]

Response type: List[DbsInfoResult]

Schema for a list of database information objects.

Status Code

  • HTTP response for postDbsInfo.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for payload too large.

  • HTTP error for unsupported media type.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example DbsInfoResults response.

    [
      {
        "info": {
          "cluster": {
            "n": 3,
            "q": 1,
            "r": 1,
            "w": 1
          },
          "compact_running": false,
          "db_name": "products",
          "disk_format_version": 8,
          "doc_count": 5,
          "doc_del_count": 1,
          "instance_start_time": "0",
          "partitioned_indexes": {
            "count": 4,
            "indexes": {
              "search": 2,
              "view": 2
            },
            "limit": 10
          },
          "props": {
            "partitioned": true
          },
          "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
          "sizes": {
            "active": 8887,
            "external": 1872,
            "file": 685680
          },
          "update_seq": "89-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj"
        },
        "key": "products"
      },
      {
        "info": {
          "cluster": {
            "n": 3,
            "q": 8,
            "r": 2,
            "w": 2
          },
          "compact_running": false,
          "db_name": "users",
          "disk_format_version": 8,
          "doc_count": 11,
          "doc_del_count": 0,
          "instance_start_time": "0",
          "props": {},
          "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
          "sizes": {
            "active": 67475,
            "external": 2339,
            "file": 3872387
          },
          "update_seq": "13-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj"
        },
        "key": "users"
      },
      {
        "info": {
          "cluster": {
            "n": 3,
            "q": 8,
            "r": 2,
            "w": 2
          },
          "compact_running": false,
          "db_name": "orders",
          "disk_format_version": 8,
          "doc_count": 5,
          "doc_del_count": 0,
          "instance_start_time": "0",
          "props": {},
          "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
          "sizes": {
            "active": 44475,
            "external": 1339,
            "file": 133970
          },
          "update_seq": "13-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj"
        },
        "key": "orders"
      }
    ]
  • Example DbsInfoResults response.

    [
      {
        "info": {
          "cluster": {
            "n": 3,
            "q": 1,
            "r": 1,
            "w": 1
          },
          "compact_running": false,
          "db_name": "products",
          "disk_format_version": 8,
          "doc_count": 5,
          "doc_del_count": 1,
          "instance_start_time": "0",
          "partitioned_indexes": {
            "count": 4,
            "indexes": {
              "search": 2,
              "view": 2
            },
            "limit": 10
          },
          "props": {
            "partitioned": true
          },
          "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
          "sizes": {
            "active": 8887,
            "external": 1872,
            "file": 685680
          },
          "update_seq": "89-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj"
        },
        "key": "products"
      },
      {
        "info": {
          "cluster": {
            "n": 3,
            "q": 8,
            "r": 2,
            "w": 2
          },
          "compact_running": false,
          "db_name": "users",
          "disk_format_version": 8,
          "doc_count": 11,
          "doc_del_count": 0,
          "instance_start_time": "0",
          "props": {},
          "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
          "sizes": {
            "active": 67475,
            "external": 2339,
            "file": 3872387
          },
          "update_seq": "13-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj"
        },
        "key": "users"
      },
      {
        "info": {
          "cluster": {
            "n": 3,
            "q": 8,
            "r": 2,
            "w": 2
          },
          "compact_running": false,
          "db_name": "orders",
          "disk_format_version": 8,
          "doc_count": 5,
          "doc_del_count": 0,
          "instance_start_time": "0",
          "props": {},
          "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
          "sizes": {
            "active": 44475,
            "external": 1339,
            "file": 133970
          },
          "update_seq": "13-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj"
        },
        "key": "orders"
      }
    ]
  • Example error response for a bad request missing keys.

    {
      "error": "bad_request",
      "reason": "`keys` member must exist."
    }
  • Example error response for a bad request missing keys.

    {
      "error": "bad_request",
      "reason": "`keys` member must exist."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Delete a database

Deletes the specified database and all documents and attachments contained within it. To avoid deleting a database, the server responds with a 400 HTTP status code when the request URL includes a ?rev= parameter. This response suggests that a user wanted to delete a document but forgot to add the document ID to the URL.

Deletes the specified database and all documents and attachments contained within it. To avoid deleting a database, the server responds with a 400 HTTP status code when the request URL includes a ?rev= parameter. This response suggests that a user wanted to delete a document but forgot to add the document ID to the URL.

Deletes the specified database and all documents and attachments contained within it. To avoid deleting a database, the server responds with a 400 HTTP status code when the request URL includes a ?rev= parameter. This response suggests that a user wanted to delete a document but forgot to add the document ID to the URL.

Deletes the specified database and all documents and attachments contained within it. To avoid deleting a database, the server responds with a 400 HTTP status code when the request URL includes a ?rev= parameter. This response suggests that a user wanted to delete a document but forgot to add the document ID to the URL.

Deletes the specified database and all documents and attachments contained within it. To avoid deleting a database, the server responds with a 400 HTTP status code when the request URL includes a ?rev= parameter. This response suggests that a user wanted to delete a document but forgot to add the document ID to the URL.

DELETE /{db}
(cloudant *CloudantV1) DeleteDatabase(deleteDatabaseOptions *DeleteDatabaseOptions) (result *Ok, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) DeleteDatabaseWithContext(ctx context.Context, deleteDatabaseOptions *DeleteDatabaseOptions) (result *Ok, response *core.DetailedResponse, err error)
ServiceCall<Ok> deleteDatabase(DeleteDatabaseOptions deleteDatabaseOptions)
deleteDatabase(params)
delete_database(
        self,
        db: str,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.database.delete

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.database.delete

Rate limit

This operation consumes one write request.

Request

Instantiate the DeleteDatabaseOptions struct and set the fields to provide parameter values for the DeleteDatabase method.

Use the DeleteDatabaseOptions.Builder to create a DeleteDatabaseOptions object that contains the parameter values for the deleteDatabase method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

WithContext method only

The DeleteDatabase options.

The deleteDatabase options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X DELETE "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    deleteDatabaseOptions := service.NewDeleteDatabaseOptions(
      "products",
    )
    
    ok, response, err := service.DeleteDatabase(deleteDatabaseOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(ok, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.DeleteDatabaseOptions;
    import com.ibm.cloud.cloudant.v1.model.Ok;
    
    Cloudant service = Cloudant.newInstance();
    
    DeleteDatabaseOptions databaseOptions =
        new DeleteDatabaseOptions.Builder()
            .db("products")
            .build();
    
    Ok response =
        service.deleteDatabase(databaseOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.deleteDatabase({db: 'products'}).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.delete_database(db='products').get_result()
    
    print(response)
    

Response

Schema for an OK result.

Schema for an OK result.

Schema for an OK result.

Schema for an OK result.

Schema for an OK result.

Status Code

  • HTTP response for Ok operations.

  • HTTP response for Ok operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example Ok response.

    {
      "ok": true
    }
  • Example Ok response.

    {
      "ok": true
    }
  • Example Ok response.

    {
      "ok": true
    }
  • Example Ok response.

    {
      "ok": true
    }
  • Example error response for a bad request deleting a database with a document rev.

    {
      "error": "bad_request",
      "reason": "You tried to DELETE a database with a ?=rev parameter. Did you mean to DELETE a document instead?"
    }
  • Example error response for a bad request deleting a database with a document rev.

    {
      "error": "bad_request",
      "reason": "You tried to DELETE a database with a ?=rev parameter. Did you mean to DELETE a document instead?"
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Retrieve information about a database

Retrieve detailed information about the database.

Retrieve detailed information about the database.

Retrieve detailed information about the database.

Retrieve detailed information about the database.

Retrieve detailed information about the database.

GET /{db}
(cloudant *CloudantV1) GetDatabaseInformation(getDatabaseInformationOptions *GetDatabaseInformationOptions) (result *DatabaseInformation, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) GetDatabaseInformationWithContext(ctx context.Context, getDatabaseInformationOptions *GetDatabaseInformationOptions) (result *DatabaseInformation, response *core.DetailedResponse, err error)
ServiceCall<DatabaseInformation> getDatabaseInformation(GetDatabaseInformationOptions getDatabaseInformationOptions)
getDatabaseInformation(params)
get_database_information(
        self,
        db: str,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.database-info.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.database-info.read

Request

Instantiate the GetDatabaseInformationOptions struct and set the fields to provide parameter values for the GetDatabaseInformation method.

Use the GetDatabaseInformationOptions.Builder to create a GetDatabaseInformationOptions object that contains the parameter values for the getDatabaseInformation method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

WithContext method only

The GetDatabaseInformation options.

The getDatabaseInformation options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    getDatabaseInformationOptions := service.NewGetDatabaseInformationOptions(
      "products",
    )
    
    databaseInformation, response, err := service.GetDatabaseInformation(getDatabaseInformationOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(databaseInformation, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.DatabaseInformation;
    import com.ibm.cloud.cloudant.v1.model.GetDatabaseInformationOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    GetDatabaseInformationOptions databaseInfoOptions =
        new GetDatabaseInformationOptions.Builder()
            .db("products")
            .build();
    
    DatabaseInformation response =
        service.getDatabaseInformation(databaseInfoOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.getDatabaseInformation({db: 'products'}).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.get_database_information(db='products').get_result()
    
    print(response)
    

Response

Schema for information about a database.

Schema for information about a database.

Schema for information about a database.

Schema for information about a database.

Schema for information about a database.

Status Code

  • HTTP response for DatabaseInformation.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example DatabaseInformation response.

    {
      "cluster": {
        "n": 3,
        "q": 8,
        "r": 2,
        "w": 2
      },
      "compact_running": false,
      "db_name": "products",
      "disk_format_version": 8,
      "doc_count": 5,
      "doc_del_count": 1,
      "instance_start_time": "0",
      "partitioned_indexes": {
        "count": 4,
        "indexes": {
          "search": 2,
          "view": 2
        },
        "limit": 10
      },
      "props": {
        "partitioned": true
      },
      "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
      "sizes": {
        "active": 8887,
        "external": 1872,
        "file": 685680
      },
      "update_seq": "89-g1AAAAIjeJzLYWBg4MhgTmHQTklKzi9KdUhJMtbLzCtJTS9KLMnMzysuSS0uMTAw1EvOyS9NScwr0ctLLckBamLKYwGSDA-A1H8gyErkRDXFkBRTDkBMuY9hihEppiyAmLI_K1GQAh81QEyZn5XIRZaPkhKAZFI9tjAh0jdJDiAT4rGZQKRPkhRAJtiDTRAkyxeJDEnyEAdkAQCgLLsf"
    }
  • Example DatabaseInformation response.

    {
      "cluster": {
        "n": 3,
        "q": 8,
        "r": 2,
        "w": 2
      },
      "compact_running": false,
      "db_name": "products",
      "disk_format_version": 8,
      "doc_count": 5,
      "doc_del_count": 1,
      "instance_start_time": "0",
      "partitioned_indexes": {
        "count": 4,
        "indexes": {
          "search": 2,
          "view": 2
        },
        "limit": 10
      },
      "props": {
        "partitioned": true
      },
      "purge_seq": "8-g1AAAALReJyd0T8OgjAUBvCKjq6ewM2BQPyz6hUUeoAWSExDIDE4ewqvoNBLeAouwRmE58diQprY4PR16C9f-17KGJufpzFbxjLKL8khljs3SvNrLLLC8_zv2c2SIsVlRzC54DxUwhmyzW_WIy5XWldKTEYV9kjLPVFnSFsnEEn0Bob0LRIolErrUgk2lGuLBKrkjag1pK0TqMtm7MT53XivpRUsAEM8MSxjN5YJg5VgiDfRa-xmwVowxJHz-o9ufLhGPLRujJltrRofbhDYNGFq6gOYofZj",
      "sizes": {
        "active": 8887,
        "external": 1872,
        "file": 685680
      },
      "update_seq": "89-g1AAAAIjeJzLYWBg4MhgTmHQTklKzi9KdUhJMtbLzCtJTS9KLMnMzysuSS0uMTAw1EvOyS9NScwr0ctLLckBamLKYwGSDA-A1H8gyErkRDXFkBRTDkBMuY9hihEppiyAmLI_K1GQAh81QEyZn5XIRZaPkhKAZFI9tjAh0jdJDiAT4rGZQKRPkhRAJtiDTRAkyxeJDEnyEAdkAQCgLLsf"
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a database does not exist.

    {
      "error": "not_found",
      "reason": "Database does not exist."
    }
  • Example error response for a database does not exist.

    {
      "error": "not_found",
      "reason": "Database does not exist."
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Retrieve the HTTP headers for a database

Returns the HTTP headers that contain a minimal amount of information about the specified database. Since the response body is empty, using the HEAD method is a lightweight way to check if the database exists or not.

Returns the HTTP headers that contain a minimal amount of information about the specified database. Since the response body is empty, using the HEAD method is a lightweight way to check if the database exists or not.

Returns the HTTP headers that contain a minimal amount of information about the specified database. Since the response body is empty, using the HEAD method is a lightweight way to check if the database exists or not.

Returns the HTTP headers that contain a minimal amount of information about the specified database. Since the response body is empty, using the HEAD method is a lightweight way to check if the database exists or not.

Returns the HTTP headers that contain a minimal amount of information about the specified database. Since the response body is empty, using the HEAD method is a lightweight way to check if the database exists or not.

HEAD /{db}
(cloudant *CloudantV1) HeadDatabase(headDatabaseOptions *HeadDatabaseOptions) (response *core.DetailedResponse, err error)
(cloudant *CloudantV1) HeadDatabaseWithContext(ctx context.Context, headDatabaseOptions *HeadDatabaseOptions) (response *core.DetailedResponse, err error)
ServiceCall<Void> headDatabase(HeadDatabaseOptions headDatabaseOptions)
headDatabase(params)
head_database(
        self,
        db: str,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.database-info.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.database-info.read

Request

Instantiate the HeadDatabaseOptions struct and set the fields to provide parameter values for the HeadDatabase method.

Use the HeadDatabaseOptions.Builder to create a HeadDatabaseOptions object that contains the parameter values for the headDatabase method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

WithContext method only

The HeadDatabase options.

The headDatabase options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" --head "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    headDatabaseOptions := service.NewHeadDatabaseOptions(
      "products",
    )
    
    response, err := service.HeadDatabase(headDatabaseOptions)
    if err != nil {
      panic(err)
    }
    
    fmt.Println(response.StatusCode)
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.HeadDatabaseOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    HeadDatabaseOptions databaseOptions =
        new HeadDatabaseOptions.Builder()
            .db("products")
            .build();
    
    int statusCode =
        service.headDatabase(databaseOptions).execute().getStatusCode();
    
    System.out.println(statusCode);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.headDatabase({db: 'products'}).then(response => {
      console.log(response.status);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.head_database(db='products')
    print(response.get_status_code())
    

Response

Response Headers

  • Header for returning the compression codec used if an attachment's content_type is in list of compressible types.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Header returning the attachment size. If a compression codec is used, this value is the compressed size.

    Possible values: 0 ≤ value ≤ 10485760

  • Header returning the server response date-time.

    Possible values: 28 ≤ length ≤ 31, Value must match regular expression ^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), [0-3]\d (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} [0-2]\d:[0-5]\d:[0-6]\d ([+-]\d{4}|[A-Z]{2,3})$

  • Header returning the server information.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Header added by proxies through which the response was sent.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Header returning the Cloudant IAM action of the request.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^cloudantnosqldb\..+$

  • Header returning the Cloudant backend that handled the request.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Header returning the Cloudant class of the request.

    Possible values: [lookup,query,unlimited,write]

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

Status Code

  • HTTP response for DatabaseInformation.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Create a database

Create a new database with the requested properties.

Create a new database with the requested properties.

Create a new database with the requested properties.

Create a new database with the requested properties.

Create a new database with the requested properties.

PUT /{db}
(cloudant *CloudantV1) PutDatabase(putDatabaseOptions *PutDatabaseOptions) (result *Ok, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PutDatabaseWithContext(ctx context.Context, putDatabaseOptions *PutDatabaseOptions) (result *Ok, response *core.DetailedResponse, err error)
ServiceCall<Ok> putDatabase(PutDatabaseOptions putDatabaseOptions)
putDatabase(params)
put_database(
        self,
        db: str,
        *,
        partitioned: Optional[bool] = None,
        q: Optional[int] = None,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.database.create

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.database.create

Rate limit

This operation consumes one write request.

Request

Instantiate the PutDatabaseOptions struct and set the fields to provide parameter values for the PutDatabase method.

Use the PutDatabaseOptions.Builder to create a PutDatabaseOptions object that contains the parameter values for the putDatabase method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

Query Parameters

  • Query parameter to specify whether to enable database partitions when creating a database.

    Before using read the FAQs to understand the limitations and appropriate use cases.

    Default: false

  • The number of replicas of the database in the cluster. The default is 3, unless overridden in the cluster config.

    Possible values: value = 3

    Default: 3

  • The number of shards in the database. Each shard is a partition of the hash value range. Cloudant recommends using the default value for most databases. However, if your database is expected to be larger than 250 GB or have a lot of indexes, you may need to adjust the settings. In these cases, it's best to reach out to IBM Cloudant customer support for guidance on how to meet your specific needs and requirements.

    Possible values: 1 ≤ value ≤ 120

    Default: 16

WithContext method only

The PutDatabase options.

The putDatabase options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Query parameter to specify whether to enable database partitions when creating a database.

    Before using read the FAQs to understand the limitations and appropriate use cases.

    Default: false

  • The number of shards in the database. Each shard is a partition of the hash value range. Cloudant recommends using the default value for most databases. However, if your database is expected to be larger than 250 GB or have a lot of indexes, you may need to adjust the settings. In these cases, it's best to reach out to IBM Cloudant customer support for guidance on how to meet your specific needs and requirements.

    Possible values: 1 ≤ value ≤ 120

    Default: 16

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Query parameter to specify whether to enable database partitions when creating a database.

    Before using read the FAQs to understand the limitations and appropriate use cases.

    Default: false

  • The number of shards in the database. Each shard is a partition of the hash value range. Cloudant recommends using the default value for most databases. However, if your database is expected to be larger than 250 GB or have a lot of indexes, you may need to adjust the settings. In these cases, it's best to reach out to IBM Cloudant customer support for guidance on how to meet your specific needs and requirements.

    Possible values: 1 ≤ value ≤ 120

    Default: 16

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X PUT "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products"
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    putDatabaseOptions := service.NewPutDatabaseOptions(
      "events",
    )
    putDatabaseOptions.SetPartitioned(true)
    
    ok, response, err := service.PutDatabase(putDatabaseOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(ok, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.Ok;
    import com.ibm.cloud.cloudant.v1.model.PutDatabaseOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    PutDatabaseOptions databaseOptions = new PutDatabaseOptions.Builder()
        .db("events")
        .partitioned(true)
        .build();
    
    Ok response =
        service.putDatabase(databaseOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.putDatabase({
      db: 'events',
      partitioned: true
    }).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.put_database(db='events', partitioned=True).get_result()
    
    print(response)
    

Response

Schema for an OK result.

Schema for an OK result.

Schema for an OK result.

Schema for an OK result.

Schema for an OK result.

Status Code

  • HTTP response for database creation operation.

  • HTTP response for database creation operation.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for precondition failed.

  • HTTP error for unsupported media type.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example Ok response.

    {
      "ok": true
    }
  • Example Ok response.

    {
      "ok": true
    }
  • Example Ok response.

    {
      "ok": true
    }
  • Example Ok response.

    {
      "ok": true
    }
  • Example error response for an invalid database name.

    {
      "error": "illegal_database_name",
      "reason": "Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed. Must begin with a letter."
    }
  • Example error response for an invalid database name.

    {
      "error": "illegal_database_name",
      "reason": "Only lowercase characters (a-z), digits (0-9), and any of the characters _, $, (, ), +, -, and / are allowed. Must begin with a letter."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for a database already existing.

    {
      "error": "file_exists",
      "reason": "The database could not be created, the file already exists."
    }
  • Example error response for a database already existing.

    {
      "error": "file_exists",
      "reason": "The database could not be created, the file already exists."
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Query the database document changes feed (GET)

Returns a sorted list of changes made to documents in the database, in time order of application. Only the most recent change for a specific document is included in the list. For example, if you add fields to a document and then delete them, an API client that checks for changes might not know about the intermediate state of added documents. These checks listen for updates to the database for post processing or synchronization, and for practical purposes, a continuously connected _changes feed is a reasonable approach for generating a real-time log for most applications.

Note

Before using the changes feed read the FAQs to understand the limitations and appropriate use cases.

To use some filter types you must use the POST version of this request.

GET /{db}/_changes

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.any-document.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.any-document.read

Request

Custom Headers

  • Header parameter to specify the ID of the last events received by the server on a previous connection. Overrides since query parameter.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^0|([1-9]\d*-[A-Za-z0-9-_]+)|now$

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

Query Parameters

  • Query parameter to specify whether to include the encoding information for compressed attachments. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include attachment content in the response. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include a list of conflicted revisions in each returned document. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to return changes in the descending order with most recent change first. The since parameter has no effect when using descending order.

    Default: false

  • Query parameter to specify a JSON array list of document IDs to restrict the changes feed to. Used with the _doc_ids filter. Since length of URL is limited, it is better to use POST /{db}/_changes instead.

    Possible values: 0 ≤ number of items ≤ 65535, 1 ≤ length ≤ 7168, Value must match regular expression ^[^_].*$

  • Query parameter to specify the changes feed type.

    Allowable values: [continuous,eventsource,longpoll,normal]

    Default: normal

  • Query parameter to specify a filter to emit only specific events from the changes stream.

    The built-in filter types are:

    • _design - Returns only changes to design documents.
    • _doc_ids - Returns changes for documents with an ID matching one specified in doc_ids request body parameter. (POST only)
    • _selector - Returns changes for documents that match the selector request body parameter. The selector syntax is the same as used for _find. (POST only)
    • _view - Returns changes for documents that match an existing map function in the view specified by the query parameter view.

    Additionally, the value can be the name of a JS filter function from a design document. For example: design_doc/filtername.

    Note: For better performance use the built-in _selector, _design or _doc_ids filters rather than JS based _view or design document filters. If you need to pass values to change the filtered content use the _selector filter type.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^_design|_docs_ids|_selector|_view|.*\/.*$

  • Query parameter to specify the period in milliseconds after which an empty line is sent in the results. Off by default and only applicable for continuous and eventsource feeds. Overrides any timeout to keep the feed alive indefinitely. May also be true to use a value of 60000.

    Note: Delivery of heartbeats cannot be relied on at specific intervals. If your application runs in an environment where idle network connections may break, heartbeat is not suitable as a keepalive mechanism. Instead, consider one of the following options:

    • Use the timeout parameter with a value that is compatible with your network environment.
    • Switch to scheduled usage of one of the non-continuous changes feed types (normal or longpoll).
    • Use TCP keepalive.

    Possible values: 1 ≤ value ≤ 60000

  • Query parameter to specify whether to include the full content of the documents in the response.

    Default: false

  • Query parameter to specify the ID of the last events received by the server on a previous connection. Alias of Last-Event-ID header.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^0|([1-9]\d*-[A-Za-z0-9-_]+)|now$

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify that the update seq should only be calculated with every Nth result returned. When fetching changes in a batch, setting seq_interval=<batch size>, where <batch size> is the number of results requested per batch, load can be reduced on the source database as computing the seq value across many shards (especially in highly-sharded databases) is expensive.

    Possible values: 1 ≤ value ≤ 4294967295

  • Query parameter to specify to start the results from the change immediately after the given update sequence. Possible values are:

    • 0 for all available changes (default).
    • now for future changes.
    • A valid update sequence, for example, from the seq value of a change received before.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^0|([1-9]\d*-[A-Za-z0-9-_]+)|now$

    Example: 0

  • Query parameter to specify how many revisions are returned in the changes array. The default, main_only, will only return the current "winning" revision; all_docs will return all leaf revisions (including conflicts and deleted former conflicts).

    Allowable values: [main_only,all_docs]

    Default: main_only

  • Query parameter to specify the 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. Default value is specified by httpd/changes_timeout configuration option. Note that 60000 value is also the default maximum timeout to prevent undetected dead connections.

    Possible values: 0 ≤ value ≤ 60000

    Default: 60000

  • Query parameter to specify a view function as a filter. Documents pass the filter if the view's map function emits at least one record for them.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^[^_].*$

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_changes?limit=1"
    

Response

Schema for normal changes feed result.

Status Code

  • HTTP response for /{db}/_changes style operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example ChangesResult response.

    {
      "last_seq": "7-g1AAAAPveJy1kk9OAjEYxSuYGBO3nsCdC9LOP5yVXkGhB-jXdoKTsSQG1p7CKyj0Ep6CS3AGob5hwYSNMJOwek3T971fXr-KMXYz6Rt2Z0hP3-2ToWygq-ncKDfjXOzPA2dnFR73FKNbKcelYoe2-H9bbZJ07_2ynPTVxRvurjTPhU6i06YcpkVH0hDk6TGEbWtOmAKBddRwUpw-iKE4ByeCxlR6v2jNCdOSPkLY1JxsxykyLlKuDLueO2OLV2dNq6-tx23dJXuR8rMtD2wj2CDfqL5m6u2Ycp1HQ5N26e4ILaIWiIL8hvDTgXcDG-RZylXDm8V5IbLkPLwodgX58n7dgRfFriHYz9DsZpqQtQWdNqn8A1TdTOE",
      "pending": 3,
      "results": [
        {
          "changes": [
            {
              "rev": "7-7a5191bfeb2f6eed6b3b6fa83f4810f5"
            }
          ],
          "deleted": true,
          "id": "0007741142412418284",
          "seq": "1-g1AAAAMFeJydkcENgjAUhquYePHqBN48EEBj4klXUOgAbSExDUJi8OwUrqDQJZyCJZhBqD8XE0Iiwulvmvf1e68vJITMToZPFj4X8SXY-3xjijC--ixKLMv-ns0oSEIUjxnhc0o9yUgTW_3GaojypVKZPBlsdMbdVFhbW6yd_15p2pwOG0SK77SuevcJSHP06rbILicgj0ul0t5OQBm_aV22yI5l1FAVTciR0ntfKzAXGOKJz-prBpYCQ7y1fg1wl8AQB0rzAW4MnCMeShUD3Bi4QGDTGrT8AMkPBk0"
        }
      ]
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Query the database document changes feed

Requests the database changes feed in the same way as GET /{db}/_changes does. It is widely used with the filter query parameter because it allows one to pass more information to the filter.

Note

Before using the changes feed read the FAQs to understand the limitations and appropriate use cases.

If you need to pass parameters to dynamically change the filtered content use the _selector filter type for better performance and compatibility. The SDKs have full support for change requests using selector filters, but don't support passing parameters to design document filters.

Requests the database changes feed in the same way as GET /{db}/_changes does. It is widely used with the filter query parameter because it allows one to pass more information to the filter.

Note

Before using the changes feed read the FAQs to understand the limitations and appropriate use cases.

If you need to pass parameters to dynamically change the filtered content use the _selector filter type for better performance and compatibility. The SDKs have full support for change requests using selector filters, but don't support passing parameters to design document filters.

Requests the database changes feed in the same way as GET /{db}/_changes does. It is widely used with the filter query parameter because it allows one to pass more information to the filter.

Note

Before using the changes feed read the FAQs to understand the limitations and appropriate use cases.

If you need to pass parameters to dynamically change the filtered content use the _selector filter type for better performance and compatibility. The SDKs have full support for change requests using selector filters, but don't support passing parameters to design document filters.

Requests the database changes feed in the same way as GET /{db}/_changes does. It is widely used with the filter query parameter because it allows one to pass more information to the filter.

Note

Before using the changes feed read the FAQs to understand the limitations and appropriate use cases.

If you need to pass parameters to dynamically change the filtered content use the _selector filter type for better performance and compatibility. The SDKs have full support for change requests using selector filters, but don't support passing parameters to design document filters.

Requests the database changes feed in the same way as GET /{db}/_changes does. It is widely used with the filter query parameter because it allows one to pass more information to the filter.

Note

Before using the changes feed read the FAQs to understand the limitations and appropriate use cases.

If you need to pass parameters to dynamically change the filtered content use the _selector filter type for better performance and compatibility. The SDKs have full support for change requests using selector filters, but don't support passing parameters to design document filters.

POST /{db}/_changes
(cloudant *CloudantV1) PostChanges(postChangesOptions *PostChangesOptions) (result *ChangesResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostChangesWithContext(ctx context.Context, postChangesOptions *PostChangesOptions) (result *ChangesResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostChangesAsStream(postChangesOptions *PostChangesOptions) (result io.ReadCloser, response *core.DetailedResponse, err error)
ServiceCall<ChangesResult> postChanges(PostChangesOptions postChangesOptions)
ServiceCall<InputStream> postChangesAsStream(PostChangesOptions postChangesOptions)
postChanges(params)
postChangesAsStream(params)
post_changes(
        self,
        db: str,
        *,
        doc_ids: Optional[List[str]] = None,
        fields: Optional[List[str]] = None,
        selector: Optional[dict] = None,
        last_event_id: Optional[str] = None,
        att_encoding_info: Optional[bool] = None,
        attachments: Optional[bool] = None,
        conflicts: Optional[bool] = None,
        descending: Optional[bool] = None,
        feed: Optional[str] = None,
        filter: Optional[str] = None,
        heartbeat: Optional[int] = None,
        include_docs: Optional[bool] = None,
        limit: Optional[int] = None,
        seq_interval: Optional[int] = None,
        since: Optional[str] = None,
        style: Optional[str] = None,
        timeout: Optional[int] = None,
        view: Optional[str] = None,
        **kwargs,
    ) -> DetailedResponse
post_changes_as_stream(
        self,
        db: str,
        *,
        doc_ids: Optional[List[str]] = None,
        fields: Optional[List[str]] = None,
        selector: Optional[dict] = None,
        last_event_id: Optional[str] = None,
        att_encoding_info: Optional[bool] = None,
        attachments: Optional[bool] = None,
        conflicts: Optional[bool] = None,
        descending: Optional[bool] = None,
        feed: Optional[str] = None,
        filter: Optional[str] = None,
        heartbeat: Optional[int] = None,
        include_docs: Optional[bool] = None,
        limit: Optional[int] = None,
        seq_interval: Optional[int] = None,
        since: Optional[str] = None,
        style: Optional[str] = None,
        timeout: Optional[int] = None,
        view: Optional[str] = None,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.any-document.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.any-document.read

Request

Instantiate the PostChangesOptions struct and set the fields to provide parameter values for the PostChanges method.

Use the PostChangesOptions.Builder to create a PostChangesOptions object that contains the parameter values for the postChanges method.

Custom Headers

  • Header parameter to specify the ID of the last events received by the server on a previous connection. Overrides since query parameter.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^0|([1-9]\d*-[A-Za-z0-9-_]+)|now$

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

Query Parameters

  • Query parameter to specify whether to include the encoding information for compressed attachments. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include attachment content in the response. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include a list of conflicted revisions in each returned document. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to return changes in the descending order with most recent change first. The since parameter has no effect when using descending order.

    Default: false

  • Query parameter to specify the changes feed type.

    Allowable values: [continuous,eventsource,longpoll,normal]

    Default: normal

  • Query parameter to specify a filter to emit only specific events from the changes stream.

    The built-in filter types are:

    • _design - Returns only changes to design documents.
    • _doc_ids - Returns changes for documents with an ID matching one specified in doc_ids request body parameter. (POST only)
    • _selector - Returns changes for documents that match the selector request body parameter. The selector syntax is the same as used for _find. (POST only)
    • _view - Returns changes for documents that match an existing map function in the view specified by the query parameter view.

    Additionally, the value can be the name of a JS filter function from a design document. For example: design_doc/filtername.

    Note: For better performance use the built-in _selector, _design or _doc_ids filters rather than JS based _view or design document filters. If you need to pass values to change the filtered content use the _selector filter type.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^_design|_docs_ids|_selector|_view|.*\/.*$

  • Query parameter to specify the period in milliseconds after which an empty line is sent in the results. Off by default and only applicable for continuous and eventsource feeds. Overrides any timeout to keep the feed alive indefinitely. May also be true to use a value of 60000.

    Note: Delivery of heartbeats cannot be relied on at specific intervals. If your application runs in an environment where idle network connections may break, heartbeat is not suitable as a keepalive mechanism. Instead, consider one of the following options:

    • Use the timeout parameter with a value that is compatible with your network environment.
    • Switch to scheduled usage of one of the non-continuous changes feed types (normal or longpoll).
    • Use TCP keepalive.

    Possible values: 1 ≤ value ≤ 60000

  • Query parameter to specify whether to include the full content of the documents in the response.

    Default: false

  • Query parameter to specify the ID of the last events received by the server on a previous connection. Alias of Last-Event-ID header.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^0|([1-9]\d*-[A-Za-z0-9-_]+)|now$

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify that the update seq should only be calculated with every Nth result returned. When fetching changes in a batch, setting seq_interval=<batch size>, where <batch size> is the number of results requested per batch, load can be reduced on the source database as computing the seq value across many shards (especially in highly-sharded databases) is expensive.

    Possible values: 1 ≤ value ≤ 4294967295

  • Query parameter to specify to start the results from the change immediately after the given update sequence. Possible values are:

    • 0 for all available changes (default).
    • now for future changes.
    • A valid update sequence, for example, from the seq value of a change received before.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^0|([1-9]\d*-[A-Za-z0-9-_]+)|now$

    Example: 0

  • Query parameter to specify how many revisions are returned in the changes array. The default, main_only, will only return the current "winning" revision; all_docs will return all leaf revisions (including conflicts and deleted former conflicts).

    Allowable values: [main_only,all_docs]

    Default: main_only

  • Query parameter to specify the 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. Default value is specified by httpd/changes_timeout configuration option. Note that 60000 value is also the default maximum timeout to prevent undetected dead connections.

    Possible values: 0 ≤ value ≤ 60000

    Default: 60000

  • Query parameter to specify a view function as a filter. Documents pass the filter if the view's map function emits at least one record for them.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^[^_].*$

HTTP request body for postChanges.

Examples:

Example ChangesQuery request if ?filter=_doc_ids is used.

{
  "doc_ids": [
    "0007741142412418284"
  ]
}

Example ChangesQuery request if ?filter=_selector is used.

{
  "fields": [
    "type",
    "user"
  ],
  "selector": {
    "_id": {
      "$regex": "^0+7741142412418284"
    }
  }
}

WithContext method only

The PostChanges options.

The postChanges options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Schema for a list of document IDs.

    Possible values: 0 ≤ number of items ≤ 65535, 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

    Examples:
  • JSON array that uses the field syntax. Use this parameter to specify which fields of a document must be returned. If it is omitted or empty, the entire document is returned.

    Possible values: 0 ≤ number of items ≤ 65535, 1 ≤ length ≤ 7168, Value must match regular expression /^.+$/

  • JSON object describing criteria used to select documents. The selector specifies fields in the document, and provides an expression to evaluate with the field content or other data.

    The selector object must:

    • Be structured as valid JSON.
    • Contain a valid query expression.

    Using a selector is significantly more efficient than using a JavaScript filter function, and is the recommended option if filtering on document attributes only.

    Elementary selector syntax requires you to specify one or more fields, and the corresponding values required for those fields. You can create more complex selector expressions by combining operators.

    Operators are identified by the use of a dollar sign $ prefix in the name field.

    There are two core types of operators in the selector syntax:

    • Combination operators: applied at the topmost level of selection. They are used to combine selectors. A combination operator takes a single argument. The argument is either another selector, or an array of selectors.
    • Condition operators: are specific to a field, and are used to evaluate the value stored in that field. For instance, the basic $eq operator matches when the specified field contains a value that is equal to the supplied argument.

    It is important for query performance to use appropriate selectors:

    • Only equality operators such as $eq, $gt, $gte, $lt, and $lte (but not $ne) can be used as the basis of a query. You should include at least one of these in a selector.
    • Some operators such as $not, $or, $in, and $regex cannot be answered from an index. For query selectors use these operators in conjunction with equality operators or create and use a partial index to reduce the number of documents that will need to be scanned.

    See the Cloudant Docsfor a list of all available combination and conditional operators.

    For further reference see selector syntax.

  • Header parameter to specify the ID of the last events received by the server on a previous connection. Overrides since query parameter.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^0|([1-9]\\d*-[A-Za-z0-9-_]+)|now$/

  • Query parameter to specify whether to include the encoding information for compressed attachments. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include attachment content in the response. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include a list of conflicted revisions in each returned document. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to return changes in the descending order with most recent change first. The since parameter has no effect when using descending order.

    Default: false

  • Query parameter to specify the changes feed type.

    Allowable values: [continuous,eventsource,longpoll,normal]

    Default: normal

  • Query parameter to specify a filter to emit only specific events from the changes stream.

    The built-in filter types are:

    • _design - Returns only changes to design documents.
    • _doc_ids - Returns changes for documents with an ID matching one specified in doc_ids request body parameter. (POST only)
    • _selector - Returns changes for documents that match the selector request body parameter. The selector syntax is the same as used for _find. (POST only)
    • _view - Returns changes for documents that match an existing map function in the view specified by the query parameter view.

    Additionally, the value can be the name of a JS filter function from a design document. For example: design_doc/filtername.

    Note: For better performance use the built-in _selector, _design or _doc_ids filters rather than JS based _view or design document filters. If you need to pass values to change the filtered content use the _selector filter type.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^_design|_docs_ids|_selector|_view|.*\/.*$/

  • Query parameter to specify the period in milliseconds after which an empty line is sent in the results. Off by default and only applicable for continuous and eventsource feeds. Overrides any timeout to keep the feed alive indefinitely. May also be true to use a value of 60000.

    Note: Delivery of heartbeats cannot be relied on at specific intervals. If your application runs in an environment where idle network connections may break, heartbeat is not suitable as a keepalive mechanism. Instead, consider one of the following options:

    • Use the timeout parameter with a value that is compatible with your network environment.
    • Switch to scheduled usage of one of the non-continuous changes feed types (normal or longpoll).
    • Use TCP keepalive.

    Possible values: 1 ≤ value ≤ 60000

  • Query parameter to specify whether to include the full content of the documents in the response.

    Default: false

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify that the update seq should only be calculated with every Nth result returned. When fetching changes in a batch, setting seq_interval=<batch size>, where <batch size> is the number of results requested per batch, load can be reduced on the source database as computing the seq value across many shards (especially in highly-sharded databases) is expensive.

    Possible values: 1 ≤ value ≤ 4294967295

  • Query parameter to specify to start the results from the change immediately after the given update sequence. Possible values are:

    • 0 for all available changes (default).
    • now for future changes.
    • A valid update sequence, for example, from the seq value of a change received before.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^0|([1-9]\\d*-[A-Za-z0-9-_]+)|now$/

    Examples:
  • Query parameter to specify how many revisions are returned in the changes array. The default, main_only, will only return the current "winning" revision; all_docs will return all leaf revisions (including conflicts and deleted former conflicts).

    Allowable values: [main_only,all_docs]

    Default: main_only

  • Query parameter to specify the 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. Default value is specified by httpd/changes_timeout configuration option. Note that 60000 value is also the default maximum timeout to prevent undetected dead connections.

    Possible values: 0 ≤ value ≤ 60000

    Default: 60000

  • Query parameter to specify a view function as a filter. Documents pass the filter if the view's map function emits at least one record for them.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^[^_].*$/

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Schema for a list of document IDs.

    Possible values: 0 ≤ number of items ≤ 65535, 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

    Examples:
  • JSON array that uses the field syntax. Use this parameter to specify which fields of a document must be returned. If it is omitted or empty, the entire document is returned.

    Possible values: 0 ≤ number of items ≤ 65535, 1 ≤ length ≤ 7168, Value must match regular expression /^.+$/

  • JSON object describing criteria used to select documents. The selector specifies fields in the document, and provides an expression to evaluate with the field content or other data.

    The selector object must:

    • Be structured as valid JSON.
    • Contain a valid query expression.

    Using a selector is significantly more efficient than using a JavaScript filter function, and is the recommended option if filtering on document attributes only.

    Elementary selector syntax requires you to specify one or more fields, and the corresponding values required for those fields. You can create more complex selector expressions by combining operators.

    Operators are identified by the use of a dollar sign $ prefix in the name field.

    There are two core types of operators in the selector syntax:

    • Combination operators: applied at the topmost level of selection. They are used to combine selectors. A combination operator takes a single argument. The argument is either another selector, or an array of selectors.
    • Condition operators: are specific to a field, and are used to evaluate the value stored in that field. For instance, the basic $eq operator matches when the specified field contains a value that is equal to the supplied argument.

    It is important for query performance to use appropriate selectors:

    • Only equality operators such as $eq, $gt, $gte, $lt, and $lte (but not $ne) can be used as the basis of a query. You should include at least one of these in a selector.
    • Some operators such as $not, $or, $in, and $regex cannot be answered from an index. For query selectors use these operators in conjunction with equality operators or create and use a partial index to reduce the number of documents that will need to be scanned.

    See the Cloudant Docsfor a list of all available combination and conditional operators.

    For further reference see selector syntax.

  • Header parameter to specify the ID of the last events received by the server on a previous connection. Overrides since query parameter.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^0|([1-9]\\d*-[A-Za-z0-9-_]+)|now$/

  • Query parameter to specify whether to include the encoding information for compressed attachments. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include attachment content in the response. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to include a list of conflicted revisions in each returned document. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to return changes in the descending order with most recent change first. The since parameter has no effect when using descending order.

    Default: false

  • Query parameter to specify the changes feed type.

    Allowable values: [continuous,eventsource,longpoll,normal]

    Default: normal

  • Query parameter to specify a filter to emit only specific events from the changes stream.

    The built-in filter types are:

    • _design - Returns only changes to design documents.
    • _doc_ids - Returns changes for documents with an ID matching one specified in doc_ids request body parameter. (POST only)
    • _selector - Returns changes for documents that match the selector request body parameter. The selector syntax is the same as used for _find. (POST only)
    • _view - Returns changes for documents that match an existing map function in the view specified by the query parameter view.

    Additionally, the value can be the name of a JS filter function from a design document. For example: design_doc/filtername.

    Note: For better performance use the built-in _selector, _design or _doc_ids filters rather than JS based _view or design document filters. If you need to pass values to change the filtered content use the _selector filter type.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^_design|_docs_ids|_selector|_view|.*\/.*$/

  • Query parameter to specify the period in milliseconds after which an empty line is sent in the results. Off by default and only applicable for continuous and eventsource feeds. Overrides any timeout to keep the feed alive indefinitely. May also be true to use a value of 60000.

    Note: Delivery of heartbeats cannot be relied on at specific intervals. If your application runs in an environment where idle network connections may break, heartbeat is not suitable as a keepalive mechanism. Instead, consider one of the following options:

    • Use the timeout parameter with a value that is compatible with your network environment.
    • Switch to scheduled usage of one of the non-continuous changes feed types (normal or longpoll).
    • Use TCP keepalive.

    Possible values: 1 ≤ value ≤ 60000

  • Query parameter to specify whether to include the full content of the documents in the response.

    Default: false

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify that the update seq should only be calculated with every Nth result returned. When fetching changes in a batch, setting seq_interval=<batch size>, where <batch size> is the number of results requested per batch, load can be reduced on the source database as computing the seq value across many shards (especially in highly-sharded databases) is expensive.

    Possible values: 1 ≤ value ≤ 4294967295

  • Query parameter to specify to start the results from the change immediately after the given update sequence. Possible values are:

    • 0 for all available changes (default).
    • now for future changes.
    • A valid update sequence, for example, from the seq value of a change received before.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^0|([1-9]\\d*-[A-Za-z0-9-_]+)|now$/

    Examples:
  • Query parameter to specify how many revisions are returned in the changes array. The default, main_only, will only return the current "winning" revision; all_docs will return all leaf revisions (including conflicts and deleted former conflicts).

    Allowable values: [main_only,all_docs]

    Default: main_only

  • Query parameter to specify the 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. Default value is specified by httpd/changes_timeout configuration option. Note that 60000 value is also the default maximum timeout to prevent undetected dead connections.

    Possible values: 0 ≤ value ≤ 60000

    Default: 60000

  • Query parameter to specify a view function as a filter. Documents pass the filter if the view's map function emits at least one record for them.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^[^_].*$/

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X POST "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_changes" -H "Content-Type: application/json" --data '{
     "doc_ids": [
     "small-appliances:1000042"
     ]
    }'
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    postChangesOptions := service.NewPostChangesOptions(
      "orders",
    )
    
    changesResult, response, err := service.PostChanges(postChangesOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(changesResult, "", "  ")
    fmt.Println(string(b))
    
  • import (
      "encoding/json"
      "fmt"
      "io"
      "os"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    postChangesOptions := service.NewPostChangesOptions(
      "orders",
    )
    
    changesResult, response, err := service.PostChangesAsStream(postChangesOptions)
    if err != nil {
      panic(err)
    }
    
    if changesResult != nil {
      defer changesResult.Close()
      outFile, err := os.Create("result.json")
      if err != nil {
        panic(err)
      }
      defer outFile.Close()
      if _, err = io.Copy(outFile, changesResult); err != nil {
        panic(err)
      }
    }
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.ChangesResult;
    import com.ibm.cloud.cloudant.v1.model.PostChangesOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    PostChangesOptions changesOptions = new PostChangesOptions.Builder()
        .db("orders")
        .build();
    
    ChangesResult response =
        service.postChanges(changesOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.PostChangesOptions;
    
    import java.io.InputStream;
    import java.io.File;
    import java.nio.file.StandardCopyOption;
    
    Cloudant service = Cloudant.newInstance();
    
    PostChangesOptions changesOptions = new PostChangesOptions.Builder()
        .db("orders")
        .build();
    
    File file = new File("result.json");
    
    try (InputStream response =
            service.postChangesAsStream(changesOptions).execute()
                .getResult()) {
        java.nio.file.Files.copy(
            response,
            file.toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    }
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.postChanges({
      db: 'orders'
    }).then(response => {
      console.log(response.result);
    });
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.postChangesAsStream({
      db: 'orders'
    }).then(response => {
      let stream = fs.createWriteStream("result.json");
      response.result.pipe(stream);
      response.result.on('end', () => stream.end());
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    response = service.post_changes(
      db='orders'
    ).get_result()
    
    print(response)
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    result = service.post_changes_as_stream(
      db='orders'
    ).get_result()
    
    with open('result.json', 'wb') as f:
      for chunk in result.iter_content():
        f.write(chunk)
    

Response

Response type for PostChanges: ChangesResult

Response type for PostChangesAsStream: io.ReadCloser

Response type for postChanges: ChangesResult

Response type for postChangesAsStream: InputStream

Response type for postChanges: ChangesResult

Response type for postChangesAsStream: NodeJS.ReadableStream

Response type for post_changes: ChangesResult

Response type for post_changes_as_stream: BinaryIO

Schema for normal changes feed result.

Schema for normal changes feed result.

Schema for normal changes feed result.

Schema for normal changes feed result.

Schema for normal changes feed result.

Status Code

  • HTTP response for /{db}/_changes style operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for payload too large.

  • HTTP error for unsupported media type.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example ChangesResult response.

    {
      "last_seq": "7-g1AAAAPveJy1kk9OAjEYxSuYGBO3nsCdC9LOP5yVXkGhB-jXdoKTsSQG1p7CKyj0Ep6CS3AGob5hwYSNMJOwek3T971fXr-KMXYz6Rt2Z0hP3-2ToWygq-ncKDfjXOzPA2dnFR73FKNbKcelYoe2-H9bbZJ07_2ynPTVxRvurjTPhU6i06YcpkVH0hDk6TGEbWtOmAKBddRwUpw-iKE4ByeCxlR6v2jNCdOSPkLY1JxsxykyLlKuDLueO2OLV2dNq6-tx23dJXuR8rMtD2wj2CDfqL5m6u2Ycp1HQ5N26e4ILaIWiIL8hvDTgXcDG-RZylXDm8V5IbLkPLwodgX58n7dgRfFriHYz9DsZpqQtQWdNqn8A1TdTOE",
      "pending": 3,
      "results": [
        {
          "changes": [
            {
              "rev": "7-7a5191bfeb2f6eed6b3b6fa83f4810f5"
            }
          ],
          "deleted": true,
          "id": "0007741142412418284",
          "seq": "1-g1AAAAMFeJydkcENgjAUhquYePHqBN48EEBj4klXUOgAbSExDUJi8OwUrqDQJZyCJZhBqD8XE0Iiwulvmvf1e68vJITMToZPFj4X8SXY-3xjijC--ixKLMv-ns0oSEIUjxnhc0o9yUgTW_3GaojypVKZPBlsdMbdVFhbW6yd_15p2pwOG0SK77SuevcJSHP06rbILicgj0ul0t5OQBm_aV22yI5l1FAVTciR0ntfKzAXGOKJz-prBpYCQ7y1fg1wl8AQB0rzAW4MnCMeShUD3Bi4QGDTGrT8AMkPBk0"
        }
      ]
    }
  • Example ChangesResult response.

    {
      "last_seq": "7-g1AAAAPveJy1kk9OAjEYxSuYGBO3nsCdC9LOP5yVXkGhB-jXdoKTsSQG1p7CKyj0Ep6CS3AGob5hwYSNMJOwek3T971fXr-KMXYz6Rt2Z0hP3-2ToWygq-ncKDfjXOzPA2dnFR73FKNbKcelYoe2-H9bbZJ07_2ynPTVxRvurjTPhU6i06YcpkVH0hDk6TGEbWtOmAKBddRwUpw-iKE4ByeCxlR6v2jNCdOSPkLY1JxsxykyLlKuDLueO2OLV2dNq6-tx23dJXuR8rMtD2wj2CDfqL5m6u2Ycp1HQ5N26e4ILaIWiIL8hvDTgXcDG-RZylXDm8V5IbLkPLwodgX58n7dgRfFriHYz9DsZpqQtQWdNqn8A1TdTOE",
      "pending": 3,
      "results": [
        {
          "changes": [
            {
              "rev": "7-7a5191bfeb2f6eed6b3b6fa83f4810f5"
            }
          ],
          "deleted": true,
          "id": "0007741142412418284",
          "seq": "1-g1AAAAMFeJydkcENgjAUhquYePHqBN48EEBj4klXUOgAbSExDUJi8OwUrqDQJZyCJZhBqD8XE0Iiwulvmvf1e68vJITMToZPFj4X8SXY-3xjijC--ixKLMv-ns0oSEIUjxnhc0o9yUgTW_3GaojypVKZPBlsdMbdVFhbW6yd_15p2pwOG0SK77SuevcJSHP06rbILicgj0ul0t5OQBm_aV22yI5l1FAVTciR0ntfKzAXGOKJz-prBpYCQ7y1fg1wl8AQB0rzAW4MnCMeShUD3Bi4QGDTGrT8AMkPBk0"
        }
      ]
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Create or modify a document in a database

Creates or modifies a document in the specified database by using the supplied JSON document.

For creation, you may specify the document ID but you should not specify the revision. If you don't specify the document ID, then the server generates an ID for your document.

For modification, you must specify the document ID and a revision identifier in the JSON document.

If your document ID includes the _local/ or _design/ prefix, then this operation creates or modifies a local or a design document respectively.

Creates or modifies a document in the specified database by using the supplied JSON document.

For creation, you may specify the document ID but you should not specify the revision. If you don't specify the document ID, then the server generates an ID for your document.

For modification, you must specify the document ID and a revision identifier in the JSON document.

If your document ID includes the _local/ or _design/ prefix, then this operation creates or modifies a local or a design document respectively.

Creates or modifies a document in the specified database by using the supplied JSON document.

For creation, you may specify the document ID but you should not specify the revision. If you don't specify the document ID, then the server generates an ID for your document.

For modification, you must specify the document ID and a revision identifier in the JSON document.

If your document ID includes the _local/ or _design/ prefix, then this operation creates or modifies a local or a design document respectively.

Creates or modifies a document in the specified database by using the supplied JSON document.

For creation, you may specify the document ID but you should not specify the revision. If you don't specify the document ID, then the server generates an ID for your document.

For modification, you must specify the document ID and a revision identifier in the JSON document.

If your document ID includes the _local/ or _design/ prefix, then this operation creates or modifies a local or a design document respectively.

Creates or modifies a document in the specified database by using the supplied JSON document.

For creation, you may specify the document ID but you should not specify the revision. If you don't specify the document ID, then the server generates an ID for your document.

For modification, you must specify the document ID and a revision identifier in the JSON document.

If your document ID includes the _local/ or _design/ prefix, then this operation creates or modifies a local or a design document respectively.

POST /{db}
(cloudant *CloudantV1) PostDocument(postDocumentOptions *PostDocumentOptions) (result *DocumentResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostDocumentWithContext(ctx context.Context, postDocumentOptions *PostDocumentOptions) (result *DocumentResult, response *core.DetailedResponse, err error)
ServiceCall<DocumentResult> postDocument(PostDocumentOptions postDocumentOptions)
postDocument(params)
post_document(
        self,
        db: str,
        document: Union['Document', BinaryIO],
        *,
        content_type: Optional[str] = None,
        batch: Optional[str] = None,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following actions. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.data-document.write

  • cloudantnosqldb.design-document.write

  • cloudantnosqldb.local-document.write

Auditing

Calling this method generates the following auditing events.

  • cloudantnosqldb.data-document.write

  • cloudantnosqldb.design-document.write

  • cloudantnosqldb.local-document.write

Rate limit

This operation consumes one write request.

Request

Instantiate the PostDocumentOptions struct and set the fields to provide parameter values for the PostDocument method.

Use the PostDocumentOptions.Builder to create a PostDocumentOptions object that contains the parameter values for the postDocument method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

  • Allowable values: [application/json,multipart/mixed,multipart/related]

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

Query Parameters

  • Query parameter to specify whether to store in batch mode. The server will respond with a HTTP 202 Accepted response code immediately.

    Allowable values: [ok]

HTTP request body for Document operations.

Examples:

Example Document.

{
  "_id": "exampleid",
  "brand": "Foo",
  "colours": [
    "red",
    "green",
    "black",
    "blue"
  ],
  "description": "Slim Colourful Design Electronic Cooking Appliance for ...",
  "image": "assets/img/0gmsnghhew.jpg",
  "keywords": [
    "Foo",
    "Scales",
    "Weight",
    "Digital",
    "Kitchen"
  ],
  "name": "Digital Kitchen Scales",
  "price": 14.99,
  "productId": "1000042",
  "taxonomy": [
    "Home",
    "Kitchen",
    "Small Appliances"
  ],
  "type": "product"
}

WithContext method only

The PostDocument options.

The postDocument options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • HTTP request body for Document operations.

    Examples:
  • The type of the input.

    Allowable values: [application/json,multipart/mixed,multipart/related,application/octet-stream]

    Default: application/json

  • Query parameter to specify whether to store in batch mode. The server will respond with a HTTP 202 Accepted response code immediately.

    Allowable values: [ok]

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Schema for a document.

  • The type of the input.

    Allowable values: [application/json,multipart/mixed,multipart/related,application/octet-stream]

    Default: application/json

  • Query parameter to specify whether to store in batch mode. The server will respond with a HTTP 202 Accepted response code immediately.

    Allowable values: [ok]

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X POST "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products" -H "Content-Type: application/json" --data '{
      "_id": "small-appliances:1000042",
      "type": "product",
      "productId": "1000042",
      "brand": "Salter",
      "name": "Digital Kitchen Scales",
      "description": "Slim Colourful Design Electronic Cooking Appliance for Home / Kitchen, Weigh up to 5kg + Aquatronic for Liquids ml + fl. oz. 15Yr Guarantee - Green",
      "price: 14.99,
      "image": "assets/img/0gmsnghhew.jpg"
    }'
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
      "github.com/IBM/go-sdk-core/v5/core"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    productsDoc := cloudantv1.Document{
      ID: core.StringPtr("1000042"),
    }
    productsDoc.SetProperty("type", "product")
    productsDoc.SetProperty("productId", "1000042")
    productsDoc.SetProperty("brand", "Salter")
    productsDoc.SetProperty("name", "Digital Kitchen Scales")
    productsDoc.SetProperty("description", "Slim Colourful Design Electronic Cooking Appliance for Home / Kitchen, Weigh up to 5kg + Aquatronic for Liquids ml + fl. oz. 15Yr Guarantee - Green")
    productsDoc.SetProperty("price", 14.99)
    productsDoc.SetProperty("image", "assets/img/0gmsnghhew.jpg")
    
    postDocumentOptions := service.NewPostDocumentOptions(
      "products",
    )
    postDocumentOptions.SetDocument(&productsDoc)
    
    documentResult, response, err := service.PostDocument(postDocumentOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(documentResult, "", "  ")
    fmt.Println(string(b))
    
  • import (
      "encoding/json"
      "fmt"
      "os"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
      "github.com/IBM/go-sdk-core/v5/core"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    productsDocReader, err := os.Open("products_doc.json")
    if err != nil {
      panic(err)
    }
    defer productsDocReader.Close()
    
    postDocumentOptions := service.NewPostDocumentOptions(
      "products",
    )
    postDocumentOptions.SetContentType("application/json")
    postDocumentOptions.SetBody(productsDocReader)
    
    documentResult, response, err := service.PostDocument(postDocumentOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(documentResult, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.Document;
    import com.ibm.cloud.cloudant.v1.model.DocumentResult;
    import com.ibm.cloud.cloudant.v1.model.PostDocumentOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    Document productsDocument = new Document();
    productsDocument.setId("1000042");
    productsDocument.put("type", "product");
    productsDocument.put("productId", "1000042");
    productsDocument.put("brand", "Salter");
    productsDocument.put("name", "Digital Kitchen Scales");
    productsDocument.put("description", "Slim Colourful Design Electronic"
        + "Cooking Appliance for Home / Kitchen, Weigh up to 5kg + Aquatronic"
        + "for Liquids ml + fl. oz. 15Yr Guarantee - Green");
    productsDocument.put("price", 14.99);
    productsDocument.put("image", "assets/img/0gmsnghhew.jpg");
    
    PostDocumentOptions documentOptions =
        new PostDocumentOptions.Builder()
            .db("products")
            .document(productsDocument)
            .build();
    
    DocumentResult response =
        service.postDocument(documentOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import java.io.FileInputStream;
    
    import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.Document;
    import com.ibm.cloud.cloudant.v1.model.DocumentResult;
    import com.ibm.cloud.cloudant.v1.model.PostDocumentOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    try (FileInputStream productsDocumentStream = new FileInputStream("products_doc.json")) {
        PostDocumentOptions documentOptions =
            new PostDocumentOptions.Builder()
                .db("products")
                .contentType("application/json")
                .body(productsDocumentStream)
                .build();
    
        DocumentResult response =
            service.postDocument(documentOptions).execute()
                .getResult();
    
        System.out.println(response);
    }
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    const productsDoc: CloudantV1.Document = {
      _id: '1000042',
      type: 'product',
      productId: '1000042',
      brand: 'Salter',
      name: 'Digital Kitchen Scales',
      description: 'Slim Colourful Design Electronic Cooking Appliance for Home / Kitchen, Weigh up to 5kg + Aquatronic for Liquids ml + fl. oz. 15Yr Guarantee - Green',
      price: 14.99,
      image: 'assets/img/0gmsnghhew.jpg'
    };
    
    service.postDocument({
      db: 'products',
      document: productsDoc
    }).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import Document, CloudantV1
    
    service = CloudantV1.new_instance()
    
    products_doc = Document(
      _id="1000042",
      type="product",
      productId="1000042",
      brand="Salter",
      name="Digital Kitchen Scales",
      description="Slim Colourful Design Electronic Cooking Appliance for Home / Kitchen, Weigh up to 5kg + Aquatronic for Liquids ml + fl. oz. 15Yr Guarantee - Green",
      price=14.99,
      image="assets/img/0gmsnghhew.jpg")
    
    response = service.post_document(db='products', document=products_doc).get_result()
    
    print(response)
    
  • from ibmcloudant.cloudant_v1 import Document, CloudantV1
    
    service = CloudantV1.new_instance()
    
    with open("products_doc.json", "rb") as products_doc:
      response = service.post_document(
          db='products',
          document=products_doc_binary,
          content_type="application/json"
      ).get_result()
    
    print(response)
    

Response

Schema for the result of a document modification.

Schema for the result of a document modification.

Schema for the result of a document modification.

Schema for the result of a document modification.

Schema for the result of a document modification.

Status Code

  • HTTP response for Document modification operations.

  • HTTP response for Document modification operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for exceeded data usage quota.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for conflict.

  • HTTP error for gone.

  • HTTP error for payload too large.

  • HTTP error for unsupported media type.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example DocumentResult for a creation.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for a creation.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for a deletion.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "3-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for a deletion.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "3-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for an update.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-9c65296036141e575d32ba9c034dd3ee"
    }
  • Example DocumentResult for an update.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-9c65296036141e575d32ba9c034dd3ee"
    }
  • Example DocumentResult for a creation.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for a creation.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for a deletion.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "3-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for a deletion.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "3-056f5f44046ecafc08a2bc2b9c229e20"
    }
  • Example DocumentResult for an update.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-9c65296036141e575d32ba9c034dd3ee"
    }
  • Example DocumentResult for an update.

    {
      "id": "exampleid",
      "ok": true,
      "rev": "2-9c65296036141e575d32ba9c034dd3ee"
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for writer or creator access is required.

    {
      "error": "unauthorized",
      "reason": "one of _writer, _creator is required for this request."
    }
  • Example error response for writer or creator access is required.

    {
      "error": "unauthorized",
      "reason": "one of _writer, _creator is required for this request."
    }
  • Example error response when the data quota of the plan is exceeded.

    {
      "error": "over_data_quota",
      "reason": "Account has exceeded its data usage quota. An upgrade to a paid plan is required."
    }
  • Example error response when the data quota of the plan is exceeded.

    {
      "error": "over_data_quota",
      "reason": "Account has exceeded its data usage quota. An upgrade to a paid plan is required."
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for a document update conflict.

    {
      "error": "conflict",
      "reason": "Document update conflict."
    }
  • Example error response for a document update conflict.

    {
      "error": "conflict",
      "reason": "Document update conflict."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for a request with a document size that exceeds the allowable limit.

    {
      "error": "document_too_large",
      "reason": "doc_id"
    }
  • Example error response for a request with a document size that exceeds the allowable limit.

    {
      "error": "document_too_large",
      "reason": "doc_id"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Query a list of all documents in a database (GET)

Queries the primary index (all document IDs). The results that match the query parameters are returned in a JSON object, including a list of matching documents with basic contents, such as the ID and revision. When no query parameters are specified, results for all documents in the database are returned. Optionally, document content or additional metadata can be included in the response.

GET /{db}/_all_docs

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.any-document.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.any-document.read

Rate limit

This operation consumes one global query request.

Request

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

Query Parameters

  • Query parameter to specify whether to include a list of conflicted revisions in each returned document. Note that when used with a view-style query or changes feed this only applies when requesting documents in the response.

    Default: false

  • Query parameter to specify whether to return rows in descending by key order.

    Default: false

  • Query parameter to specify to stop returning records when the specified key is reached. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Query parameter to stop returning rows at the specified document ID. No effect if using group or not providing end key.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^[^_].*$

  • Query parameter to specify whether to include the full content of the documents in the response.

    Default: false

  • Query parameter to specify whether the specified end key should be included in the result.

    Default: true

  • Query parameter to specify to return only rows that match the specified key. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Query parameter to specify returning only rows that match any of the specified keys. String representation of a JSON array of keys that match the key type emitted by the view function. Must be URL encoded.

    Possible values: 2 ≤ length ≤ 7168, Value must match regular expression ^\[(".*")*\]$

  • Query parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

  • Query parameter to specify the number of records before starting to return the results.

    Possible values: 0 ≤ value ≤ 9007199254740991

    Default: 0

  • Query parameter to specify to start returning records from the specified key. String representation of any JSON type that matches the key type emitted by the view function.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^.+$

  • Query parameter to start returning rows at the specified document ID. No effect if using group or not providing start key.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression ^[^_].*$

  • Query parameter to specify whether to include in the response an update_seq value indicating the sequence id of the database the view reflects.

    Default: false

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X GET "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_all_docs"
    

Response

Schema for the result of an all documents operation.

Status Code

  • HTTP response for getAllDocs and postAllDocs.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example AllDocsResult response.

    {
      "offset": 0,
      "rows": [
        {
          "doc": {
            "_id": "exampleid",
            "_rev": "1-967a00dff5e02add41819138abb3284d"
          },
          "id": "exampleid",
          "key": "exampleid",
          "value": {
            "rev": "1-967a00dff5e02add41819138abb3284d"
          }
        }
      ],
      "total_rows": 1
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Query a list of all documents in a database

Queries the primary index (all document IDs). The results that match the request body parameters are returned in a JSON object, including a list of matching documents with basic contents, such as the ID and revision. When no request body parameters are specified, results for all documents in the database are returned. Optionally, document content or additional metadata can be included in the response.

Queries the primary index (all document IDs). The results that match the request body parameters are returned in a JSON object, including a list of matching documents with basic contents, such as the ID and revision. When no request body parameters are specified, results for all documents in the database are returned. Optionally, document content or additional metadata can be included in the response.

Queries the primary index (all document IDs). The results that match the request body parameters are returned in a JSON object, including a list of matching documents with basic contents, such as the ID and revision. When no request body parameters are specified, results for all documents in the database are returned. Optionally, document content or additional metadata can be included in the response.

Queries the primary index (all document IDs). The results that match the request body parameters are returned in a JSON object, including a list of matching documents with basic contents, such as the ID and revision. When no request body parameters are specified, results for all documents in the database are returned. Optionally, document content or additional metadata can be included in the response.

Queries the primary index (all document IDs). The results that match the request body parameters are returned in a JSON object, including a list of matching documents with basic contents, such as the ID and revision. When no request body parameters are specified, results for all documents in the database are returned. Optionally, document content or additional metadata can be included in the response.

POST /{db}/_all_docs
(cloudant *CloudantV1) PostAllDocs(postAllDocsOptions *PostAllDocsOptions) (result *AllDocsResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostAllDocsWithContext(ctx context.Context, postAllDocsOptions *PostAllDocsOptions) (result *AllDocsResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostAllDocsAsStream(postAllDocsOptions *PostAllDocsOptions) (result io.ReadCloser, response *core.DetailedResponse, err error)
ServiceCall<AllDocsResult> postAllDocs(PostAllDocsOptions postAllDocsOptions)
ServiceCall<InputStream> postAllDocsAsStream(PostAllDocsOptions postAllDocsOptions)
postAllDocs(params)
postAllDocsAsStream(params)
post_all_docs(
        self,
        db: str,
        *,
        att_encoding_info: Optional[bool] = None,
        attachments: Optional[bool] = None,
        conflicts: Optional[bool] = None,
        descending: Optional[bool] = None,
        include_docs: Optional[bool] = None,
        inclusive_end: Optional[bool] = None,
        limit: Optional[int] = None,
        skip: Optional[int] = None,
        update_seq: Optional[bool] = None,
        end_key: Optional[str] = None,
        key: Optional[str] = None,
        keys: Optional[List[str]] = None,
        start_key: Optional[str] = None,
        **kwargs,
    ) -> DetailedResponse
post_all_docs_as_stream(
        self,
        db: str,
        *,
        att_encoding_info: Optional[bool] = None,
        attachments: Optional[bool] = None,
        conflicts: Optional[bool] = None,
        descending: Optional[bool] = None,
        include_docs: Optional[bool] = None,
        inclusive_end: Optional[bool] = None,
        limit: Optional[int] = None,
        skip: Optional[int] = None,
        update_seq: Optional[bool] = None,
        end_key: Optional[str] = None,
        key: Optional[str] = None,
        keys: Optional[List[str]] = None,
        start_key: Optional[str] = None,
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.any-document.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.any-document.read

Rate limit

This operation consumes one global query request.

Request

Instantiate the PostAllDocsOptions struct and set the fields to provide parameter values for the PostAllDocs method.

Use the PostAllDocsOptions.Builder to create a PostAllDocsOptions object that contains the parameter values for the postAllDocs method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

HTTP request body for postAllDocs and postPartitionAllDocs.

Examples:

Example AllDocs request.

{
  "limit": 10,
  "start_key": "0007741142412418284"
}

WithContext method only

The PostAllDocs options.

The postAllDocs options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Parameter to specify whether to include the encoding information for compressed attachments. This only applies when requesting documents in the response.

    Default: false

  • Parameter to specify whether to include attachment content in included document content or only the attachment metadata. This only applies when requesting documents in the response.

    Default: false

  • Parameter to specify whether to include a list of conflicted revisions in each returned document. This only applies when requesting documents in the response.

    Default: false

  • Parameter to specify whether to return the documents in descending by key order.

    Default: false

  • Parameter to specify whether to include the full content of the documents in the response.

    Default: false

  • Parameter to specify whether to include the specified end key in the result.

    Default: true

  • Parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

    Examples:
  • Parameter to specify the number of records before starting to return the results.

    Possible values: 0 ≤ value ≤ 9007199254740991

    Default: 0

  • Parameter to specify whether to include in the response an update_seq value indicating the sequence id of the database the view reflects.

    Default: false

  • Schema for a document ID.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

  • Schema for a document ID.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

  • Schema for a list of document IDs.

    Possible values: 0 ≤ number of items ≤ 65535, 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

  • Schema for a document ID.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

    Examples:

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Parameter to specify whether to include the encoding information for compressed attachments. This only applies when requesting documents in the response.

    Default: false

  • Parameter to specify whether to include attachment content in included document content or only the attachment metadata. This only applies when requesting documents in the response.

    Default: false

  • Parameter to specify whether to include a list of conflicted revisions in each returned document. This only applies when requesting documents in the response.

    Default: false

  • Parameter to specify whether to return the documents in descending by key order.

    Default: false

  • Parameter to specify whether to include the full content of the documents in the response.

    Default: false

  • Parameter to specify whether to include the specified end key in the result.

    Default: true

  • Parameter to specify the number of returned documents to limit the result to.

    Possible values: 0 ≤ value ≤ 4294967295

    Examples:
  • Parameter to specify the number of records before starting to return the results.

    Possible values: 0 ≤ value ≤ 9007199254740991

    Default: 0

  • Parameter to specify whether to include in the response an update_seq value indicating the sequence id of the database the view reflects.

    Default: false

  • Schema for a document ID.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

  • Schema for a document ID.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

  • Schema for a list of document IDs.

    Possible values: 0 ≤ number of items ≤ 65535, 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

  • Schema for a document ID.

    Possible values: 1 ≤ length ≤ 7168, Value must match regular expression /^([^_]|_(design|local)\/).+$/

    Examples:
  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X POST "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/orders/_all_docs" -H "Content-Type: application/json" --data '{
      "include_docs": true,
      "startkey": "abc",
      "limit": 10
    }'
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    postAllDocsOptions := service.NewPostAllDocsOptions(
      "orders",
    )
    postAllDocsOptions.SetIncludeDocs(true)
    postAllDocsOptions.SetStartKey("abc")
    postAllDocsOptions.SetLimit(10)
    
    allDocsResult, response, err := service.PostAllDocs(postAllDocsOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(allDocsResult, "", "  ")
    fmt.Println(string(b))
    
  • import (
      "encoding/json"
      "fmt"
      "io"
      "os"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    postAllDocsOptions := service.NewPostAllDocsOptions(
      "orders",
    )
    postAllDocsOptions.SetIncludeDocs(true)
    postAllDocsOptions.SetStartKey("abc")
    postAllDocsOptions.SetLimit(10)
    
    allDocsResult, response, err := service.PostAllDocsAsStream(postAllDocsOptions)
    if err != nil {
        panic(err)
    }
    
    if allDocsResult != nil {
      defer allDocsResult.Close()
      outFile, err := os.Create("result.json")
      if err != nil {
        panic(err)
      }
      defer outFile.Close()
      if _, err = io.Copy(outFile, allDocsResult); err != nil {
        panic(err)
      }
    }
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.AllDocsResult;
    import com.ibm.cloud.cloudant.v1.model.PostAllDocsOptions;
    
    Cloudant service = Cloudant.newInstance();
    
    PostAllDocsOptions docsOptions =
        new PostAllDocsOptions.Builder()
            .db("orders")
            .includeDocs(true)
            .startKey("abc")
            .limit(10)
            .build();
    
    AllDocsResult response =
        service.postAllDocs(docsOptions).execute().getResult();
    
    System.out.println(response);
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.PostAllDocsOptions;
    
    import java.io.InputStream;
    import java.io.File;
    import java.nio.file.StandardCopyOption;
    
    Cloudant service = Cloudant.newInstance();
    
    PostAllDocsOptions docsOptions =
        new PostAllDocsOptions.Builder()
            .db("orders")
            .includeDocs(true)
            .startKey("abc")
            .limit(10)
            .build();
    
    File file = new File("result.json");
    
    try (InputStream response =
            service.postAllDocsAsStream(docsOptions).execute()
                .getResult()) {
        java.nio.file.Files.copy(
            response,
            file.toPath(),
            StandardCopyOption.REPLACE_EXISTING);
    }
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.postAllDocs({
      db: 'orders',
      includeDocs: true,
      startKey: 'abc',
      limit: 10
    }).then(response => {
      console.log(response.result);
    });
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    service.postAllDocsAsStream({
      db: 'orders',
      includeDocs: true,
      startKey: 'abc',
      limit: 10
    }).then(response => {
      let stream = fs.createWriteStream("result.json");
      response.result.pipe(stream);
      response.result.on('end', () => stream.end());
    });
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    response = service.post_all_docs(
      db='orders',
      include_docs=True,
      start_key='abc',
      limit=10
    ).get_result()
    
    print(response)
    
  • from ibmcloudant.cloudant_v1 import CloudantV1
    
    service = CloudantV1.new_instance()
    
    result = service.post_all_docs_as_stream(
      db='orders',
      include_docs=True,
      start_key='abc',
      limit=10
    ).get_result()
    
    with open('result.json', 'wb') as f:
      for chunk in result.iter_content():
        f.write(chunk)
    

Response

Response type for PostAllDocs: AllDocsResult

Response type for PostAllDocsAsStream: io.ReadCloser

Response type for postAllDocs: AllDocsResult

Response type for postAllDocsAsStream: InputStream

Response type for postAllDocs: AllDocsResult

Response type for postAllDocsAsStream: NodeJS.ReadableStream

Response type for post_all_docs: AllDocsResult

Response type for post_all_docs_as_stream: BinaryIO

Schema for the result of an all documents operation.

Schema for the result of an all documents operation.

Schema for the result of an all documents operation.

Schema for the result of an all documents operation.

Schema for the result of an all documents operation.

Status Code

  • HTTP response for getAllDocs and postAllDocs.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for payload too large.

  • HTTP error for unsupported media type.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example AllDocsResult response.

    {
      "offset": 0,
      "rows": [
        {
          "doc": {
            "_id": "exampleid",
            "_rev": "1-967a00dff5e02add41819138abb3284d"
          },
          "id": "exampleid",
          "key": "exampleid",
          "value": {
            "rev": "1-967a00dff5e02add41819138abb3284d"
          }
        }
      ],
      "total_rows": 1
    }
  • Example AllDocsResult response.

    {
      "offset": 0,
      "rows": [
        {
          "doc": {
            "_id": "exampleid",
            "_rev": "1-967a00dff5e02add41819138abb3284d"
          },
          "id": "exampleid",
          "key": "exampleid",
          "value": {
            "rev": "1-967a00dff5e02add41819138abb3284d"
          }
        }
      ],
      "total_rows": 1
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Multi-query the list of all documents in a database

Runs multiple queries using the primary index (all document IDs). Returns a JSON object that contains a list of result objects, one for each query, with a structure equivalent to that of a single _all_docs request. This enables you to request multiple queries in a single request, in place of multiple POST /{db}/_all_docs requests.

Runs multiple queries using the primary index (all document IDs). Returns a JSON object that contains a list of result objects, one for each query, with a structure equivalent to that of a single _all_docs request. This enables you to request multiple queries in a single request, in place of multiple POST /{db}/_all_docs requests.

Runs multiple queries using the primary index (all document IDs). Returns a JSON object that contains a list of result objects, one for each query, with a structure equivalent to that of a single _all_docs request. This enables you to request multiple queries in a single request, in place of multiple POST /{db}/_all_docs requests.

Runs multiple queries using the primary index (all document IDs). Returns a JSON object that contains a list of result objects, one for each query, with a structure equivalent to that of a single _all_docs request. This enables you to request multiple queries in a single request, in place of multiple POST /{db}/_all_docs requests.

Runs multiple queries using the primary index (all document IDs). Returns a JSON object that contains a list of result objects, one for each query, with a structure equivalent to that of a single _all_docs request. This enables you to request multiple queries in a single request, in place of multiple POST /{db}/_all_docs requests.

POST /{db}/_all_docs/queries
(cloudant *CloudantV1) PostAllDocsQueries(postAllDocsQueriesOptions *PostAllDocsQueriesOptions) (result *AllDocsQueriesResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostAllDocsQueriesWithContext(ctx context.Context, postAllDocsQueriesOptions *PostAllDocsQueriesOptions) (result *AllDocsQueriesResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostAllDocsQueriesAsStream(postAllDocsQueriesOptions *PostAllDocsQueriesOptions) (result io.ReadCloser, response *core.DetailedResponse, err error)
ServiceCall<AllDocsQueriesResult> postAllDocsQueries(PostAllDocsQueriesOptions postAllDocsQueriesOptions)
ServiceCall<InputStream> postAllDocsQueriesAsStream(PostAllDocsQueriesOptions postAllDocsQueriesOptions)
postAllDocsQueries(params)
postAllDocsQueriesAsStream(params)
post_all_docs_queries(
        self,
        db: str,
        queries: List['AllDocsQuery'],
        **kwargs,
    ) -> DetailedResponse
post_all_docs_queries_as_stream(
        self,
        db: str,
        queries: List['AllDocsQuery'],
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following action. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.any-document.read

Auditing

Calling this method generates the following auditing event.

  • cloudantnosqldb.any-document.read

Rate limit

This operation consumes one global query per query in the request.

Request

Instantiate the PostAllDocsQueriesOptions struct and set the fields to provide parameter values for the PostAllDocsQueries method.

Use the PostAllDocsQueriesOptions.Builder to create a PostAllDocsQueriesOptions object that contains the parameter values for the postAllDocsQueries method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

HTTP request body for allDocsQueriesQuery, designDocsQueriesQuery and localDocsQueriesQuery.

Examples:

Example AllDocsQueriesQuery request.

{
  "queries": [
    {
      "keys": [
        "small-appliances:1000042",
        "small-appliances:1000043"
      ]
    },
    {
      "limit": 3,
      "skip": 2
    }
  ]
}

WithContext method only

The PostAllDocsQueries options.

The postAllDocsQueries options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • An array of query objects with fields for the parameters of each individual view query to be executed. The field names and their meaning are the same as the query parameters of a regular /_all_docs request.

    Possible values: 1 ≤ number of items ≤ 65535

    Examples:

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • An array of query objects with fields for the parameters of each individual view query to be executed. The field names and their meaning are the same as the query parameters of a regular /_all_docs request.

    Possible values: 1 ≤ number of items ≤ 65535

    Examples:
  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X POST "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/products/_all_docs/queries" -H "Content-Type: application/json" --data '{
      "queries": [
        {
          "keys": [
            "small-appliances:1000042",
            "small-appliances:1000043"
          ]
        },
        {
          "limit": 3,
          "skip": 2
        }
      ]
    }'
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
      "github.com/IBM/go-sdk-core/v5/core"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    allDocsQueries := []cloudantv1.AllDocsQuery{
      {
        Keys: []string{
          "1000042",
          "1000043",
        },
      },
      {
        Limit: core.Int64Ptr(3),
        Skip:  core.Int64Ptr(2),
      },
    }
    postAllDocsQueriesOptions := service.NewPostAllDocsQueriesOptions(
      "products",
      allDocsQueries,
    )
    
    allDocsQueriesResult, response, err := service.PostAllDocsQueries(postAllDocsQueriesOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(allDocsQueriesResult, "", "  ")
    fmt.Println(string(b))
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.AllDocsQuery;
    import com.ibm.cloud.cloudant.v1.model.AllDocsQueriesResult;
    import com.ibm.cloud.cloudant.v1.model.PostAllDocsQueriesOptions;
    
    import java.util.Arrays;
    
    Cloudant service = Cloudant.newInstance();
    
    AllDocsQuery query1 = new AllDocsQuery.Builder()
        .keys(Arrays.asList("1000042",
            "1000043"))
        .build();
    
    AllDocsQuery query2 = new AllDocsQuery.Builder()
        .limit(3)
        .skip(2)
        .build();
    
    PostAllDocsQueriesOptions queriesOptions =
        new PostAllDocsQueriesOptions.Builder()
            .queries(Arrays.asList(query1, query2))
            .db("products")
            .build();
    
    AllDocsQueriesResult response =
        service.postAllDocsQueries(queriesOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import { CloudantV1 } from '@ibm-cloud/cloudant';
    
    const service = CloudantV1.newInstance({});
    
    const allDocsQueries: CloudantV1.AllDocsQuery[] = [{
        keys: ['1000042', '1000043'],
      },
      {
        limit: 3,
        skip: 2
    }];
    
    service.postAllDocsQueries({
      db: 'products',
      queries: allDocsQueries
    }).then(response => {
      console.log(response.result);
    });
    
  • from ibmcloudant.cloudant_v1 import AllDocsQuery, CloudantV1
    
    service = CloudantV1.new_instance()
    
    all_docs_query1 = AllDocsQuery(
      keys=['1000042', '1000043']
    )
    
    all_docs_query2 = AllDocsQuery(
      limit=3,
      skip=2
    )
    
    response = service.post_all_docs_queries(
      db='products',
      queries=[all_docs_query1, all_docs_query2]
    ).get_result()
    
    print(response)
    

Response

Response type for PostAllDocsQueries: AllDocsQueriesResult

Response type for PostAllDocsQueriesAsStream: io.ReadCloser

Response type for postAllDocsQueries: AllDocsQueriesResult

Response type for postAllDocsQueriesAsStream: InputStream

Response type for postAllDocsQueries: AllDocsQueriesResult

Response type for postAllDocsQueriesAsStream: NodeJS.ReadableStream

Response type for post_all_docs_queries: AllDocsQueriesResult

Response type for post_all_docs_queries_as_stream: BinaryIO

Schema for the result of an all documents queries operation.

Schema for the result of an all documents queries operation.

Schema for the result of an all documents queries operation.

Schema for the result of an all documents queries operation.

Schema for the result of an all documents queries operation.

Status Code

  • HTTP response for /_all_docs/queries style operations.

  • HTTP error for bad request.

  • HTTP error for unauthorized.

  • HTTP error for payment required.

  • HTTP error for forbidden.

  • HTTP error for not found.

  • HTTP error for timeout reading client request.

  • HTTP error for gone.

  • HTTP error for payload too large.

  • HTTP error for unsupported media type.

  • HTTP error for too many requests.

  • HTTP error for internal server error.

  • HTTP error for bad gateway.

  • HTTP error for service unavailable.

  • HTTP error for gateway timeout.

Example responses
  • Example AllDocsQueriesResult response.

    {
      "results": [
        {
          "offset": 0,
          "rows": [
            {
              "id": "exampleid",
              "key": "exampleid",
              "value": {
                "rev": "1-5005d65514fe9e90f8eccf174af5dd64"
              }
            },
            {
              "id": "exampleid2",
              "key": "exampleid2",
              "value": {
                "rev": "1-2d7810b054babeda4812b3924428d6d6"
              }
            }
          ],
          "total_rows": 5
        },
        {
          "offset": 2,
          "rows": [
            {
              "id": "exampleid3",
              "key": "exampleid3",
              "value": {
                "rev": "1-5005d65514fe9e90f8eccf174af5dd64"
              }
            },
            {
              "id": "exampleid4",
              "key": "exampleid4",
              "value": {
                "rev": "1-2d7810b054babeda4812b3924428d6d6"
              }
            }
          ],
          "total_rows": 5
        }
      ]
    }
  • Example AllDocsQueriesResult response.

    {
      "results": [
        {
          "offset": 0,
          "rows": [
            {
              "id": "exampleid",
              "key": "exampleid",
              "value": {
                "rev": "1-5005d65514fe9e90f8eccf174af5dd64"
              }
            },
            {
              "id": "exampleid2",
              "key": "exampleid2",
              "value": {
                "rev": "1-2d7810b054babeda4812b3924428d6d6"
              }
            }
          ],
          "total_rows": 5
        },
        {
          "offset": 2,
          "rows": [
            {
              "id": "exampleid3",
              "key": "exampleid3",
              "value": {
                "rev": "1-5005d65514fe9e90f8eccf174af5dd64"
              }
            },
            {
              "id": "exampleid4",
              "key": "exampleid4",
              "value": {
                "rev": "1-2d7810b054babeda4812b3924428d6d6"
              }
            }
          ],
          "total_rows": 5
        }
      ]
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for a bad request.

    {
      "error": "bad_request",
      "reason": "Bad request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for reader access is required for this request.

    {
      "error": "unauthorized",
      "reason": "_reader access is required for this request."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response for incorrect credentials.

    {
      "error": "unauthorized",
      "reason": "Name or password is incorrect."
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response when payment is required. For example, if the data quota of the plan is exceeded.

    {
      "error": "payment_required",
      "reason": "Payment required"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for a forbidden request.

    {
      "error": "forbidden",
      "reason": "server_admin access is required for this request"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for an account temporarily locked out.

    {
      "error": "forbidden",
      "reason": "Account is temporarily locked due to multiple authentication failures"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for a not found request.

    {
      "error": "not_found",
      "reason": "missing"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for timeout reading client request.

    {
      "error": "request_timeout",
      "reason": "Request timeout"
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for gone.

    {
      "error": "gone",
      "reason": "The requested resource is no longer located here, verify your DNS settings."
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for a request size that exceeds the limit.

    {
      "error": "too_large",
      "reason": "the request entity is too large"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for unsupported media type.

    {
      "error": "bad_content_type",
      "reason": "Content-Type must be application/json"
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for too many requests.

    {
      "error": "too_many_requests",
      "reason": "You've exceeded your rate limit allowance. Please try again later."
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for an unknown server error.

    {
      "error": "unknown_error",
      "reason": "function_clause",
      "ref": 2632214382
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for bad gateway.

    {
      "error": "bad_gateway",
      "reason": "Bad gateway"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for service unavailable.

    {
      "error": "service_unavailable",
      "reason": "Service unavailable"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }
  • Example error response for gateway timeout.

    {
      "error": "gateway_timeout",
      "reason": "Gateway timeout"
    }

Bulk modify multiple documents in a database

The bulk document API allows you to create, update, and delete multiple documents at the same time within a single request. The basic operation is similar to creating, updating, or deleting a single document, except that you batch the document structure and information.

The bulk document API allows you to create, update, and delete multiple documents at the same time within a single request. The basic operation is similar to creating, updating, or deleting a single document, except that you batch the document structure and information.

The bulk document API allows you to create, update, and delete multiple documents at the same time within a single request. The basic operation is similar to creating, updating, or deleting a single document, except that you batch the document structure and information.

The bulk document API allows you to create, update, and delete multiple documents at the same time within a single request. The basic operation is similar to creating, updating, or deleting a single document, except that you batch the document structure and information.

The bulk document API allows you to create, update, and delete multiple documents at the same time within a single request. The basic operation is similar to creating, updating, or deleting a single document, except that you batch the document structure and information.

POST /{db}/_bulk_docs
(cloudant *CloudantV1) PostBulkDocs(postBulkDocsOptions *PostBulkDocsOptions) (result []DocumentResult, response *core.DetailedResponse, err error)
(cloudant *CloudantV1) PostBulkDocsWithContext(ctx context.Context, postBulkDocsOptions *PostBulkDocsOptions) (result []DocumentResult, response *core.DetailedResponse, err error)
ServiceCall<List<DocumentResult>> postBulkDocs(PostBulkDocsOptions postBulkDocsOptions)
postBulkDocs(params)
post_bulk_docs(
        self,
        db: str,
        bulk_docs: Union['BulkDocs', BinaryIO],
        **kwargs,
    ) -> DetailedResponse

Authorization

To call this method, you must be assigned one or more IAM access roles that include the following actions. You can check your access by going to Users > User > Access.

  • cloudantnosqldb.data-document.write

  • cloudantnosqldb.design-document.write

  • cloudantnosqldb.local-document.write

Auditing

Calling this method generates the following auditing events.

  • cloudantnosqldb.data-document.write

  • cloudantnosqldb.design-document.write

  • cloudantnosqldb.local-document.write

Rate limit

This operation consumes one write request per document revision.

Request

Instantiate the PostBulkDocsOptions struct and set the fields to provide parameter values for the PostBulkDocs method.

Use the PostBulkDocsOptions.Builder to create a PostBulkDocsOptions object that contains the parameter values for the postBulkDocs method.

Custom Headers

  • Set a unique identifier to trace a request.

    Possible values: length = 36, Value must match regular expression ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$

Path Parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression ^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+/-]*$

HTTP request body for postBulkDocs.

Examples:

Example BulkDocs request: create and update documents

{
  "docs": [
    {
      "_id": "0007241142412418284",
      "date": "2019-01-28T10:44:22.000Z",
      "eventType": "addedToBasket",
      "productId": "1000042",
      "type": "event",
      "userid": "abc123"
    },
    {
      "_id": "0008001142412418285",
      "date": "2019-01-28T12:30:00.000Z",
      "eventType": "addedToBasket",
      "productId": "1000043",
      "type": "event",
      "userid": "def456"
    }
  ]
}

Example BulkDocs request: delete documents

{
  "docs": [
    {
      "_deleted": true,
      "_id": "0007241142412418284",
      "_rev": "1-5005d65514fe9e90f8eccf174af5dd64"
    },
    {
      "_deleted": true,
      "_id": "0008001142412418285",
      "_rev": "1-2d7810b054babeda4812b3924428d6d6"
    }
  ]
}

WithContext method only

The PostBulkDocs options.

The postBulkDocs options.

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • HTTP request body for postBulkDocs.

    Examples:

parameters

  • Path parameter to specify the database name.

    Possible values: 1 ≤ length ≤ 238, Value must match regular expression /^_dbs$|^_global_changes$|^_metadata$|^_nodes$|^_replicator$|^_users$|^[a-z][a-z0-9_$()+\/-]*$/

  • Schema for submitting documents for bulk modifications.

  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X POST "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/events/_bulk_docs" -H "Content-Type: application/json" --data '{
      "docs": [
        {
          "_id": "0007241142412418284",
          "type": "event",
          "userid": "abc123",
          "eventType": "addedToBasket",
          "productId": "1000042",
          "date": "2019-01-28T10:44:22.000Z"
        },
        {
          "_id": "0008001142412418285",
          "type": "event",
          "userid": "def456",
          "eventType": "addedToBasket",
          "productId": "1000043",
          "date": "2019-01-28T12:30:00.000Z"
        }
      ]
    }'
    
  • curl -H "Authorization: Bearer A1b2C3QiOiIyMDE4MDgxNDAwMDAwMDAwMDAwMDBjNzYwNzY2YjYxYjYwYjYwIiwidHlwIjoiSldUIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJ1c2VyQGdtYWlsLmNvbSIsImF1ZCI6Imh0dHBzOi8vaWF1LmNsb3VkLmlibS5jb20iLCJpYXQiOjE2ODg4ODg4ODgsImV4cCI6MTY4ODg5MjQ4OCwiaXNzIjoiaHR0cHM6Ly9pYXUuY2xvdWQuaWJtLmNvbSIsInNjb3BlIjpbImNsb3VkLnJlYWRlciJdfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" -X POST "https://~replace-with-cloudant-host~.cloudantnosqldb.appdomain.cloud/events/_bulk_docs" -H "Content-Type: application/json" --data '{
      "docs": [
        {
          "_id": "0007241142412418284",
          "_rev": "1-00000000000000000000000000000000",
          "_deleted": true
        },
        {
          "_id": "0007241142412418285",
          "_rev": "1-00000000000000000000000000000000",
          "_deleted": true
        }
      ]
    }'
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
      "github.com/IBM/go-sdk-core/v5/core"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    eventDoc1 := cloudantv1.Document{
      ID: core.StringPtr("ns1HJS13AMkK:0007241142412418284"),
    }
    eventDoc1.SetProperty("type", "event")
    eventDoc1.SetProperty("userId", "abc123")
    eventDoc1.SetProperty("eventType", "addedToBasket")
    eventDoc1.SetProperty("productId", "1000042")
    eventDoc1.SetProperty("date", "2019-01-28T10:44:22.000Z")
    
    eventDoc2 := cloudantv1.Document{
      ID: core.StringPtr("H8tDIwfadxp9:0007241142412418285"),
    }
    eventDoc2.SetProperty("type", "event")
    eventDoc2.SetProperty("userId", "abc234")
    eventDoc2.SetProperty("eventType", "addedToBasket")
    eventDoc2.SetProperty("productId", "1000050")
    eventDoc2.SetProperty("date", "2019-01-25T20:00:00.000Z")
    
    postBulkDocsOptions := service.NewPostBulkDocsOptions(
      "events",
    )
    bulkDocs, err := service.NewBulkDocs(
      []cloudantv1.Document{
        eventDoc1,
        eventDoc2,
      },
    )
    if err != nil {
      panic(err)
    }
    
    postBulkDocsOptions.SetBulkDocs(bulkDocs)
    
    documentResult, response, err := service.PostBulkDocs(postBulkDocsOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(documentResult, "", "  ")
    fmt.Println(string(b))
    
  • import (
      "encoding/json"
      "fmt"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
      "github.com/IBM/go-sdk-core/v5/core"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    eventDoc1 := cloudantv1.Document{
      ID: core.StringPtr("ns1HJS13AMkK:0007241142412418284"),
    }
    eventDoc1.Rev = core.StringPtr("1-00000000000000000000000000000000")
    eventDoc1.Deleted = core.BoolPtr(true)
    
    eventDoc2 := cloudantv1.Document{
      ID: core.StringPtr("H8tDIwfadxp9:0007241142412418285"),
    }
    eventDoc2.Rev = core.StringPtr("1-00000000000000000000000000000000")
    eventDoc2.Deleted = core.BoolPtr(true)
    
    postBulkDocsOptions := service.NewPostBulkDocsOptions(
      "events",
    )
    bulkDocs, err := service.NewBulkDocs(
      []cloudantv1.Document{
        eventDoc1,
        eventDoc2,
      },
    )
    if err != nil {
      panic(err)
    }
    
    postBulkDocsOptions.SetBulkDocs(bulkDocs)
    
    documentResult, response, err := service.PostBulkDocs(postBulkDocsOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(documentResult, "", "  ")
    fmt.Println(string(b))
    
  • import (
      "encoding/json"
      "fmt"
      "os"
    
      "github.com/IBM/cloudant-go-sdk/cloudantv1"
    )
    
    service, err := cloudantv1.NewCloudantV1(
      &cloudantv1.CloudantV1Options{},
    )
    if err != nil {
      panic(err)
    }
    
    file, err := os.Open("upload.json")
    if err != nil {
      panic(err)
    }
    
    postBulkDocsOptions := service.NewPostBulkDocsOptions(
      "events",
    )
    
    postBulkDocsOptions.SetBody(file)
    
    documentResult, response, err := service.PostBulkDocs(postBulkDocsOptions)
    if err != nil {
      panic(err)
    }
    
    b, _ := json.MarshalIndent(documentResult, "", "  ")
    fmt.Println(string(b))
    

    Content of upload.json

    {
      "docs": [
        {
          "_id": "ns1HJS13AMkK:0007241142412418284",
          "type": "event",
          "userId": "abc123",
          "eventType": "addedToBasket",
          "productId": "1000042",
          "date": "2019-01-28T10:44:22.000Z"
        },
        {
          "_id": "H8tDIwfadxp9:0007241142412418285",
          "type": "event",
          "userId": "abc234",
          "eventType": "addedToBasket",
          "productId": "1000050",
          "date": "2019-01-25T20:00:00.000Z"
        }
      ]
    }
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.BulkDocs;
    import com.ibm.cloud.cloudant.v1.model.Document;
    import com.ibm.cloud.cloudant.v1.model.DocumentResult;
    import com.ibm.cloud.cloudant.v1.model.PostBulkDocsOptions;
    
    import java.util.Arrays;
    import java.util.List;
    
    Cloudant service = Cloudant.newInstance();
    
    Document eventDoc1 = new Document();
    eventDoc1.setId("ns1HJS13AMkK:0007241142412418284");
    eventDoc1.put("type", "event");
    eventDoc1.put("userId", "abc123");
    eventDoc1.put("eventType", "addedToBasket");
    eventDoc1.put("productId", "1000042");
    eventDoc1.put("date", "2019-01-28T10:44:22.000Z");
    
    Document eventDoc2 = new Document();
    eventDoc2.setId("H8tDIwfadxp9:0007241142412418285");
    eventDoc2.put("type", "event");
    eventDoc2.put("userId", "abc234");
    eventDoc2.put("eventType", "addedToBasket");
    eventDoc2.put("productId", "1000050");
    eventDoc2.put("date", "2019-01-28T10:44:22.000Z");
    
    BulkDocs bulkDocs = new BulkDocs.Builder()
        .docs(Arrays.asList(eventDoc1, eventDoc2))
        .build();
    
    PostBulkDocsOptions bulkDocsOptions = new PostBulkDocsOptions.Builder()
        .db("events")
        .bulkDocs(bulkDocs)
        .build();
    
    List<DocumentResult> response =
        service.postBulkDocs(bulkDocsOptions).execute()
            .getResult();
    
    System.out.println(response);
    
  • import com.ibm.cloud.cloudant.v1.Cloudant;
    import com.ibm.cloud.cloudant.v1.model.BulkDocs;
    import com.ibm.cloud.cloudant.v1.model.Document;
    import com.ibm.cloud.cloudant.v1.model.DocumentResult;
    import com.ibm.cloud.cloudant.v1.model.PostBulkDocsOptions;
    
    import java.util.Arrays;
    import java.util.List;