Introduction to the Azure Cosmos DB REST API
The Azure Cosmos DB REST API provides a comprehensive way to interact with your Azure Cosmos DB data. You can perform operations such as creating, reading, updating, and deleting resources like databases, collections (containers), documents, and more. This API is designed to be stateless, allowing you to interact with your data from any client that can make HTTP requests.
Authentication
All requests to Azure Cosmos DB must be authenticated. The primary method of authentication is using the Resource Tokens or the Master Key.
Master Key Authentication
You can use the primary or secondary master key of your Azure Cosmos DB account to authenticate requests. This is typically used for administrative operations or when building services that manage your Cosmos DB account.
Authorization Header:
{"type": "master", "token": "YOUR_MASTER_KEY"}
Resource Token Authentication
Resource tokens are generated by Azure Cosmos DB and grant specific permissions to a user for accessing resources. They are ideal for client-side applications that require controlled access to specific data.
Authorization Header:
{"type": "resource", "token": "YOUR_RESOURCE_TOKEN"}
Common Request and Response Headers
The following headers are commonly used for interacting with Azure Cosmos DB resources:
Request Headers
| Header | Description |
|---|---|
Authorization |
Specifies authentication credentials (Master Key or Resource Token). |
x-ms-date |
The UTC date and time of the request. |
x-ms-version |
The version of the Azure Cosmos DB REST API to use. |
Content-Type |
The MIME type of the request body. Typically application/json. |
x-ms-continuation |
Used for pagination when retrieving large lists of resources. |
x-ms-max-item-count |
Specifies the maximum number of items to return in a query. |
x-ms-documentdb-is-query |
Set to True for query operations. |
x-ms-indexing-directive |
Controls indexing behavior for a specific operation (e.g., exclude). |
Response Headers
| Header | Description |
|---|---|
x-ms-request-id |
A unique identifier for the request. |
x-ms-activity-id |
An ID for tracing operations across services. |
x-ms-session-token |
Used for session consistency. |
x-ms-continuation |
Returned for paginated results to fetch the next page. |
x-ms-collection-partition-index |
Indicates the partition index for collections. |
x-ms-upsert-bypass-id |
Indicates if upsert bypassed ID checks. |
x-ms-cosmos-diagnostics |
Detailed diagnostics information. |
Content-Type |
The MIME type of the response body. |
Content-Length |
The size of the response body. |
Last-Modified |
The last modified date and time of the resource. |
ETag |
The ETag of the resource, used for optimistic concurrency control. |
x-ms-charge |
The Request Units (RUs) consumed by the operation. |
Resource Model
Azure Cosmos DB resources are organized hierarchically. The top-level resource is the account, followed by databases, collections (containers), and then documents, attachments, users, permissions, stored procedures, triggers, and user-defined functions.
Databases
Databases are logical containers for collections (containers) and other resources.
List Databases
Retrieves a list of all databases in the account.
Example Response (200 OK):
{
"dbs": [
{
"id": "ToDoList",
"_rid": "y8cKAA==",
"_ts": 1443155453,
"_self": "dbs/y8cKAA==/",
"_etag": "00000100-0000-0000-0000-56155e8f0000",
"_colls": "colls/"
},
{
"id": "UserDatabase",
"_rid": "gZ7KAA==",
"_ts": 1443248394,
"_self": "dbs/gZ7KAA==/",
"_etag": "00000200-0000-0000-0000-5616939a0000",
"_colls": "colls/"
}
],
"_rid": "",
"_count": 2
}
Create Database
Creates a new database.
Request Body:
{
"id": "NewDatabase"
}
Read Database
Retrieves a specific database by its ID.
Delete Database
Deletes a database and all its contents.
Collections (Containers)
Collections (now referred to as Containers in Azure Cosmos DB terminology) are logical groupings of documents (items) and are the units of provisioned throughput and storage.
List Collections
Retrieves a list of collections within a database.
Create Collection
Creates a new collection.
Request Body:
{
"id": "MyNewCollection",
"indexingPolicy": {
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*",
"indexes": [
{
"kind": "Range",
"data_type": "string",
"precision": -1
},
{
"kind": "Range",
"data_type": "number",
"precision": -1
}
]
}
],
"excludedPaths": []
},
"partitionKey": {
"paths": [
"/categoryId"
],
"kind": "Hash"
},
"conflictResolutionPolicy": {
"mode": "LastWriterWins",
"resolutionPath": "/myLastUpdated"
},
"uniqueKeyPolicy": {
"uniqueKeys": []
},
"defaultTtl": 604800,
"throughput": 400
}
Read Collection
Retrieves a specific collection by its ID.
Update Collection
Updates properties of an existing collection.
Request Body: (Example: Updating default TTL)
{
"id": "MyNewCollection",
"defaultTtl": 1209600, // 14 days
"_rid": "y8cKAAIBAw==",
"_ts": 1443155453,
"_self": "dbs/y8cKAA==/colls/y8cKAAIBAw==/",
"_etag": "00000200-0000-0000-0000-56155e8f0001",
"indexingPolicy": {
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*",
"indexes": [
{
"kind": "Range",
"data_type": "string",
"precision": -1
},
{
"kind": "Range",
"data_type": "number",
"precision": -1
}
]
}
],
"excludedPaths": []
},
"partitionKey": {
"paths": [
"/categoryId"
],
"kind": "Hash"
},
"conflictResolutionPolicy": {
"mode": "LastWriterWins",
"resolutionPath": "/myLastUpdated"
},
"uniqueKeyPolicy": {
"uniqueKeys": []
}
}
Delete Collection
Deletes a collection and all its documents.
List Collection Metrics
Retrieves metrics for a collection.
Documents (Items)
Documents are the fundamental units of data storage in Azure Cosmos DB. Each document is a JSON object.
List Documents
Retrieves a list of documents from a collection.
Querying Documents: Use the x-ms-documentdb-is-query header set to True and provide a SQL query in the request body.
x-ms-documentdb-is-query:
True
Request Body for Query:
{
"query": "SELECT * FROM root r WHERE r.status = 'active'"
}
Create Document
Creates a new document within a collection.
Request Body:
{
"id": "todo1",
"description": "Buy groceries",
"isComplete": false,
"category": "personal"
}
Read Document
Retrieves a specific document by its ID.
Update Document
Updates an existing document. Use the If-Match header with the document's ETag for optimistic concurrency control.
If-Match:
"your_document_etag"
Request Body:
{
"id": "todo1",
"description": "Buy organic groceries",
"isComplete": false,
"category": "personal",
"_rid": "y8cKAAIBAwMDAwA=",
"_ts": 1443155453,
"_self": "dbs/y8cKAA==/colls/y8cKAAIBAw==/docs/y8cKAAIBAwMDAwA=/",
"_etag": "00000300-0000-0000-0000-56155e8f0002"
}
Delete Document
Deletes a document.
Query Documents
Perform complex queries using a SQL-like query language. Set the x-ms-documentdb-is-query header to True and provide the query in the request body.
x-ms-documentdb-is-query:
True
Example Query: Fetching documents with specific properties and ordering.
{
"query": "SELECT c.id, c.description FROM c WHERE c.category = 'personal' ORDER BY c._ts DESC",
"parameters": []
}
Stored Procedures
Stored procedures allow you to encapsulate logic for complex operations on your documents. They are written in JavaScript.
List Stored Procedures
Retrieves a list of stored procedures for a collection.
Create Stored Procedure
Creates a new stored procedure.
Request Body:
{
"id": "updateTaskStatus",
"body": "function (taskId, newStatus) { \n var task = getDocument(taskId); \n task.isComplete = newStatus; \n return task; \n}"
}
Execute Stored Procedure
Executes a stored procedure.
x-ms-documentdb-script-version:
(optional)
Request Body (for parameters):
[
"todo1",
true
]
Indexing Policy
The indexing policy defines how your data is indexed in Azure Cosmos DB. You can customize it to optimize query performance.
Default Indexing Policy (for a Collection)
{
"indexingMode": "consistent",
"automatic": true,
"includedPaths": [
{
"path": "/*",
"indexes": [
{ "kind": "Range", "data_type": "string", "precision": -1 },
{ "kind": "Range", "data_type": "number", "precision": -1 }
]
}
],
"excludedPaths": []
}
You can modify this policy when creating or updating a collection.
Throughput Management
Throughput in Azure Cosmos DB is measured in Request Units (RUs). You can provision throughput at the database or collection level.
Setting Throughput for a Collection
Throughput (in RUs/sec) can be specified when creating or updating a collection.
x-ms-offer-type:
Standard
Request Body (within the collection definition):
{
"id": "MyCollection",
"throughput": 400 // 400 RUs/sec
}
Reading Throughput (Offer)
Retrieve the current provisioned throughput for a resource.
This reference provides a foundational understanding of the Azure Cosmos DB REST API. For detailed information on specific operations, error codes, and advanced features, please refer to the official Microsoft Azure Cosmos DB documentation.