Azure Cosmos DB REST API
The Azure Cosmos DB REST API provides programmatic access to Cosmos DB resources (databases, containers, items, permissions, users, stored procedures, triggers, and UDFs) using standard HTTP verbs.
Base URI
https://{account}.documents.azure.com
Supported HTTP Methods
- GET – Retrieve resources
- POST – Create resources or execute stored procedures
- PUT – Replace resources
- PATCH – Update partial content (preview)
- DELETE – Delete resources
All requests and responses are JSON-formatted unless stated otherwise.
Master Key Authentication
Requests must be signed with the account’s master key or a resource token. The signature is generated using HMAC‑SHA256.
Required Headers
x-ms-date
– Current UTC date, e.g.,Wed, 01 Oct 2024 12:34:56 GMT
Authorization
– Signature string:type=master&ver=1.0&sig={signature}
Signature Generation (Pseudo‑code)
string verb = requestMethod.ToUpperInvariant();
string resourceType = requestResourceType.ToLowerInvariant();
string resourceId = requestResourceId;
string date = xMsDateHeader.ToLowerInvariant();
string payload = $"{verb}\n{resourceType}\n{resourceId}\n{date}\n\n";
byte[] key = Convert.FromBase64String(masterKey);
using var hmac = new HMACSHA256(key);
string signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)));
string authHeader = Uri.EscapeDataString($"type=master&ver=1.0&sig={signature}");
Example Authorization Header
type%3Dmaster%26ver%3D1.0%26sig%3DvKJwVJtK5...
Common Operations
Create a Database
Request
POST https://myaccount.documents.azure.com/dbs
x-ms-date: Wed, 01 Oct 2024 12:34:56 GMT
Authorization: {authHeader}
Content-Type: application/json
{
"id": "SampleDB"
}
Read a Container
GET https://myaccount.documents.azure.com/dbs/SampleDB/colls/Items
x-ms-date: Wed, 01 Oct 2024 12:34:56 GMT
Authorization: {authHeader}
Execute a Stored Procedure
POST https://myaccount.documents.azure.com/dbs/SampleDB/colls/Items/sprocs/InsertItem
x-ms-date: Wed, 01 Oct 2024 12:34:56 GMT
Authorization: {authHeader}
Content-Type: application/json
{
"params": [
{ "id": "item1", "name": "Sample Item" }
]
}
Standard Request Headers
Header | Description |
---|---|
x-ms-date | UTC timestamp of the request. |
Authorization | Signature generated from the master key. |
Content-Type | Usually application/json . |
x-ms-version | API version, e.g., 2023-11-15 . |
x-ms-consistency-level | Optional consistency override. |
Standard Response Headers
Header | Description |
---|---|
x-ms-request-charge | Request Units (RU) consumed. |
x-ms-activity-id | Correlation ID for troubleshooting. |
x-ms-session-token | Session token for consistency. |
Sample: Node.js SDK using REST API
const crypto = require('crypto');
const https = require('https');
const account = 'myaccount';
const masterKey = 'YOUR_MASTER_KEY';
const dbId = 'SampleDB';
const containerId = 'Items';
function getAuthHeader(verb, resourceType, resourceId, date) {
const key = Buffer.from(masterKey, 'base64');
const payload = `${verb.toLowerCase()}\n${resourceType.toLowerCase()}\n${resourceId}\n${date.toLowerCase()}\n\n`;
const sig = crypto.createHmac('sha256', key).update(payload, 'utf8').digest('base64');
return encodeURIComponent(`type=master&ver=1.0&sig=${sig}`);
}
function request(options, body) {
return new Promise((resolve, reject) => {
const req = https.request(options, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve({status: res.statusCode, headers: res.headers, body: data}));
});
req.on('error', reject);
if (body) req.write(body);
req.end();
});
}
// Example: Create a document
(async () => {
const verb = 'POST';
const resourceType = 'docs';
const resourceId = `dbs/${dbId}/colls/${containerId}`;
const date = new Date().toUTCString();
const auth = getAuthHeader(verb, resourceType, resourceId, date);
const options = {
hostname: `${account}.documents.azure.com`,
path: `/${resourceId}/docs`,
method: verb,
headers: {
'x-ms-date': date,
'x-ms-version': '2023-11-15',
'Authorization': auth,
'Content-Type': 'application/json'
}
};
const payload = JSON.stringify({ id: 'item1', name: 'Sample Item' });
const resp = await request(options, payload);
console.log('Status:', resp.status);
console.log('Body:', resp.body);
})();