Azure Cosmos DB is a globally distributed, multi-model NoSQL database service provided by Microsoft Azure. It is designed to handle large-scale, high-performance applications that require low-latency access to data.
Azure Cosmos DB Benefits:
- Azure Cosmos DB offers support for multiple data models, including document, key-value, graph, and column-family, allowing developers to choose the most appropriate data model for their applications.
- It provides automatic scaling, high availability, and global replication, ensuring that your data is always accessible and protected.
- With its flexible and powerful features, Azure Cosmos DB enables developers to build and scale globally distributed applications with ease.
.NET Core API with Azure Cosmos DB SQL integration
Step 1: Create a new .NET Core API Project Open your preferred IDE (such as Visual Studio or Visual Studio Code) and create a new .NET Core API project.
Step 2: Install required packages In your project, you’ll need to install the following NuGet packages:
dotnet add package Microsoft.Azure.Cosmos
Step 3: Configure Azure Cosmos DB SQL connection In the appsettings.json file, add the Azure Cosmos DB SQL connection settings:
"CosmosDbSettings": { "EndpointUri": "<YOUR_COSMOS_DB_ENDPOINT_URI>", "PrimaryKey": "<YOUR_COSMOS_DB_PRIMARY_KEY>", "DatabaseName": "<YOUR_COSMOS_DB_DATABASE_NAME>", "ContainerName": "<YOUR_COSMOS_DB_CONTAINER_NAME>" }
Step 3: Go to azure portal https://portal.azure.com/
- Go to create resource.
- Search Cosmos DB.
- Create Cosmos DB SQL.
- Go To Data Explore And Click To Create Container.
- Add name of database, container and set Id to Partition Id.
- Click OK button our database and container is ready to use.
- Copy and pate the Database and Container Name in appsettings.json file.
- To get EndpointUri and Primary key click on key from left menu.
Step 4: Create a TodoItem model class that represents the data you want to store in Cosmos DB.
public class TodoItem { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("isCompleted")] public bool IsCompleted { get; set; } }
Step 5: Create a repository class Create a repository class that handles the CRUD operations with Azure Cosmos DB.
public class TodoRepository { private readonly Container _container; public TodoRepository(IConfiguration configuration) { var cosmosDbSettings = configuration.GetSection("CosmosDbSettings").Get<CosmosDbSettings>(); var cosmosClient = new CosmosClient(cosmosDbSettings.EndpointUri, cosmosDbSettings.PrimaryKey); var database = cosmosClient.GetDatabase(cosmosDbSettings.DatabaseName); _container = database.GetContainer(cosmosDbSettings.ContainerName); } public async Task<IEnumerable<TodoItem>> GetTodoItems() { var sqlQuery = new QueryDefinition("SELECT * FROM c"); var queryResultSetIterator = _container.GetItemQueryIterator<TodoItem>(sqlQuery); var todoItems = new List<TodoItem>(); while (queryResultSetIterator.HasMoreResults) { var currentResultSet = await queryResultSetIterator.ReadNextAsync(); todoItems.AddRange(currentResultSet); } return todoItems; } public async Task<TodoItem> GetTodoItemById(string id) { var response = await _container.ReadItemAsync<TodoItem>(id, new PartitionKey(id)); return response.Resource; } public async Task<TodoItem> CreateTodoItem(TodoItem todoItem) { var response = await _container.CreateItemAsync(todoItem, new PartitionKey(todoItem.Id)); return response.Resource; } public async Task<TodoItem> UpdateTodoItem(TodoItem todoItem) { var response = await _container.UpsertItemAsync(todoItem, new PartitionKey(todoItem.Id)); return response.Resource; } public async Task DeleteTodoItem(string id) { await _container.DeleteItemAsync<TodoItem>(id, new PartitionKey(id)); }
Step 6: Create API endpoints Create API endpoints in your controller to handle the CRUD operations
using AzureCosmosDb.Models; using AzureCosmosDb.Repository; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace AzureCosmosDb.Controllers { [Route("api/[controller]")] [ApiController] public class TodoController : ControllerBase { private readonly TodoRepository _repository; public TodoController(TodoRepository repository) { _repository = repository; } [HttpGet] public async Task<IActionResult> GetTodoItems() { var todoItems = await _repository.GetTodoItems(); return Ok(todoItems); } [HttpGet("{id}")] public async Task<IActionResult> GetTodoItem(string id) { var todoItem = await _repository.GetTodoItemById(id); if (todoItem == null) return NotFound(); return Ok(todoItem); } [HttpPost] public async Task<IActionResult> CreateTodoItem(TodoItem todoItem) { todoItem.Id = Guid.NewGuid().ToString(); var createdItem = await _repository.CreateTodoItem(todoItem); return CreatedAtAction(nameof(GetTodoItem), new { id = createdItem.Id }, createdItem); } [HttpPut("{id}")] public async Task<IActionResult> UpdateTodoItem(string id, TodoItem todoItem) { var existingItem = await _repository.GetTodoItemById(id); if (existingItem == null) return NotFound(); todoItem.Id = existingItem.Id; var updatedItem = await _repository.UpdateTodoItem(todoItem); return Ok(updatedItem); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteTodoItem(string id) { var existingItem = await _repository.GetTodoItemById(id); if (existingItem == null) return NotFound(); await _repository.DeleteTodoItem(id); return NoContent(); } } }
Step 7: Configure dependency injection in Program.cs
builder.Services.Configure<CosmosDbSettings>(builder.Configuration.GetSection("CosmosDbSettings")); builder.Services.AddSingleton<TodoRepository>();
Step 8: Run the application