Create WebAPI

Create a WebAPI Project to consume data from Cosmos DB

Create project

Let us create an asp.net web api project inside a folder called CosmosDemo by running the following command:

dotnet new webapi

Create Item model in a folder called Models

At the root of your project, create the Models folder and a class called Item inside it. Replace the contents of it with the code shown below:

using Newtonsoft.Json;

namespace CosmosDemo.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; }
}

Create a folder called Services

Inside the folder define an interface ICosmosDbService as given in the code below:

In the same folder create a class CosmosDbService that implements the interface as shown below:

Replace Program.cs

Replace Program.cs class with the code shown below:

Add ItemsController

In the Controllers folder create a class ItemsController as shown below:

Modify appsettings.json

Replace the contents of appsettings.json file with the one shown below:

Remove others

You might want to remove weather controller and weather model which was created as part of the template!

Alternatively Download repo

Alternatively, you can download this project from my repository and only add the Account and Key values in appsettings.json, with your values:

https://github.com/ravirammysore/CosmosDemo

Last updated