Create C# API Using Azure Cosmos Library

Adrian Hartanto
Bina Nusantara IT Division
2 min readSep 30, 2022
Image form Unsplash By Phil

This Article is inspired when I create an SSIS API with Azure Cosmos Library. You can create other API using this method to improve performance in hitting the azure cosmos database.

Install Microsoft.Azure.Cosmos

Microsoft creates a document that can help you to install this package. The installment document can be read in Microsoft Database Installment Document.

Create Connection to Cosmos Database

Use the client library to get a connection to Cosmos Database. Set Keys in your appsettings.json. To set this you can read in Connecting To Cosmos Documentation.

The database must have the same name as your database and it is located here.

Database Location in Azure Cosmos Portal

Use the code below to retrieve using Azure Cosmos Library.

Database db = client.GetDatabase(“YourDatabase”);Container ctr = db.GetContainer(“YourContainer”);

The container name must be the same as your container name in the database.

CRUD Using Transactional batch

A transactional batch is good for performance and serializing your data. When using transactional batch to CRUD, you only make one connection to your container without a repetitive hit to the container.

This is the example code to do a transactional batch.

//first get your id and partition key to the list. Because in this //library you need an id and partition key to locate the datavar listPair = dto.Select(s => (s.Id, new PartitionKey(s.PartitionKey))).ToList();var data = (await ctr.ReadManyItemsAsync<YourModel>(listPair)).Resource;var partitionKeyDistinct = data.Select(s => s.PartitionKey).Distinct().ToList();partitionKeyDistinct.ForEach(async i =>{// create batch itemvar batch = ctr.CreateTransactionalBatch(new PartitionKey(i));data.Where(p => p.PartitionKey == i).ToList().ForEach(j =>{// update your data.var x = dto.Where(p => p.Id == j.Id).FirstOrDefault();j.Status = x.Status;j.StatusMessage = x.StatusMessage;// Add your changed data for the response.res.Add(j);//Dobatch.UpsertItem<YourModel>(j);});await batch.ExecuteAsync();});

In Conclusion

To summarize what to do:

1. Install Microsoft.Azure.Cosmos to use Microsoft.Azure.Cosmos library.

2. Create a Connection to Cosmos Database.

3. Using Transactional Batch for Create, Read, Update, and Delete.

In order to improve your performance in your API.

--

--