N1QL REST API

N1QL REST API

N1QL provides a REST API to enable clients to execute N1QL statements. The REST API runs synchronously, so once execution of the statement in the request is started, results are streamed back to the client, terminating when execution of the statement finishes. In this section, you will find information about the REST endpoints, request and response parameters, and examples.

The REST endpoints are:

  • http://node:8093/query/service
  • https://node:18093/query/service (for secure access)

where node is the host name or IP address of a computer running the N1QL query engine.

The N1QL REST API query service allows you to execute a N1QL statement.

See Examples for REST API samples.

Request specification

This section describes how to specify requests.

Request format
Here is the format for GET and POST requests.
GET /query/service
POST /query/service
Request parameters
This table contains details of all the parameters that can be passed in a request to the /query/service endpoint:
Parameter name Value Description
statement String Required if prepared is not provided. Any valid N1QL statement for a POST request, or a read-only N1QL statement (such as SELECT or EXPLAIN) for a GET request. If both the prepared and statement parameters are present and non-empty, an error is returned.
prepared String Required if statement is not provided. The prepared form of the N1QL statement to be executed. If both the prepared and statement parameters are present and non-empty, an error is returned.
timeout String (duration format) Optional. Maximum time to spend on the request before timing out. The default value is "0s", which means no timeout is applied. That is, the request runs until completion regardless of how long it takes. Its format includes an amount and a unit. Valid units are "ns", "us", "ms", "s", "m", "h", for nanoseconds, microseconds, milliseconds, seconds, minutes and hours, respectively. The unit is mandatory. Examples are "10ms" (which means 10 milliseconds), "1m" (which means 1 minute), and "0.5s" (which means half a second). There is also a server-wide timeout parameter. If both the server-wide timeout parameter and the timeout parameter in the request are specified, the minimum of the two timeout values is applied.
namespace String Optional. Specifies the namespace to use. If a request does not specify a namespace, the server wide namespace parameter is used.
readonly Boolean Optional. Always true for GET requests. By default, false for POST requests. If the server-wide readonly parameter is set to true, its setting supersedes the request readonly parameter.
metrics Boolean Optional. Specifies that metrics should be returned with query results. Default value is true.
pretty Boolean Added in version 4.5.1.

Optional. Specifies if the query results are to be returned in a pretty format. When set to false, the white space characters are stripped from the query results, thus reducing the number of bytes transferred over the network. The performance benefits are significantly visible when executing queries that produce large result sets.

max_parallelism String Optional. Specifies the maximum parallelism for the query. When zero or a negative value is specified, the number of logical CPUs is used as the parallelism for the query. The server wide max_parallelism parameter has a default value of 1. If a request includes max_parallelism, it is capped by the server max_parallelism. If a request does not include max_parallelism, the server wide max_parallelism parameter is used.
$<identifier> json_value Optional. If the statement has one or more named parameters, there should be one or more named parameters in the request. A named parameter consists of the $ character followed by an identifier. An identifier is an alphabetical character followed by one or more alphanumeric characters. Named parameters apply to prepared also.
args list Optional. If the statement has one or more positional parameters, this parameter is required in the request. This is a list of JSON values, one for each positional parameter in the statement. Positional parameters apply to prepared also.
signature Boolean Optional. Include a header for the results schema in the response. Default value is true.
scan_consistency enum Optional. Specify the consistency guarantee or constraint for index scanning using one of the following values: not_bounded (default), request_plus, statement_plus, and at_plus. Values are case insensitive.
creds list Optional. A list of credentials in the form of user/password objects. If credentials are supplied in the request header (that is, using HTTP basic authentication), then creds is ignored. See Authentication Parameters section for full specification.
client_context_id string Optional. A piece of data supplied by the client that is echoed in the response, if present. N1QL makes no assumptions about the meaning of this data and just logs and echoes it. Maximum allowed size is 64 characters. A client_context_id longer than 64 characters is cut off at 64 characters.
Named parameters
If the statement in a request contains named parameters, the request should contain the parameters described in the following table.

Here is an example of a statement containing named parameters:

 SELECT detail FROM emp WHERE name = $nval AND age > $aval						
Parameter Name Value
statement SELECT detail FROM emp WHERE name = $nval AND age > $aval
$nval "smith"
$aval 45

There should be a named parameter in the request for each query parameter in the request’s statement parameter.

Positional parameters
If the statement in a request contains positional parameters, the request should contain the parameters described in the following table.

Here is an example of a statement containing positional parameters:

 SELECT detail FROM emp WHERE name = $1 AND hiredate > $2 						
statement SELECT detail FROM emp WHERE name = $1 AND age > $2
args [ "smith", 45 ]

Positional parameters can also be specified in a statement using the question mark (?), so the following statement is an alternative way to specify the same query:

Parameter Name Value
statement SELECT detail FROM emp WHERE name = ? AND age > ?
args [ "smith", 45 ]
Consistency parameters

scan_consistency

This parameter specifies the consistency guarantee or constraint for index scanning using one of the values listed in the following table.

Table 1. scan_consistency parameters
Value Description
not_bounded Default value for single-statement requests.

No timestamp vector is used in the index scan. This is also the fastest mode as we eliminate the cost of obtaining the vector and any wait time for the index to catch up with the vector.

at_plus This implements bounded consistency. The request includes a scan_vector parameter and a value, which is used as a lower bound. This can be used to implement read-your-own-writes (RYOW).
request_plus This implements strong consistency per request. Before processing the request, a current vector is obtained. The vector is used as a lower bound for the statements in the request. If there are DML statements in the request, RYOW is also applied within the request.

If request_plus is specified in a query that runs during a failover of an index node, the query waits until the rebalance operation completes and the index data has rebalanced before returning a result.

statement_plus This implements strong consistency per statement. Before processing each statement, a current vector is obtained and used as a lower bound for that statement.
Default behavior The default behavior for a single statement is not_bounded. For multi-statement requests, the default behavior is not_bounded for the request overall, and RYOW within the request.

Optional: If you want to disable RYOW within a request, add a separate request_consistency parameter and set it to not_bounded.

scan_vector

See at_plus parameter in the previous table executen1ql.html#table_xmr_grl_lt.

scan_wait

This parameter is a duration value (units of time) that specifies how much time the indexer is allowed to wait until it can satisfy the required scan_consistency and scan_vector criteria. After receiving the scan request, if the indexer is unable to catch up within that duration and initiate the scan, the indexer aborts with an error and the scan fails.

Authentication parameters
The Query API supports two types of credentials: local (or bucket) and admin. The format is an identity and password:
[local:] <bucket-name>
[admin:] <admin-name>
<password>

Note that identities can be optionally qualified. Clients passing in bucket names as the identity can prefix them with local:. This is to provide clarity and future-proofing for all current and future clients of query services.

Providing credentials in a request

Credentials can be passed via HTTP headers (HTTP basic authentication) or via the creds request parameter. If a request contains both HTTP basic authentication header and a creds parameter, the HTTP basic authentication header is ignored and only the creds parameter is used for authenticating.

HTTP headers (HTTP basic authentication) can only be used to provide a single credential. The creds request parameter contains a JSON array of user/pass objects:
creds=[{"user":"...","pass":"..."},{"user":"...","pass":"..."},...] 
The creds request parameter is the only way to provide multiple credentials for a request.
Request content type
For POST requests, you can specify the parameters in the request body in URL-encoded format or JSON format. For GET requests, you specify the parameters in the request URL in URL-encoded format. For URL-encoded parameters, the format is consistent with the syntax for variables according to the RFC 6570.

Response

This section has two subsections: Response HTTP Status Codes and Response Body.

Response HTTP status code

Normal status code:

200 OK- The request completed with or without errors. Any errors or warnings that occurred during the request will be in the response body.

Possible error codes:

400 Bad Request- The request cannot be processed for one of the following reasons:

  • The statement contains a N1QL syntax error.
  • The request has a missing or unrecognized HTTP parameter.
  • The request is badly formatted (for example, the request body contains a JSON syntax error).

401 Unauthorized- The credentials provided with the request are missing or invalid.

403 Forbidden- There is a read-only violation. Either there was an attempt to create or update in a GET request or a POST request where readonly is set or the client does not have the authorization to modify an object (index, keyspace or namespace) in the statement.

404 Not Found- The statement in the request references an invalid namespace or keyspace.

405 Method Not Allowed- The REST method type in the request is unsupported.

409 Conflict- There is an attempt to create an object (keyspace or index) that already exists.

410 Gone- The server is shutting down gracefully. Previously made requests are being completed, but no new requests are being accepted.

500 Internal Server Error- There was an unforeseen problem processing the request.

503 Service Unavailable- There is an issue (that is possibly temporary) preventing the request being processed; the request queue is full or the data store is not accessible.

Response body

The response body has the following structure:

{
"requestID": UUID,
"clientContextID": string,
"signature": 
{ 
	*.* |
	( field_name:    field_type,
	...
	)
	},

"results": 
	[
	json_value,
	...    
	],
"errors":  
	[ 
	{ "code": int, "msg":  string }, ... 
	],
"warnings":    
	[ 
	{ "code": int, "msg": string }, … 
	],
"status":  "success",
"metrics":  
	{ 
	"elapsedTime": string, 
	"executionTime": string,
	"resultCount": unsigned int, 
	"resultSize": unsigned int,
	"mutationCount": unsigned int, 
	"sortCount": unsigned int, 
	"errorCount": unsigned int,
	"warningCount": unsigned int
	}
}
requestID UUID A unique identifier for the response.
clientContextID string The clientContextID of the request, if one was supplied (see client_context _id in Request Parameters).
signature object The schema of the results. Present only when the query completes successfully.
results list A list of all the objects returned by the query. An object can be any JSON value.
status enum The status of the request. Possible values are: success, running, errors, completed, stopped, timeout, fatal.
errors list A list of 0 or more error objects. If an error occurred during processing of the request, it will be represented by an error object in this list.
error.code int A number that identifies the error.
error.msg string A message describing the error in detail.
warnings list A list of 0 or more warning objects. If a warning occurred during processing of the request, it is represented by a warning object in this list.
warning.code int A number that identifies the warning.
warning.msg string A message describing the warning in full.
metrics object An object containing metrics about the request.
metrics.elapsedTime string The total time taken for the request, that is the time from when the request was received until the results were returned.
metrics.executionTime string The time taken for the execution of the request, that is the time from when query execution started until the results were returned.
metrics.resultCount unsigned int The total number of objects in the results.
metrics.resultSize unsigned int The total number of bytes in the results.
metrics.mutationCount unsigned int The number of mutations that were made during the request.
metrics.sortCount unsigned int The number of objects that were sorted. Present only if the request includes ORDER BY.

If a query includes ORDER BY, LIMIT, or OFFSET clauses, an application can use the sortCount value to give the overall number of results in a message such as "page 1 of N".

metrics.errorCount unsigned int The number of errors that occurred during the request.
metrics.warningCount unsigned int The number of warnings that occurred during the request.

Request error and warning format

Errors and warnings have the following format:

{
	"code" : int,
	"msg" : string,
	"name": string,
	"sev" : int,
	"temp" : bool
}			

code: A unique number for the error or warning. The code ranges are partitioned by component. The codes can also include parts that indicate severity and transience. code is always present in every condition returned in the Query REST API or captured in a log.

msg:A detailed description of the condition. msg is always present in every condition returned in the Query REST API or captured in a log.

The following elements are optional and can be present in a condition returned in the Query REST API or captured in a log. Additional elements not listed here might also be present. Clients and consumers of the REST API or the logs must accommodate any additional elements.

name:Unique name that has a 1:1 mapping to the code. Uniquely identifies the condition. name is helpful for pattern matching and can have meaning making it more memorable than the code). The name should be fully qualified. Here are some examples:

  • indexing.scan.io_failure
  • query.execute.index_not_found

sev:One of the following N1QL severity levels (listed in order of severity):

  1. Severe
  2. Error
  3. Warn
  4. Info

temp:Indicates if the condition is transient (for example, the queue is full). If the value is false, it tells clients and users that a retry without modification produces the same condition.