Azure Cosmos DB APIs

Azure Cosmos DB is a fully managed NoSQL database service that offers multiple data models and APIs. Choose the API that matches your application’s data model and query preferences.

SQL (Core) API

The SQL API provides a JSON document model with rich query capabilities using a SQL‑like syntax.

// Create a Cosmos DB client
const { CosmosClient } = require("@azure/cosmos");
const client = new CosmosClient({ endpoint: "YOUR_ENDPOINT", key: "YOUR_KEY" });

async function run() {
  const { database } = await client.databases.createIfNotExists({ id: "DemoDB" });
  const { container } = await database.containers.createIfNotExists({ id: "Items" });

  // Insert a document
  const { resource: createdItem } = await container.items.create({
    id: "item1",
    category: "books",
    title: "Design Patterns"
  });

  // Query documents
  const querySpec = {
    query: "SELECT * FROM c WHERE c.category = @category",
    parameters: [{ name: "@category", value: "books" }]
  };
  const { resources } = await container.items.query(querySpec).fetchAll();
  console.log(resources);
}
run().catch(console.error);

MongoDB API

Use the MongoDB wire protocol to interact with Cosmos DB using existing MongoDB drivers.

// Node.js MongoDB driver
const { MongoClient } = require("mongodb");
const uri = "mongodb://YOUR_ENDPOINT:10255/?ssl=true&replicaSet=globaldb";
const client = new MongoClient(uri, { auth: { username: "YOUR_USERNAME", password: "YOUR_PASSWORD" }, tlsInsecure: false });

async function run() {
  await client.connect();
  const db = client.db("DemoDB");
  const col = db.collection("Items");

  // Insert a document
  await col.insertOne({ _id: "item2", category: "movies", title: "Inception" });

  // Find documents
  const docs = await col.find({ category: "movies" }).toArray();
  console.log(docs);
}
run().catch(console.error);

Cassandra API

Provides a Cassandra‑compatible endpoint for existing Cassandra applications.

// Java driver
import com.datastax.oss.driver.api.core.CqlSession;
import java.net.InetSocketAddress;

public class CassandraDemo {
  public static void main(String[] args) {
    try (CqlSession session = CqlSession.builder()
        .addContactPoint(new InetSocketAddress("YOUR_ENDPOINT", 10350))
        .withAuthCredentials("YOUR_USERNAME", "YOUR_PASSWORD")
        .withSslContext(SslContextFactory.createSslContext())
        .withKeyspace("DemoDB")
        .build()) {

      // Insert
      session.execute("INSERT INTO Items (id, category, title) VALUES ('item3','music','Jazz Classics')");

      // Query
      session.execute("SELECT * FROM Items WHERE category='music'")
          .forEach(row -> System.out.println(row.getString("title")));
    }
  }
}

Gremlin (Graph) API

Interact with graph data using the Gremlin traversal language.

// Gremlin JS
const gremlin = require('gremlin');
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const Graph = gremlin.structure.Graph;

const dc = new DriverRemoteConnection('wss://YOUR_ENDPOINT:443/', {
  mimeType: 'application/vnd.gremlin-v2.0+json',
  auth: { username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD' }
});
const graph = new Graph();
const g = graph.traversal().withRemote(dc);

async function run() {
  // Add vertices
  await g.addV('person').property('id', 'p1').property('name', 'Alice').next();
  await g.addV('person').property('id', 'p2').property('name', 'Bob').next();
  // Add edge
  await g.V('p1').addE('knows').to(g.V('p2')).next();

  // Query
  const result = await g.V().hasLabel('person').values('name').toList();
  console.log(result);
  dc.close();
}
run().catch(console.error);

Table API

Provides an Azure Table storage‑compatible interface for key‑value data.

// C# Table client
using Azure;
using Azure.Data.Tables;

var serviceClient = new TableServiceClient(new Uri("https://YOUR_ACCOUNT.table.core.windows.net"), new TableSharedKeyCredential("YOUR_ACCOUNT", "YOUR_KEY"));
var tableClient = serviceClient.GetTableClient("DemoTable");

// Insert entity
var entity = new TableEntity("partition1", "row1") { { "Name", "John Doe" }, { "Age", 30 } };
await tableClient.AddEntityAsync(entity);

// Query entities
await foreach (var e in tableClient.QueryAsync(e => e.PartitionKey == "partition1"))
{
    Console.WriteLine($"{e.RowKey}: {e.GetString("Name")} ({e.GetInt32("Age")})");
}

Further Resources

ResourceDescription
Cosmos DB OverviewLearn the fundamentals of Azure Cosmos DB.
SQL API DocsDetailed documentation for the SQL API.
MongoDB API DocsGuide to using the MongoDB API with Cosmos DB.
Cassandra API DocsGetting started with the Cassandra API.
Gremlin API DocsWorking with graph data via Gremlin.
Table API DocsKey‑value storage using Table API.