Introduction to Azure Cosmos DB APIs
Azure Cosmos DB is a globally distributed, multi-model database service. It offers robust APIs for interacting with your data, including a powerful REST API and comprehensive SDKs for various programming languages.
Getting Started
To start using the Cosmos DB APIs, you'll need an Azure account and a Cosmos DB account provisioned. You can then create databases, containers, and items.
Key concepts include:
- Accounts: The top-level resource for Cosmos DB.
- Databases: A logical grouping of containers.
- Containers: Where your data is stored. Can be document collections, key-value tables, graph collections, etc.
- Items: The individual data entities within a container.
Azure Cosmos DB REST API
The REST API provides a programmatic interface to manage and query your Cosmos DB resources. It uses standard HTTP methods (GET, POST, PUT, DELETE) and JSON for request and response bodies.
Common Operations
- Create Container:
POST /dbs/{database_id}/colls
- Read Container:
GET /dbs/{database_id}/colls/{collection_id}
- Create Item:
POST /dbs/{database_id}/colls/{collection_id}/docs
- Read Item:
GET /dbs/{database_id}/colls/{collection_id}/docs/{doc_id}
- Query Items:
POST /dbs/{database_id}/colls/{collection_id}/docs
with a JSON body containing the query.
Authentication
Requests to the Cosmos DB REST API must be authenticated. The most common method is using the Resource Token or Master Key.
Requests must include the x-ms-date
header, which is the UTC date/time of the request, and an Authorization
header containing the signature.
Error Handling
Cosmos DB returns standard HTTP status codes. Common error codes include:
400 Bad Request
: Invalid request syntax.401 Unauthorized
: Authentication failed.404 Not Found
: Resource not found.409 Conflict
: Resource already exists.429 Too Many Requests
: Request rate exceeded (throttling).
Error responses also include a JSON body with more details, such as code
and message
.
SDK Reference
The Azure Cosmos DB SDKs simplify interaction with the database by providing language-native interfaces.
Azure Cosmos DB .NET SDK
The .NET SDK offers LINQ support, asynchronous operations, and robust error handling.
Install-Package Microsoft.Azure.Cosmos
Example: Creating an item
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Cosmos.Linq;
using System.Threading.Tasks;
// Assume cosmosClient is initialized
var container = cosmosClient.GetContainer("myDatabase", "myContainer");
var newItem = new { id = "item1", category = "electronics", name = "Laptop" };
var response = await container.CreateItemAsync(newItem);
Azure Cosmos DB Java SDK
The Java SDK provides a fluent API for interacting with Cosmos DB resources.
Maven dependency: com.azure:azure-cosmos
Example: Querying items
import com.azure.cosmos.CosmosClient;
import com.azure.cosmos.CosmosContainer;
import com.azure.cosmos.models.CosmosQueryRequestOptions;
import com.azure.cosmos.util.CosmosPagedIterable;
// Assume cosmosClient is initialized
CosmosContainer container = cosmosClient.getDatabase("myDatabase").getContainer("myContainer");
String query = "SELECT * FROM c WHERE c.category = 'electronics'";
CosmosQueryRequestOptions options = new CosmosQueryRequestOptions();
CosmosPagedIterable<Item> items = container.queryItems(query, options, Item.class);
for (Item item : items) {
System.out.println("Found item: " + item);
}
Azure Cosmos DB Node.js SDK
The Node.js SDK offers a modern JavaScript interface for Cosmos DB.
npm install @azure/cosmos
Example: Upserting an item
const { CosmosClient } = require("@azure/cosmos");
// Assume client is initialized
const container = client.database("myDatabase").container("myContainer");
const item = { id: "item2", name: "Tablet", price: 300 };
const { resource: createdItem } = await container.upsertItem(item);
console.log(`Upserted item: ${createdItem.id}`);
Azure Cosmos DB Python SDK
The Python SDK provides an idiomatic Python experience for managing Cosmos DB.
pip install azure-cosmos
Example: Reading an item
from azure.cosmos import CosmosClient
# Assume client is initialized
container = client.get_database_client("myDatabase").get_container_client("myContainer")
item_id = "item1"
item_data = container.read_item(item=item_id, partition_key="some_partition_key_if_needed")
print(f"Read item: {item_data}")
Cosmos DB Resource Model
Resources in Cosmos DB are represented using a hierarchical structure. Each resource has a unique _rid
(resource ID) and _ts
(timestamp).
Item Example:
{
"id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
"_rid": "some_rid_value",
"_ts": 1678886400,
"category": "gadgets",
"name": "Smartwatch",
"version": "1.0"
}
Query Language (SQL)
Azure Cosmos DB supports a powerful SQL query language for retrieving data. Queries are executed using the query
operation via the REST API or SDKs.
Example Query:
SELECT VALUE c FROM c WHERE c.category = "electronics" AND c.price > 1000
API Best Practices
- Use SDKs: SDKs abstract away many low-level details and provide a better developer experience.
- Optimize Queries: Ensure your queries are efficient, use appropriate indexing, and leverage partition keys.
- Handle Throttling: Implement retry logic for
429 Too Many Requests
errors. - Leverage Partition Keys: Design your data model with effective partition keys for scalability.
- Batch Operations: For multiple operations, consider using batching if supported by the API/SDK for improved performance.