Get started with Azure Cosmos DB for NoSQL using .NET

APPLIES TO: NoSQL

This article shows you how to connect to Azure Cosmos DB for NoSQL using the .NET SDK. Once connected, you can perform operations on databases, containers, and items.

Package (NuGet) | Samples | API reference | Library source code | Give Feedback

Prerequisites

Set up your project

Create the .NET console application

Create a new .NET application by using the dotnet new command with the console template.

dotnet new console

Import the Microsoft.Azure.Cosmos NuGet package using the dotnet add package command.

dotnet add package Microsoft.Azure.Cosmos

Build the project with the dotnet build command.

dotnet build

Connect to Azure Cosmos DB for NoSQL

To connect to the API for NoSQL of Azure Cosmos DB, create an instance of the CosmosClient class. This class is the starting point to perform all operations against databases. There are three core ways to connect to an API for NoSQL account using the CosmosClient class:

Connect with an endpoint and key

The most common constructor for CosmosClient has two parameters:

Parameter Example value Description
accountEndpoint COSMOS_ENDPOINT environment variable API for NoSQL endpoint to use for all requests
authKeyOrResourceToken COSMOS_KEY environment variable Account key or resource token to use when authenticating

Retrieve your account endpoint and key

  1. Create a shell variable for resourceGroupName.

    # Variable for resource group name
    resourceGroupName="msdocs-cosmos-dotnet-howto-rg"
    
  2. Use the az cosmosdb list command to retrieve the name of the first Azure Cosmos DB account in your resource group and store it in the accountName shell variable.

    # Retrieve most recently created account name
    accountName=$(
        az cosmosdb list \
            --resource-group $resourceGroupName \
            --query "[0].name" \
            --output tsv
    )
    
  3. Get the API for NoSQL endpoint URI for the account using the az cosmosdb show command.

    az cosmosdb show \
        --resource-group $resourceGroupName \
        --name $accountName \
        --query "documentEndpoint"
    
  4. Find the PRIMARY KEY from the list of keys for the account with the az-cosmosdb-keys-list command.

    az cosmosdb keys list \
        --resource-group $resourceGroupName \
        --name $accountName \
        --type "keys" \
        --query "primaryMasterKey"
    
  5. Record the URI and PRIMARY KEY values. You'll use these credentials later.

To use the URI and PRIMARY KEY values within your .NET code, persist them to new environment variables on the local machine running the application.

$env:COSMOS_ENDPOINT = "<cosmos-account-URI>"
$env:COSMOS_KEY = "<cosmos-account-PRIMARY-KEY>"

Create CosmosClient with account endpoint and key

Create a new instance of the CosmosClient class with the COSMOS_ENDPOINT and COSMOS_KEY environment variables as parameters.

// New instance of CosmosClient class using an endpoint and key string
using CosmosClient client = new(
    accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT")!,
    authKeyOrResourceToken: Environment.GetEnvironmentVariable("COSMOS_KEY")!
);

Connect with a connection string

Another constructor for CosmosClient only contains a single parameter:

Parameter Example value Description
accountEndpoint COSMOS_ENDPOINT environment variable API for NoSQL endpoint to use for all requests
connectionString COSMOS_CONNECTION_STRING environment variable Connection string to the API for NoSQL account

Retrieve your account connection string

  1. Use the az cosmosdb list command to retrieve the name of the first Azure Cosmos DB account in your resource group and store it in the accountName shell variable.

    # Retrieve most recently created account name
    accountName=$(
        az cosmosdb list \
            --resource-group $resourceGroupName \
            --query "[0].name" \
            --output tsv
    )
    
  2. Find the PRIMARY CONNECTION STRING from the list of connection strings for the account with the az-cosmosdb-keys-list command.

    az cosmosdb keys list \
        --resource-group $resourceGroupName \
        --name $accountName \
        --type "connection-strings" \
        --query "connectionStrings[?description == \`Primary SQL Connection String\`] | [0].connectionString"
    

To use the PRIMARY CONNECTION STRING value within your .NET code, persist it to a new environment variable on the local machine running the application.

$env:COSMOS_CONNECTION_STRING = "<cosmos-account-PRIMARY-CONNECTION-STRING>"

Create CosmosClient with connection string

Create a new instance of the CosmosClient class with the COSMOS_CONNECTION_STRING environment variable as the only parameter.

// New instance of CosmosClient class using a connection string
using CosmosClient client = new(
    connectionString: Environment.GetEnvironmentVariable("COSMOS_CONNECTION_STRING")!
);

Connect using the Microsoft identity platform

To connect to your API for NoSQL account using the Microsoft identity platform and Microsoft Entra ID, use a security principal. The exact type of principal will depend on where you host your application code. The table below serves as a quick reference guide.

Where the application runs Security principal
Local machine (developing and testing) User identity or service principal
Azure Managed identity
Servers or clients outside of Azure Service principal

Import Azure.Identity

The Azure.Identity NuGet package contains core authentication functionality that is shared among all Azure SDK libraries.

Import the Azure.Identity NuGet package using the dotnet add package command.

dotnet add package Azure.Identity

Rebuild the project with the dotnet build command.

dotnet build

In your code editor, add using directives for Azure.Core and Azure.Identity namespaces.

using Azure.Core;
using Azure.Identity;

Create CosmosClient with default credential implementation

If you're testing on a local machine, or your application will run on Azure services with direct support for managed identities, obtain an OAuth token by creating a DefaultAzureCredential instance.

For this example, we saved the instance in a variable of type TokenCredential as that's a more generic type that's reusable across SDKs.

// Credential class for testing on a local machine or Azure services
TokenCredential credential = new DefaultAzureCredential();

Create a new instance of the CosmosClient class with the COSMOS_ENDPOINT environment variable and the TokenCredential object as parameters.

// New instance of CosmosClient class using a connection string
using CosmosClient client = new(
    accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT")!,
    tokenCredential: credential
);

Create CosmosClient with a custom credential implementation

If you plan to deploy the application out of Azure, you can obtain an OAuth token by using other classes in the Azure.Identity client library for .NET. These other classes also derive from the TokenCredential class.

For this example, we create a ClientSecretCredential instance by using client and tenant identifiers, along with a client secret.

// Custom credential class for servers and clients outside of Azure
TokenCredential credential = new ClientSecretCredential(
    tenantId: Environment.GetEnvironmentVariable("AAD_TENANT_ID")!,
    clientId: Environment.GetEnvironmentVariable("AAD_CLIENT_ID")!,
    clientSecret: Environment.GetEnvironmentVariable("AAD_CLIENT_SECRET")!,
    options: new TokenCredentialOptions()
);

You can obtain the client ID, tenant ID, and client secret when you register an application in Microsoft Entra ID. For more information about registering Microsoft Entra applications, see Register an application with the Microsoft identity platform.

Create a new instance of the CosmosClient class with the COSMOS_ENDPOINT environment variable and the TokenCredential object as parameters.

// New instance of CosmosClient class using a connection string
using CosmosClient client = new(
    accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT")!,
    tokenCredential: credential
);

Build your application

As you build your application, your code will primarily interact with four types of resources:

  • The API for NoSQL account, which is the unique top-level namespace for your Azure Cosmos DB data.

  • Databases, which organize the containers in your account.

  • Containers, which contain a set of individual items in your database.

  • Items, which represent a JSON document in your container.

The following diagram shows the relationship between these resources.

Diagram of the Azure Cosmos DB hierarchy including accounts, databases, containers, and items.

Hierarchical diagram showing an Azure Cosmos DB account at the top. The account has two child database nodes. One of the database nodes includes two child container nodes. The other database node includes a single child container node. That single container node has three child item nodes.

Each type of resource is represented by one or more associated .NET classes. Here's a list of the most common classes:

Class Description
CosmosClient This class provides a client-side logical representation for the Azure Cosmos DB service. The client object is used to configure and execute requests against the service.
Database This class is a reference to a database that may, or may not, exist in the service yet. The database is validated server-side when you attempt to access it or perform an operation against it.
Container This class is a reference to a container that also may not exist in the service yet. The container is validated server-side when you attempt to work with it.

The following guides show you how to use each of these classes to build your application.

Guide Description
Create a database Create databases
Create a container Create containers
Read an item Point read a specific item
Query items Query multiple items

See also

Next steps

Now that you've connected to an API for NoSQL account, use the next guide to create and manage databases.