wasAsked.

How do you connect webapi appln to cosmosdb?

Wipro · Role not specified · technical

Published

Year not specified · Azure

Community answers

Posted by wasAsked editorial collection

Use the Azure Cosmos DB .NET SDK (Microsoft.Azure.Cosmos), or EF Core's Cosmos provider if you prefer EF. 1. Register a singleton CosmosClient CosmosClient is thread-safe and manages connections; create it once per application. builder.Services.AddSingleton(sp => new CosmosClient( builder.Configuration["Cosmos:Endpoint"], new DefaultAzureCredential(), // managed identity, no keys in config new CosmosClientOptions { ApplicationName = "orders-api", SerializerOptions = new() { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase } })); For managed identity, assign the app the Cosmos DB Built-in Data Contributor role with a data-plane role assignment (az cosmosdb sql role assignment create). Account keys work too but should be stored in Key Vault and rotated. 2. Repository using a container public sealed class OrderRepository(CosmosClient client) { private readonly Container _container = client.GetContainer("Shop", "Orders"); public async Task<Order?> GetAsync(string id, string customerId, CancellationToken ct) { try { var response = await _container.ReadItemAsync<Order>(id, new PartitionKey(customerId), cancellationToken: ct); return response.Resource; // point read: cheapest operation (about 1 RU for 1 KB) } catch (CosmosException e) when (e.StatusCode == HttpStatusCode.NotFound) { return null; } } public Task CreateAsync(Order order, CancellationToken ct) => _container.CreateItemAsync(order, new PartitionKey(order.CustomerId), cancellationToken: ct); public async Task<List<Order>> ByCustomerAsync(string customerId, CancellationToken ct) { var query = new QueryDefinition("SELECT * FROM c WHERE c.customerId = @c").WithParameter("@c", customerId); var results = new List<Order>(); using var it = _container.GetItemQueryIterator<Order>(query, requestOptions: new() { PartitionKey = new PartitionKey(customerId) }); while (it.HasMoreResults) results.AddRange(await it.ReadNextAsync(ct)); return results; } } 3. Design considerations - Choose the partition key carefully (high cardinality, matches common queries, even distribution) — it is hard to change later. - Prefer point reads and single-partition queries; cross-partition queries cost more Request Units. - Use continuation tokens for paging, ETags for optimistic concurrency (IfMatchEtag), and transactional batches within a partition. - Handle 429 (throttling): the SDK retries automatically; monitor RU consumption and use autoscale throughput. - Use the Cosmos DB emulator or a dev account for local development, and enable diagnostics logging for slow requests.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics