A common use case for the emulator is to serve as a development database while you're building your applications. Using the emulator for development can help you learn characteristics of creating and modeling data for a database like Azure Cosmos DB without incurring any service costs. Additionally, using the emulator as part of an automation workflow can ensure that you can run the same suite of integration tests. You can ensure that the same tests run both locally on your development machine and remotely in a continuous integration job.
Prerequisites
- .NET 6 or later, Node.js v20 or later, or Python 3.7 or later
- Ensure that all required executables are available in your
PATH.
- Windows emulator
- 64-bit Windows Server 2016, 2019, Windows 10, or Windows 11.
- Minimum hardware requirements:
- 2-GB RAM
- 10-GB available hard disk space
- Docker emulator
Install the emulator
There are multiple variations of the emulator and each variation has a relatively frictionless install process.
To get started, get the Linux-variant of the container image from the Microsoft Container Registry (MCR).
Pull the mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator Linux container image from the container registry to the local Docker host.
docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest
Check to make sure that the emulator image is available on your local Docker host.
docker images
To get started, get the Windows-variant of the container image from the Microsoft Container Registry (MCR).
Pull the mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator Windows container image from the container registry to the local Docker host.
docker pull mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator
Check to make sure that the emulator image is available on your local Docker host.
docker images
To get started, download and install the latest version of Azure Cosmos DB Emulator on your local computer.
Tip
The emulator release notes article lists all the available versions and the feature updates that were made in each release.
Download the Azure Cosmos DB emulator.
Run the installer on your local machine with administrative privileges.
The emulator automatically installs the appropriate developer certificates and configures firewall rules on your local machine.
To get started, get the Linux-variant of the container image from the Microsoft Container Registry (MCR).
Pull the mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator Linux container image using the mongodb tag from the container registry to the local Docker host.
docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest
Check to make sure that the emulator image is available on your local Docker host.
docker images
The Docker (Windows) container image doesn't support the API for MongoDB.
To get started, download and install the latest version of Azure Cosmos DB Emulator on your local computer.
Tip
The emulator release notes article lists all the available versions and the feature updates that were made in each release.
Download the Azure Cosmos DB emulator.
Run the installer on your local machine with administrative privileges.
The emulator automatically installs the appropriate developer certificates and configures firewall rules on your local machine.
The Docker container variant (Linux or Windows) of the emulator doesn't support the API for Apache Cassandra, API for Apache Gremlin, or API for Table.
To get started, download and install the latest version of Azure Cosmos DB Emulator on your local computer.
Tip
The emulator release notes article lists all the available versions and the feature updates that were made in each release.
Download the Azure Cosmos DB emulator.
Run the installer on your local machine with administrative privileges.
The emulator automatically installs the appropriate developer certificates and configures firewall rules on your local machine.
Start the emulator
Once downloaded, start the emulator with your specified API enabled.
The Docker container variant of the emulator doesn't support the API for Apache Cassandra.
Start the emulator's executable (Microsoft.Azure.Cosmos.Emulator.exe) at the %ProgramFiles%\Azure Cosmos DB Emulator path. Use these parameters to configure the emulator:
|
Description |
EnableCassandraEndpoint |
Enables API for Apache Cassandra endpoint. |
CassandraPort |
Port number to use for endpoint. |
Microsoft.Azure.Cosmos.Emulator.exe /EnableCassandraEndpoint /CassandraPort=65200
The emulator automatically opens the data explorer using the URL https://localhost:8081/_explorer/index.html.
The Docker container variant of the emulator doesn't support the API for Apache Gremlin.
Start the emulator's executable (Microsoft.Azure.Cosmos.Emulator.exe) at the %ProgramFiles%\Azure Cosmos DB Emulator path. Use these parameters to configure the emulator:
|
Description |
EnableGremlinEndpoint |
Enables API for Apache Gremlin endpoint. |
GremlinPort |
Port number to use for endpoint. |
Microsoft.Azure.Cosmos.Emulator.exe /EnableGremlinEndpoint /GremlinPort=65400
The emulator automatically opens the data explorer using the URL https://localhost:8081/_explorer/index.html.
The Docker container variant of the emulator doesn't support the API for Table.
Start the emulator's executable (Microsoft.Azure.Cosmos.Emulator.exe) at the %ProgramFiles%\Azure Cosmos DB Emulator path. Use these parameters to configure the emulator:
|
Description |
EnableTableEndpoint |
Enables API for Table endpoint. |
TablePort |
Port number to use for endpoint. |
Microsoft.Azure.Cosmos.Emulator.exe /EnableTableEndpoint /TablePort=65500
The emulator automatically opens the data explorer using the URL https://localhost:8081/_explorer/index.html.
Run a new container using the container image and the following configuration:
|
Description |
AZURE_COSMOS_EMULATOR_PARTITION_COUNT (Optional) |
Specify the number of partitions to use. |
AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE (Optional) |
Enable data persistence between emulator runs. |
AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE (Optional) |
Override the emulator's default IP address. |
For Linux systems, use:
docker run \
--publish 8081:8081 \
--publish 10250-10255:10250-10255 \
--name linux-emulator \
--detach \
mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest
For Windows systems, use:
$parameters = @(
"--publish", "8081:8081"
"--publish", "10250-10255:10250-10255"
"--name", "windows-emulator"
"--detach"
)
docker run @parameters mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest
Navigate to https://localhost:8081/_explorer/index.html to access the data explorer.
Create a new directory for the bind mount
Run a new container using the container image.
$parameters = @(
"--publish", "8081:8081"
"--publish", "10250-10255:10250-10255"
"--name", "windows-emulator"
"--detach"
)
docker run @parameters mcr.microsoft.com/cosmosdb/windows/azure-cosmos-emulator
Navigate to https://localhost:8081/_explorer/index.html to access the data explorer.
Start the emulator by selecting the application in the Windows Start menu.
Alternatively, you can start the emulator's executable (Microsoft.Azure.Cosmos.Emulator.exe) at the %ProgramFiles%\Azure Cosmos DB Emulator path.
Also, you can start the emulator from the command-line. Use these parameters to configure the emulator:
|
Description |
Port |
Port number to use for the API for NoSQL endpoint. |
Microsoft.Azure.Cosmos.Emulator.exe /Port=65000
The emulator automatically opens the data explorer using the URL https://localhost:8081/_explorer/index.html.
Run a new container using the container image and the following configuration:
|
Description |
AZURE_COSMOS_EMULATOR_ENABLE_MONGODB_ENDPOINT |
Specify the version of the MongoDB endpoint to use. Supported endpoints include: 3.2, 3.6, or 4.0. |
AZURE_COSMOS_EMULATOR_PARTITION_COUNT (Optional) |
Specify the number of partitions to use. |
AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE (Optional) |
Enable data persistence between emulator runs. |
AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE (Optional) |
Override the emulator's default IP address. |
For Linux systems, use:
docker run \
--publish 8081:8081 \
--publish 10250:10250 \
--env AZURE_COSMOS_EMULATOR_ENABLE_MONGODB_ENDPOINT=4.0 \
--name linux-emulator \
--detach \
mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:mongodb
For Windows systems, use:
$parameters = @(
"--publish", "8081:8081"
"--publish", "10250:10250"
"--env", "AZURE_COSMOS_EMULATOR_ENABLE_MONGODB_ENDPOINT=4.0"
"--name", "windows-emulator"
"--detach"
)
docker run @parameters mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:mongodb
Navigate to https://localhost:8081/_explorer/index.html to access the data explorer.
The Docker (Windows) container image doesn't support the API for MongoDB.
Start the emulator's executable (Microsoft.Azure.Cosmos.Emulator.exe) at the %ProgramFiles%\Azure Cosmos DB Emulator path. Use these parameters to configure the emulator:
|
Description |
EnableMongoDbEndpoint |
Enables API for MongoDB endpoint at specified MongoDB version. |
MongoPort |
Port number to use for endpoint. |
Microsoft.Azure.Cosmos.Emulator.exe /EnableMongoDbEndpoint=4.0 /MongoPort=65200
Note
For more information on command-line arguments and MongoDB versions supported by the emulator, see command-line parameters.
The emulator automatically opens the data explorer using the URL https://localhost:8081/_explorer/index.html.
Import the emulator's TLS/SSL certificate
Import the emulator's TLS/SSL certificate to use the emulator with your preferred developer SDK without disabling TLS/SSL on the client.
The Docker container variant (Linux or Windows) of the emulator doesn't support the API for Apache Cassandra, API for Apache Gremlin, or API for Table.
The Windows local installation of the emulator automatically imports the TLS/SSL certificates. No further action is necessary.
The certificate for the emulator is available at the path _explorer/emulator.pem on the running container. Use curl to download the certificate from the running container to your local machine.
Get the certificate from the running container.
For Linux systems, use:
curl --insecure https://localhost:8081/_explorer/emulator.pem > ~/emulatorcert.crt
For Windows systems, use:
$parameters = @{
Uri = 'https://localhost:8081/_explorer/emulator.pem'
Method = 'GET'
OutFile = 'emulatorcert.crt'
SkipCertificateCheck = $True
}
Invoke-WebRequest @parameters
Regenerate the certificate bundle by using the appropriate command for your operating system.
For Debian-based Linux systems (for example, Ubuntu), use:
sudo update-ca-certificates
For Red Hat-based Linux systems (for example, CentOS, Fedora), use:
sudo update-ca-trust
For Windows systems, use:
certutil -f -addstore "Root" ~/emulatorcert.crt
For more detailed instructions, consult the documentation specific to your operating system.
The Docker (Windows) container image doesn't support the API for MongoDB.
The Windows local installation of the emulator automatically imports the TLS/SSL certificates. No further action is necessary.
The certificate for the emulator is available at the path /_explorer/emulator.pem on the running container.
Download the certificate from the running container to your local machine.
For Linux systems, use:
curl --insecure https://localhost:8081/_explorer/emulator.pem > ~/emulatorcert.crt
For Windows systems, use:
$parameters = @{
Uri = 'https://localhost:8081/_explorer/emulator.pem'
Method = 'GET'
OutFile = 'emulatorcert.crt'
SkipCertificateCheck = $True
}
Invoke-WebRequest @parameters
Note
You may need to change the host (or IP address) and port number if you have previously modified those values.
Install the certificate according to the process typically used for your operating system. For example, in Linux you would copy the certificate to the /usr/local/share/ca-certificates/ path.
For Linux systems, use:
cp ~/emulatorcert.crt /usr/local/share/ca-certificates/
For Windows systems, use:
$parameters = @{
FilePath = 'emulatorcert.crt'
CertStoreLocation = 'Cert:\CurrentUser\Root'
}
Import-Certificate @parameters
For linux systems, regenerate the certificate bundle by using the appropriate command for your Linux distribution.
For Debian-based Linux systems (for example, Ubuntu), use:
sudo update-ca-certificates
For Red Hat-based Linux systems (for example, CentOS, Fedora), use:
sudo update-ca-trust
For more detailed instructions, consult the documentation specific to your operating system.
The certificate for the emulator is available at the folder C:\CosmosDB.Emulator\bind-mount on the running container. The folder also contains a script to automatically install the certificate.
Use docker cp to copy the entire folder to your local machine.
docker cp windows-emulator:C:\CosmosDB.Emulator\bind-mount .
Run the importcert.ps1 script in the folder.
.\bind-mount\importcert.ps1
The Windows local installation of the emulator automatically imports the TLS/SSL certificates. No further action is necessary.
Connect to the emulator from the SDK
Each SDK includes a client class typically used to connect the SDK to your Azure Cosmos DB account. By using the emulator's credentials, you can connect the SDK to the emulator instance instead.
Use the Azure Cosmos DB API for NoSQL .NET SDK to connect to the emulator from a .NET application.
Start in an empty folder.
Create a new .NET console application
dotnet new console
Add the Microsoft.Azure.Cosmos package from NuGet.
dotnet add package Microsoft.Azure.Cosmos
Open the Program.cs file.
Delete any existing content within the file.
Add a using block for the Microsoft.Azure.Cosmos namespace.
using Microsoft.Azure.Cosmos;
Create a new instance of CosmosClient using the emulator's credentials.
using CosmosClient client = new(
accountEndpoint: "https://localhost:8081/",
authKeyOrResourceToken: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
);
Create a new database and container using CreateDatabaseIfNotExistsAsync and CreateContainerIfNotExistsAsync.
Database database = await client.CreateDatabaseIfNotExistsAsync(
id: "cosmicworks",
throughput: 400
);
Container container = await database.CreateContainerIfNotExistsAsync(
id: "products",
partitionKeyPath: "/id"
);
Create a new item in the container using UpsertItemAsync.
var item = new
{
id = "68719518371",
name = "Kiama classic surfboard"
};
await container.UpsertItemAsync(item);
Run the .NET application.
dotnet run
Warning
If you get a SSL error, you may need to disable TLS/SSL for your application. This commonly occurs if you are developing on your local machine, using the Azure Cosmos DB emulator in a container, and have not imported the container's SSL certificate. To resolve this, configure the client's options to disable TLS/SSL validation before creating the client:
CosmosClientOptions options = new ()
{
HttpClientFactory = () => new HttpClient(new HttpClientHandler()
{
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
}),
ConnectionMode = ConnectionMode.Gateway,
};
using CosmosClient client = new(
...,
...,
clientOptions: options
);
Use the Azure Cosmos DB API for NoSQL Python SDK to connect to the emulator from a Python application.
Start in an empty folder.
Import the azure-cosmos package from the Python Package Index.
pip install azure-cosmos
Create the app.py file.
Import CosmosClient and PartitionKey from the azure.cosmos module.
from azure.cosmos import CosmosClient, PartitionKey
Create a new CosmosClient using the emulator's credentials.
client = CosmosClient(
url="<https://localhost:8081>",
credential=(
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGG"
"yPMbIZnqyMsEcaGQy67XIw/Jw=="
),
)
Create a new database and container using create_database_if_not_exists and create_container_if_not_exists.
database = client.create_database_if_not_exists(
id="cosmicworks",
offer_throughput=400,
)
container = database.create_container_if_not_exists(
id="products",
partition_key=PartitionKey(
path="/id",
),
)
Use upsert_item to create a new item in the container.
item = {"id": "68719518371", "name": "Kiama classic surfboard"}
container.upsert_item(item)
Run the Python application.
python app.py
Warning
If you get a SSL error, you might need to disable TLS/SSL for your application. This commonly occurs if you are developing on your local machine, using the Azure Cosmos DB emulator in a container, and have not imported the container's SSL certificate. To resolve this, configure the application to disable TLS/SSL validation before creating the client:
import urllib3
urllib3.disable_warnings()
If you're still facing SSL errors, it's possible that Python is retrieving the certificates from a different certificate store. To determine the path where Python is looking for the certificates, follow these steps:
Important
If you are using a Python virtual environment (venv) ensure it is activated before running the commands!
Open a terminal
Start the Python interpreter by typing python or python3, depending on your Python version.
In the Python interpreter, run the following commands:
from requests.utils import DEFAULT_CA_BUNDLE_PATH
print(DEFAULT_CA_BUNDLE_PATH)
Inside a virtual environment, the path might be (at least in Ubuntu):
path/to/venv/lib/pythonX.XX/site-packages/certifi/cacert.pem
Outside of a virtual environment, the path might be (at least in Ubuntu):
/etc/ssl/certs/ca-certificates.crt
Once you identified the DEFAULT_CA_BUNDLE_PATH, open a new terminal and run the following commands to append the emulator certificate to the certificate bundle:
Important
If DEFAULT_CA_BUNDLE_PATH variable points to a system directory, you might encounter a "Permission denied" error. In this case, you will need to run the commands with elevated privileges (as root). Also, you will need to update and regenerate the certificate bundle after executing the provided commands.
# Add a new line to the certificate bundle
echo >> /path/to/ca_bundle
# Append the emulator certificate to the certificate bundle
cat /path/to/emulatorcert.crt >> /path/to/ca_bundle
Use the Azure Cosmos DB API for NoSQL Node.js SDK to connect to the emulator from a Node.js/JavaScript application.
Start in an empty folder.
Initialize a new module.
npm init es6 --yes
Install the @azure/cosmos package from Node Package Manager.
npm install --save @azure/cosmos
Create the app.js file.
Import the CosmosClient type from the @azure/cosmos module.
import { CosmosClient } from '@azure/cosmos'
Use CosmosClient to create a new client instance using the emulator's credentials.
const cosmosClient = new CosmosClient({
endpoint: 'https://localhost:8081/',
key: 'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
})
Use Databases.createIfNotExists and Containers.createIfNotExists to create a database and container.
const { database } = await cosmosClient.databases.createIfNotExists({
id: 'cosmicworks',
throughput: 400
})
const { container } = await database.containers.createIfNotExists({
id: 'products',
partitionKey: {
paths: [
'/id'
]
}
})
Upsert a new item using Items.upsert.
const item = {
id: '68719518371',
name: 'Kiama classic surfboard'
}
container.items.upsert(item)
Run the Node.js application.
node app.js
Warning
If you get a SSL error, you may need to disable TLS/SSL for your application. This commonly occurs if you are developing on your local machine, using the Azure Cosmos DB emulator in a container, and have not imported the container's SSL certificate. To resolve this, configure the application to disable TLS/SSL validation before creating the client:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
Use the MongoDB .NET driver to connect to the emulator from a .NET application.
Start in an empty folder.
Create a new .NET console application
dotnet new console
Add the MongoDB.Driver package from NuGet.
dotnet add package MongoDB.Driver
Open the Program.cs file.
Delete any existing content within the file.
Add a using block for the MongoDB.Driver namespace.
using MongoDB.Driver;
Create a new instance of MongoClient using the emulator's credentials.
var client = new MongoClient(
"mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/admin?ssl=true&retrywrites=false"
);
Get the database and container using GetDatabase and GetCollection<>.
var database = client.GetDatabase("cosmicworks");
var collection = database.GetCollection<dynamic>("products");
Create a new item in the XXX using InsertOneAsync.
var item = new
{
name = "Kiama classic surfboard"
};
await collection.InsertOneAsync(item);
Run the .NET application.
dotnet run
Use the MongoDB Python driver to connect to the emulator from a Python application.
Start in an empty folder.
Import the pymongo package from the Python Package Index.
pip install pymongo
Create the app.py file.
Import the os, sys, and pymongo modules.
import pymongo
Create a new MongoClient using the emulator's credentials.
client = pymongo.MongoClient(
host=(
"mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2"
"nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/a"
"dmin?ssl=true"
),
tls=True,
)
Create a new database and container using list_database_names and list_collection_names along with the CreateDatabase and CreateCollection custom commands.
db = client["cosmicworks"]
if "cosmicworks" not in client.list_database_names():
db.command(
{
"customAction": "CreateDatabase",
"offerThroughput": 400,
}
)
collection = db["products"]
if "products" not in db.list_collection_names():
db.command({"customAction": "CreateCollection", "collection": "products"})
Use update_one to create a new item in the container.
item = {"id": "68719518371", "name": "Kiama classic surfboard"}
collection.update_one(
filter={"id": item["id"]}, update={"$set": item}, upsert=True
)
Run the Python application.
python app.py
Use the MongoDB Node.js driver to connect to the emulator from a Node.js/JavaScript application.
Start in an empty folder.
Initialize a new module.
npm init es6 --yes
Install the mongodb package from Node Package Manager.
npm install --save mongodb
Create the app.js file.
Import the MongoClient type from the mongodb module.
import { MongoClient } from 'mongodb'
Use MongoClient to create a new client instance using the emulator's credentials. Use connect to connect to the emulator.
const client = new MongoClient(
'mongodb://localhost:C2y6yDjf5%2FR%2Bob0N8A7Cgv30VRDJIWEHLM%2B4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw%2FJw%3D%3D@localhost:10255/admin?ssl=true&retrywrites=false'
)
await client.connect()
Use db and collection to create a database and container.
const database = client.db('cosmicworks')
const collection = database.collection('products')
Create a new item using insertOne.
const item = {
name: 'Kiama classic surfboard'
}
await collection.insertOne(item)
Run the Node.js application.
node app.js
Warning
If you get a SSL error, you may need to disable TLS/SSL for your application. This commonly occurs if you are developing on your local machine, using the Azure Cosmos DB emulator in a container, and have not imported the container's SSL certificate. To resolve this, configure the application to disable TLS/SSL validation before creating the client:
const client = new MongoClient(
...,
{ tlsAllowInvalidCertificates: true }
)
Use the Apache Cassandra .NET driver to connect to the emulator from a .NET application.
Start in an empty folder.
Create a new .NET console application
dotnet new console
Add the CassandraCSharpDriver package from NuGet.
dotnet add package CassandraCSharpDriver
Open the Program.cs file.
Delete any existing content within the file.
Add a using block for the Cassandra namespace.
using Cassandra;
Create a new instance of Cluster using the emulator's credentials. Create a new session using Connect.
var options = new SSLOptions(
sslProtocol: System.Security.Authentication.SslProtocols.Tls12,
checkCertificateRevocation: true,
remoteCertValidationCallback: (_, _, _, policyErrors) => policyErrors == System.Net.Security.SslPolicyErrors.None);
using var cluster = Cluster.Builder()
.WithCredentials(
username: "localhost",
password: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
)
.WithPort(
port: 10350
)
.AddContactPoint(
address: "localhost"
)
.WithSSL(
sslOptions: options
)
.Build();
using var session = cluster.Connect();
Create a new database and container using PrepareAsync and ExecuteAsync.
var createKeyspace = await session.PrepareAsync("CREATE KEYSPACE IF NOT EXISTS cosmicworks WITH replication = {'class':'basicclass', 'replication_factor': 1};");
await session.ExecuteAsync(createKeyspace.Bind());
var createTable = await session.PrepareAsync("CREATE TABLE IF NOT EXISTS cosmicworks.products (id text PRIMARY KEY, name text)");
await session.ExecuteAsync(createTable.Bind());
Create a new item in the table using ExecuteAsync. Use Bind to assign properties to the item.
var item = new
{
id = "68719518371",
name = "Kiama classic surfboard"
};
var createItem = await session.PrepareAsync("INSERT INTO cosmicworks.products (id, name) VALUES (?, ?)");
var createItemStatement = createItem.Bind(item.id, item.name);
await session.ExecuteAsync(createItemStatement);
Run the .NET application.
dotnet run
Use the Apache Cassandra Python driver to connect to the emulator from a Python application.
Start in an empty folder.
Import the cassandra-driver package from the Python Package Index.
pip install cassandra-driver
Create the app.py file.
Import PROTOCOL_TLS_CLIENT, SSLContext, and CERT_NONE from the ssl module. Then, import Cluster from the cassandra.cluster module. Finally, import PlainTextAuthProvider from the cassandra.auth module.
from ssl import PROTOCOL_TLS_CLIENT, SSLContext, CERT_NONE
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
Create a new TLS/SSL context variable using SSLContext. Configure the context to not verify the emulator's self-signed certificate.
ssl_context = SSLContext(PROTOCOL_TLS_CLIENT)
ssl_context.check_hostname = False
ssl_context.verify_mode = CERT_NONE
Create a new session using the emulator's credentials, PlainTextAuthProvider, Cluster, and cluster.connect().
auth_provider = PlainTextAuthProvider(
username="localhost",
password=(
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnq"
"yMsEcaGQy67XIw/Jw=="
),
)
cluster = Cluster(
["localhost"],
port="10350",
auth_provider=auth_provider,
ssl_context=ssl_context,
)
session = cluster.connect()
Create a new keyspace and table using session.execute.
session.execute(
"CREATE KEYSPACE IF NOT EXISTS cosmicworks WITH replication = {'class':'ba"
"sicclass', 'replication_factor': 1};"
)
session.execute(
"CREATE TABLE IF NOT EXISTS cosmicworks.products (id text PRIMARY KEY, nam"
"e text)"
)
Use session.execute to create a new item in the table.
item = {"id": "68719518371", "name": "Kiama classic surfboard"}
session.execute(
"INSERT INTO cosmicworks.products (id, name) VALUES (%s, %s)",
[item["id"], item["name"]],
)
Run the Python application.
python app.py
Use the Apache Cassandra Node.js driver to use the emulator from a Node.js/JavaScript application.
Start in an empty folder.
Initialize a new module.
npm init es6 --yes
Install the cassandra-driver package from Node Package Manager.
npm install --save cassandra-driver
Create the app.js file.
Import the Client type and auth namespace from the cassandra-driver module.
import { Client, auth } from 'cassandra-driver'
Use PlainTextAuthProvider to create a new object for the emulator's credentials. Use Client to connect to the emulator using the credentials.
const credentials = new auth.PlainTextAuthProvider(
'localhost',
'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
)
const client = new Client({
contactPoints: [
'localhost:10350'
],
authProvider: credentials,
localDataCenter: 'South Central US'
})
Use execute to run a command server-side to create a keyspace and table.
await client.execute(
'CREATE KEYSPACE IF NOT EXISTS cosmicworks WITH replication = {\'class\':\'basicclass\', \'replication_factor\': 1};'
)
await client.execute(
'CREATE TABLE IF NOT EXISTS cosmicworks.products (id text PRIMARY KEY, name text)'
)
Use execute again to create a new item with parameters.
const item = {
id: '68719518371',
name: 'Kiama classic surfboard'
}
await client.execute(
'INSERT INTO cosmicworks.products (id, name) VALUES (?, ?)',
[
item.id,
item.name
]
)
Run the Node.js application.
node app.js
Warning
If you get a SSL error, you may need to disable TLS/SSL for your application. This commonly occurs if you are developing on your local machine, using the Azure Cosmos DB emulator in a container, and have not imported the container's SSL certificate. To resolve this, configure the client to disable TLS/SSL validation:
const client = new Client({
...,
...,
...,
sslOptions: {
rejectUnauthorized: false
}
})
Important
Prior to starting, the API for Apache Gremlin requires you to create your resources in the emulator. Create a database named db1 and a container named coll1. The throughput settings are irrelevant for this guide and can be set as low as you'd like.
Use the Apache Gremlin .NET driver to connect to the emulator from a .NET application.
Start in an empty folder.
Create a new .NET console application
dotnet new console
Add the Gremlin.Net package from NuGet.
dotnet add package Gremlin.Net
Open the Program.cs file.
Delete any existing content within the file.
Add a using block for the Gremlin.Net.Driver namespace.
using Gremlin.Net.Driver;
Create a new instance of GremlinServer and GremlinClient using the emulator's credentials.
var server = new GremlinServer(
hostname: "localhost",
port: 65400,
username: "/dbs/db1/colls/coll1",
password: "C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
);
using var client = new GremlinClient(
gremlinServer: server,
messageSerializer: new Gremlin.Net.Structure.IO.GraphSON.GraphSON2MessageSerializer()
);
Clean up the graph using SubmitAsync.
await client.SubmitAsync(
requestScript: "g.V().drop()"
);
Use SubmitAsync again to add a new item to the graph with the specified parameters.
await client.SubmitAsync(
requestScript: "g.addV('product').property('id', prop_id).property('name', prop_name)",
bindings: new Dictionary<string, object>
{
{ "prop_id", "68719518371" },
{ "prop_name", "Kiama classic surfboard" }
}
);
Run the .NET application.
dotnet run
Use the Apache Gremlin Python driver to connect to the emulator from a Python application.
Start in an empty folder.
Import the gremlinpython package from the Python Package Index.
pip install gremlinpython
Create the app.py file.
Import client from the gremlin_python.driver module.
from gremlin_python.driver import client
Create a new Client using the emulator's credentials.
client = client.Client(
url="ws://localhost:8901/",
traversal_source="g",
username="/dbs/db1/colls/coll1",
password=(
"C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnq"
"yMsEcaGQy67XIw/Jw=="
),
)
Clean up the graph using client.submit.
client.submit(message="g.V().drop()")
Use client.submit again to add a new item to the graph with the specified parameters.
client.submit(
message=(
"g.addV('product').property('id', prop_id).property('name', prop_name)"
),
bindings={
"prop_id": "68719518371",
"prop_name": "Kiama classic surfboard",
},
)
Run the Python application.
python app.py
Use the Apache Gremlin Node.js driver to use the emulator from a Node.js/JavaScript application.
Start in an empty folder.
Initialize a new module.
npm init es6 --yes
Install the gremlin package from Node Package Manager.
npm install --save gremlin
Create the app.js file.
Import the gremlin module.
import gremlin from 'gremlin'
Use PlainTextSaslAuthenticator to create a new object for the emulator's credentials. Use Client to connect to the emulator using the credentials.
const credentials = new gremlin.driver.auth.PlainTextSaslAuthenticator(
'/dbs/db1/colls/coll1',
'C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=='
)
const client = new gremlin.driver.Client(
'ws://localhost:8901/',
{
credentials,
traversalsource: 'g',
rejectUnauthorized: false,
mimeType: 'application/vnd.gremlin-v2.0+json'
}
)
client.open()
Use submit to run a command server-side to clear the graph if it already has data.
await client.submit('g.V().drop()')
Use submit again to add a new item to the graph with the specified parameters.
await client.submit(
'g.addV(\'product\').property(\'id\', prop_id).property(\'name\', prop_name)', {
prop_id: '68719518371',
prop_name: 'Kiama classic surfboard'
}
)
Run the Node.js application.
node app.js
Use the Azure Tables SDK for .NET to connect to the emulator from a .NET application.
Start in an empty folder.
Create a new .NET console application
dotnet new console
Add the Azure.Data.Tables package from NuGet.
dotnet add package Azure.Data.Tables
Open the Program.cs file.
Delete any existing content within the file.
Add a using block for the Azure.Data.Tables namespace.
using Azure.Data.Tables;
Create a new instance of TableServiceClient using the emulator's credentials.
var serviceClient = new TableServiceClient(
connectionString: "DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==;TableEndpoint=http://localhost:8902/;"
);
Use GetTableClient to create a new instance of TableClient with the table's name. Then ensure the table exists using CreateIfNotExistsAsync.
var client = serviceClient.GetTableClient(
tableName: "cosmicworksproducts"
);
await client.CreateIfNotExistsAsync();
Create a new record type for items.
public record Product : Azure.Data.Tables.ITableEntity
{
public required string RowKey { get; set; }
public required string PartitionKey { get; set; }
public required string Name { get; init; }
public Azure.ETag ETag { get; set; }
public DateTimeOffset? Timestamp { get; set; }
}
Create a new item in the table using UpsertEntityAsync and the Replace mode.
var item = new Product
{
RowKey = "68719518371",
PartitionKey = "Surfboards",
Name = "Kiama classic surfboard",
Timestamp = DateTimeOffset.Now
};
await client.UpsertEntityAsync(
entity: item,
mode: TableUpdateMode.Replace
);
Run the .NET application.
dotnet run
Use the Azure Tables Python SDK to connect to the emulator from a Python application.
Start in an empty folder.
Import the azure-data-tables package from the Python Package Index.
pip install azure-data-tables
Create the app.py file.
Import TableServiceClient and UpdateMode from the azure.data.tables module.
from azure.data.tables import TableServiceClient, UpdateMode
Use TableServiceClient.from_connection_string to create a new service-level client.
service = TableServiceClient.from_connection_string(
conn_str=(
"DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey=C2y6yD"
"jf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEca"
"GQy67XIw/Jw==;TableEndpoint=http://localhost:8902/;"
)
)
Create a new table-level client using create_table_if_not_exists.
client = service.create_table_if_not_exists(table_name="cosmicworksproducts")
Use upsert_entity to create a new item in the container.
item = {
"PartitionKey": "68719518371",
"RowKey": "Surfboards",
"name": "Kiama classic surfboard",
}
client.upsert_entity(entity=item, mode=UpdateMode.REPLACE)
Run the Python application.
python app.py
Use the Azure Tables JavaScript SDK to use the emulator from a Node.js/JavaScript application.
Start in an empty folder.
Initialize a new module.
npm init es6 --yes
Install the @azure/data-tables package from Node Package Manager.
npm install --save @azure/data-tables
Create the app.js file.
Import the TableClient type from the @azure/data-tables module.
import { TableClient } from '@azure/data-tables'
Use TableClient.fromConnectionString to create a new client instance using the emulator's connection string.
const client = TableClient.fromConnectionString(
'DefaultEndpointsProtocol=http;AccountName=localhost;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==;TableEndpoint=http://localhost:8902/;',
'cosmicworksproducts'
)
Use createTable to create a new table if it doesn't already exist.
await client.createTable()
Use upsertEntity to create or replace the item.
const item = {
partitionKey: '68719518371',
rowKey: 'Surfboards',
name: 'Kiama classic surfboard'
}
await client.upsertEntity(
item,
'Replace'
)
Run the Node.js application.
node app.js
Warning
If you get a SSL error, you may need to disable TLS/SSL for your application. This commonly occurs if you are developing on your local machine, using the Azure Cosmos DB emulator in a container, and have not imported the container's SSL certificate. To resolve this, configure the client to disable TLS/SSL validation:
const client = TableClient.fromConnectionString(
...,
...,
{
allowInsecureConnection: true
}
)
Use the emulator in a GitHub Actions CI workflow
To run a continuous integration workload that automatically validates your application, use the Azure Cosmos DB emulator with a test suite from your framework of choice. The Azure Cosmos DB emulator is preinstalled in the windows-latest variant of GitHub Action's hosted runners.
Run a test suite using the built-in test driver for .NET and a testing framework such as MSTest, NUnit, or XUnit.
Validate that the unit test suite for your application works as expected.
dotnet test
Create a new workflow in your GitHub repository in a file named .github/workflows/ci.yml.
Add a job to your workflow to start the Azure Cosmos DB emulator using PowerShell and run your unit test suite.
name: Continuous Integration
on:
push:
branches:
- main
jobs:
unit_tests:
name: Run .NET unit tests
runs-on: windows-latest
steps:
- name: Checkout (GitHub)
uses: actions/checkout@v3
- name: Start Azure Cosmos DB emulator
run: |
Write-Host "Launching Cosmos DB Emulator"
Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
Start-CosmosDbEmulator
- name: Run .NET tests
run: dotnet test
Test your Python application and database operations using pytest.
Validate that the unit test suite for your application works as expected.
pip install -U pytest
pytest
Create a new workflow in your GitHub repository in a file named .github/workflows/ci.yml.
Add a job to your workflow to start the Azure Cosmos DB emulator using PowerShell and run your unit test suite.
name: Continuous Integration
on:
push:
branches:
- main
jobs:
unit_tests:
name: Run Python unit tests
runs-on: windows-latest
steps:
- name: Checkout (GitHub)
uses: actions/checkout@v3
- name: Start Azure Cosmos DB emulator
run: |
Write-Host "Launching Cosmos DB Emulator"
Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
Start-CosmosDbEmulator
- name: Install test runner
run: pip install pytest
- name: Run Python tests
run: pytest
Use mocha to test your Node.js application and its database modifications.
Validate that the unit test suite for your application works as expected.
npm install --global mocha
mocha
Create a new workflow in your GitHub repository in a file named .github/workflows/ci.yml.
Add a job to your workflow to start the Azure Cosmos DB emulator using PowerShell and run your unit test suite.
name: Continuous Integration
on:
push:
branches:
- main
jobs:
unit_tests:
name: Run Node.js unit tests
runs-on: windows-latest
steps:
- name: Checkout (GitHub)
uses: actions/checkout@v3
- name: Start Azure Cosmos DB emulator
run: |
Write-Host "Launching Cosmos DB Emulator"
Import-Module "$env:ProgramFiles\Azure Cosmos DB Emulator\PSModules\Microsoft.Azure.CosmosDB.Emulator"
Start-CosmosDbEmulator
- name: Install test runner
run: npm install --global mocha
- name: Run Node.js tests
run: mocha
Next step