Azure Cosmos DB CRUD using SQL API

In this post we can create a Web API sample using Cosmos DB.

(this is similar to the MVC Sample of MS)

Step 1: Create ASP.NET Core web application


Step 2: Choose API


Step 3: Add Controller

Name it as ItemController


Step 4: Add Nuget Package


Step 5: Create Class to represent Item

namespace CosmosDB_WebAPI.Models
     public class Item
         [JsonProperty(PropertyName = “id”)]
         public string Id { get; set; }

        [JsonProperty(PropertyName = “name”)]
         public string Name { get; set; }

        [JsonProperty(PropertyName = “description”)]
         public string Description { get; set; }

        [JsonProperty(PropertyName = “isComplete”)]
         public bool Completed { get; set; }

Step 6: Modify Controller Code

Add the following content to the ItemConroller to include GET, POST, PUT, DELETE functionalities.

namespace CosmosDB_WebAPI.Controllers
     public class ItemController : ControllerBase
         private readonly ICosmosDbService _cosmosDbService;
         public ItemController(ICosmosDbService cosmosDbService)
             _cosmosDbService = cosmosDbService;

        // GET api/values
         public async Task<IEnumerable<Item>> Get()
             return await _cosmosDbService.GetItemsAsync(“SELECT * FROM c”);

        // POST api/values
         public async void Post([FromBody] Item item)
             item.Id = Guid.NewGuid().ToString();
             await _cosmosDbService.AddItemAsync(item);

        // PUT api/values/5
         public async void Put(string id, [FromBody] Item item)
             await _cosmosDbService.UpdateItemAsync(id, item);

        // DELETE api/values/5
         public async void Delete(string id)
             await _cosmosDbService.DeleteItemAsync(id);
Step 7: Modify Config class

Configuration file below.

   “AllowedHosts”: “*”,
   “CosmosDb”: {
     “Account”: “https://localhost:8081″,
     “Key”: “C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==”,
     “DatabaseName”: “Tasks”,
     “ContainerName”: “Items”

Step 8: Run the application

Step 9: Test with Postman


GET https://localhost:44364/api/item

POST https://localhost:44364/api/item

     “name”: “Item 2”,
     “description”: “Description 2”,
     “isComplete”: true

PUT https://localhost:44364/api/item/1

     “id”: “1”,
     “name”: “Item (modified)”,
     “description”: “Description (modified)”,
     “isComplete”: true

DELETE https://localhost:44364/api/item/566b8151-3fc4-4138-8a2f-22b6939ee60a


You can download the sample here.


How to Deploy Angular Application to Azure App Service?

In this post we can see how to deploy an Angular Application into Azure App Service.

Create Angular App

  1. Install Node.js from
  2. Open Command Prompt
  3. Run command npm install -g @angular/cli
  4. Create Project ng new AngularAAD
  5. Go inside folder & Run command ng serve
  6. Open the website http://localhost:4200


Build the Angular App using command:

ng build –prod

Now you should get the dist folder which we need for deployment.

Create Azure App Service

Go to Azure Portal > App Services > Create New > Choose the version depending on the Node Version.


Run command node to get the version


Choose Operating System > Windows

Click the Create button. Wait for the creation to complete.

Go to Advanced Services (KUDU Console) of the App Service


Open CMD window & Go to wwwroot folder.

Copy the contents of dist folder to it.  (Drag & Drop from Windows Explorer to Browser)image

Test Deployment

Now you can Browse the App Service URL from the main page.

You should get the page displayed as below.


Cosmos DB–Choosing the right Model

Cosmos DB offer multiple models as below:

  • Document Model with SQL API
  • MongoDB Model with MongoDB API
  • Cassandra Model with Cassandra API
  • Table Model with Table API
  • Graph Model with Gremlin API

In this article we can see which model to choose based on the requirement.

Note As informed previously we are making a Choice of CosmosDB here due to Dynamic Schema requirement & Geo-replication.

Document Model with SQL API

If you are starting with a new project which requires storage of similar items, schema changes a lot, then SQL API is the best choice.

MongoDB with MongoDB API

If you are Migrating from existing MongoDB which have Investments of MongoDB Queries then MongoDB API is the best choice.

Cassandra Model with Cassandra API

If your project requires Web Analytics capabilities, then Cassandra API is the right choice.

Table Model with Table API

If your data consists of Key-Value pairs OR if you wanted to Migrate data from Azure Table Storage, then Table Model API would be right choice.

    • Cosmos DB (access based pricing) is Cheaper than Table Storage (size based pricing) depending on the case

Graph Model with Gremlin API

If you have relationships between data, then Graph Model is the best choice.

Example: Amazon wanted to show Product Recommendations like customer who bought LG TV 46” also bought another product TV Stand 46”

graph.V().hasLabel(‘product’).has(‘productName’, ‘LG TV’).addE(‘boughtWith’).to(g.V().hasLabel(‘product’).has(‘productName’, ‘TV Stand’))

CosmosDB–Schemaless Scenario

As discussed earlier, the Decision for choosing CosmosDB rather than SQL Server is mostly one of the following:

  • Schemaless Advantage
  • Geo Replication

In this post we can explore the same with few scenarios.

Player Table

Let us think of a Table named Player in SQL Server.  There will be properties like following:

  • ID
  • Name
  • Age
  • Address

Requirement 1

Now, the Player table NEED TO support both Football player & Cricket player.

We resolve this by adding a Type column to differentiate between the players.


Requirement 2

The requirement changed that:

  • The Football Player should have a Goals column of type int
  • The Cricket Player should have a Run Rate column of type float

We resole this by adding 2 more columns. 


Problems in Design

As you can see, there are few problems in current design:

  • There is unwanted column GOALS being allocated for CRICKET Player
  • There is unwanted column RUN RATE being allocated for FOOTBALL Player

The problem is more complicated when the FUTURE REQUIREMENT to support Tennis Player, Badminton Player also comes through.

How COSMOS DB resolves this issue?

Cosmos DB resolves this issue by using only required columns.


“name”: “John”,

“age”: “30”,

“type”: “Football”,

“goals”: 4,



“name”: “Kevin”,

“age”: “25”,

“type”: “Cricket”,

“runrate”: 5.3



In this post we have observed the Schemaless advantage of Cosmos DB.

401 Unauthorized Error–Azure Active Directory (AD)

Here I am listing down all the possible solutions for 401 Unauthorized Error during AAD configuration for your App Service or Resources.


The scenario can be like this:

  • You are able to Authenticate & Get a Valid Token
  • While presenting the Token for service access the Error 401 Unauthorized is happening

Solution 1: Ensure Resource Parameter

Ensure that while requesting the Authentication Token you are specifying the resource parameter.  Without the parameter you will still get the token but the 401 Error will occur as there is no valid resource.


Solution 2: Ensure App ID URI mentioned in the Service

Go to App Services > Authentication blade > Advanced Settings


Solution 3: Delete & Create new App Registration

Some of the configuration errors will be tricky to find – especially in restricted access production environments.  So you can try following:

  • Delete the App Registration
  • Create new App Registration
  • Set the new App Registration parameters in App Service

Solution 4: View Application Logs

Go to Log Streaming to view the Application Logs.


You can search on the Detailed error code (401.83) OR IDX10214 error code for more details.

Solution 5: View Kudu Logs

You can see the Authentication Token is passed or not through the Kudu > Debug Console > CMD > W3SVC Logs.



In this post we have seen how to troubleshoot AAD Authorization Error.  If you find another solution not listed here, please comment below so I can update back in the article.  Help us to Help you!


Testing with Postman