How to Build RESTful CRUD APIs with .NET and Azure Cosmos DB


To build RESTful CRUD APIs with .NET and Azure Cosmos DB, you can follow these steps:

Prerequisites

  1. Install .NET SDK: Ensure the latest .NET SDK is installed on your machine.
  2. Set Up Azure Cosmos DB:
    • Create an Azure Cosmos DB account using the Azure Portal.
    • Create a database and container for your API.
  3. Tools:
    • Visual Studio or Visual Studio Code.
    • Azure CLI for interacting with Azure services.

Step 1: Create a .NET Web API Project

  1. Open a terminal and run the following command:
    dotnet new webapi -n CosmosApi
    cd CosmosApi
  2. Install the Azure Cosmos DB SDK:
    dotnet add package Microsoft.Azure.Cosmos

Step 2: Configure Azure Cosmos DB in the Project

  1. Add the connection string and database details in appsettings.json:

    {
      "CosmosDb": {
        "AccountEndpoint": "<Your-Cosmos-Account-Endpoint>",
        "AccountKey": "<Your-Cosmos-Account-Key>",
        "DatabaseName": "YourDatabaseName",
        "ContainerName": "YourContainerName"
      }
    }
    
  2. Create a CosmosDbService to interact with Azure Cosmos DB:

    using Microsoft.Azure.Cosmos;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    public interface ICosmosDbService
    {
        Task<IEnumerable<T>> GetItemsAsync<T>(string query);
        Task<T> GetItemAsync<T>(string id, string partitionKey);
        Task AddItemAsync<T>(T item);
        Task UpdateItemAsync<T>(string id, T item);
        Task DeleteItemAsync<T>(string id, string partitionKey);
    }
    
    public class CosmosDbService : ICosmosDbService
    {
        private readonly Container _container;
    
        public CosmosDbService(CosmosClient dbClient, string databaseName, string containerName)
        {
            _container = dbClient.GetContainer(databaseName, containerName);
        }
    
        public async Task<IEnumerable<T>> GetItemsAsync<T>(string query)
        {
            var queryDefinition = new QueryDefinition(query);
            var queryResultSetIterator = _container.GetItemQueryIterator<T>(queryDefinition);
            var results = new List<T>();
    
            while (queryResultSetIterator.HasMoreResults)
            {
                var response = await queryResultSetIterator.ReadNextAsync();
                results.AddRange(response);
            }
    
            return results;
        }
    
        public async Task<T> GetItemAsync<T>(string id, string partitionKey)
        {
            return await _container.ReadItemAsync<T>(id, new PartitionKey(partitionKey));
        }
    
        public async Task AddItemAsync<T>(T item)
        {
            await _container.CreateItemAsync(item);
        }
    
        public async Task UpdateItemAsync<T>(string id, T item)
        {
            await _container.UpsertItemAsync(item, new PartitionKey(id));
        }
    
        public async Task DeleteItemAsync<T>(string id, string partitionKey)
        {
            await _container.DeleteItemAsync<T>(id, new PartitionKey(partitionKey));
        }
    }

Step 3: Register the Cosmos DB Service in Program.cs

Modify Program.cs to register CosmosDbService:

using Microsoft.Azure.Cosmos;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

// Configure Cosmos DB Service
builder.Services.AddSingleton<ICosmosDbService>(serviceProvider =>
{
    var cosmosDbOptions = builder.Configuration.GetSection("CosmosDb");
    var cosmosClient = new CosmosClient(cosmosDbOptions["AccountEndpoint"], cosmosDbOptions["AccountKey"]);
    return new CosmosDbService(cosmosClient, cosmosDbOptions["DatabaseName"], cosmosDbOptions["ContainerName"]);
});

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

Step 4: Create API Endpoints

  1. Add a model class:

    public class Item
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string PartitionKey { get; set; }
    }
  2. Create a Controller:

    using Microsoft.AspNetCore.Mvc;
    
    [Route("api/[controller]")]
    [ApiController]
    public class ItemsController : ControllerBase
    {
        private readonly ICosmosDbService _cosmosDbService;
    
        public ItemsController(ICosmosDbService cosmosDbService)
        {
            _cosmosDbService = cosmosDbService;
        }
    
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            var items = await _cosmosDbService.GetItemsAsync<Item>("SELECT * FROM c");
            return Ok(items);
        }
    
        [HttpGet("{id}/{partitionKey}")]
        public async Task<IActionResult> Get(string id, string partitionKey)
        {
            var item = await _cosmosDbService.GetItemAsync<Item>(id, partitionKey);
            return Ok(item);
        }
    
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] Item item)
        {
            await _cosmosDbService.AddItemAsync(item);
            return CreatedAtAction(nameof(Get), new { id = item.Id, partitionKey = item.PartitionKey }, item);
        }
    
        [HttpPut("{id}")]
        public async Task<IActionResult> Put(string id, [FromBody] Item item)
        {
            if (id != item.Id) return BadRequest();
    
            await _cosmosDbService.UpdateItemAsync(id, item);
            return NoContent();
        }
    
        [HttpDelete("{id}/{partitionKey}")]
        public async Task<IActionResult> Delete(string id, string partitionKey)
        {
            await _cosmosDbService.DeleteItemAsync<Item>(id, partitionKey);
            return NoContent();
        }
    }

Step 5: Run and Test

  1. Run the API:
    dotnet run
  2. Test the endpoints using a tool like Postman or curl.

Step 6: Deploy to Azure (Optional)

  1. Publish the app to Azure App Service:
    dotnet publish -c Release
    az webapp deploy --name <your-webapp-name> --resource-group <your-resource-group> --src-path ./bin/Release/net6.0/publish
    
  2. Configure the app settings in the Azure Portal to include your Cosmos DB credentials.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example