Build .NET Web API with Azure Cosmos Db.
Azure Cosmos DB

Build .NET Web API with Azure Cosmos Db.

Introduction:

Hi dear learners, in this article we are going to know about building a .NET Web Api with Azure Cosmos DB.

we are going to travel through the following path:

  1. Understanding Azure Cosmos DB
  2. Introducing .NET Web API framework
  3. Setting up a new .NET Web API project in Visual Studio
  4. Creating Azure Cosmos DB and Container
  5. Integrating Azure Cosmos DB with the .NET Web API


Section 1: Understanding Azure Cosmos DB

Azure Cosmos DB is a super flexible and speedy database service provided by Microsoft, designed to work with huge amounts of data spread across the globe. It's like a magic box that can store all kinds of data, not just one type, making it super versatile. Whether you're dealing with numbers, text, or even more complex data, Cosmos DB can handle it. Plus, it's built to be super fast, giving you the information you need almost instantly, no matter where you are in the world. This makes it a go-to choice for businesses and apps that need to work fast and reliably for users everywhere.


Section 2: Introducing .NET Web API framework.

The .NET Web API framework is a handy tool from Microsoft that lets developers create web services that can talk to browsers, mobile devices, or other web-based applications. Think of it as a bridge that helps different pieces of software communicate over the internet or intranet, using a common web language everyone understands. It's designed to be simple yet powerful, allowing for the creation of APIs (Application Programming Interfaces) that can send data back and forth, making it a great choice for building services that can be accessed from various devices and platforms. Whether you're looking to build a web app, a mobile app backend, or any service that needs to interact over the web, .Net Web API provides the building blocks to make it happen efficiently.


Section 3: Setting up a new .NET Web API project in Visual Studio

  1. Create a new project in Visual Studio 2022.

click on create new project

2. Select ASP.NET Core Web API template.

3. Give a project name and click on next.

Giving a project name

4. Click on create button.

5. Your Web API is ready.


Section 4: Creating Azure Cosmos DB and Container.

  1. Open Azure and click on create a resource.

2. Search for Azure Cosmos DB

3. Select Azure Cosmos DB card.

4. Click on create button.

5. Select Azure Cosmos DB according to your requirement.

For .NET Web APIs, we use Azure Cosmos Db for NoSQL as it has support for .NET client libraries with familiar SQL query language.

Once you click on create button, you will be directed to a page similar to the below one.

6. Select your Azure subscription and resource group. Provide an account name which should be unique. This will be the name of your Azure Cosmos DB account.

7. Select the location and leave the default settings for remaining options. Click on Review + Create.

Now, check the settings and click on create.

The Cosmos DB is getting ready for you.

8. Now click on Go to resource button to access the cosmos DB.

You can create a sample container with some sample data called as Items as shown. After that you can also download a sample .NET app connected to that container to build and run it.

9. As we are going to build a .NET app with cosmos DB, first let us create a container and add some records.

Click on Data Explorer in the side bar to view all the containers.

Click on add new container in the menu. Provide Database Id (database name), select appropriate throughput option according to your data usage.

I am giving the Container Id (table name) as Student and Partition key as classId, so that I can have partitions based on classes and have multiple students in each class(partition).


10. Click on OK to create a new container to store student data.


Section 5: Integrating Azure Cosmos DB with the .NET Web API

1. Navigate to Key in the side nav bar and copy the URI and Primary Key.

2. Create folders with required files as shown.

Go to .NET web Api project and open appsettings.json file and add this code.

"CosmosDbSettings": {
  "Uri": "Azure cosmos DB URI",
  "Key": "Azure cosmos DB PRIMARY KEY",
  "DbName": "Azure cosmos DB database id"
}        

Replace the strings with corresponding values for URI, PRIMARY KEY and DbName with database id given while creating the database (mycosmosdb)

3. Add the following code to program.cs file in your project.

  • Register the interface and implementation of Student service. And also, the cosmos client and container as shown below.

builder.Services.AddScoped<IStudentService, StudentService>();        
var configuration = builder.Configuration;

builder.Services.AddSingleton<CosmosClient>((provider) =>
{
    var endpointUri = configuration["CosmosDbSettings:Uri"];
    var primarykey = configuration["CosmosDbSettings:Key"];
    var databasename = configuration["CosmosDbSettings:DbName"];

    var cosmosClientOptions = new CosmosClientOptions
    {
        ApplicationName = databasename,
    };

    var loggerFactory = LoggerFactory.Create(builder =>
    {
        builder.AddConsole();
    });

    var cosmosClient = new CosmosClient(endpointUri, primarykey, cosmosClientOptions);

    cosmosClient.ClientOptions.ConnectionMode = ConnectionMode.Direct;
  
    return cosmosClient;
});

builder.Services.AddSingleton<Container>(provider =>
{
    var databasename = configuration["CosmosDbSettings:DbName"];
    var containername = "containerid";

    var cosmosClient = provider.GetRequiredService<CosmosClient>();
    return cosmosClient.GetContainer(databasename, containername);
});        

Replace containerid with the name given while creating the database (student).

3. Create models, controllers, and views that interact with Azure Cosmos DB.

  • As we have the Web Api, and the cosmos DB instance is ready it is time to create some models and controller in the web Api.
  • Let us create a simple model called as student which has the following properties.

 public class Student
 {
     [JsonProperty("id")]
     public string Id { get; set; }

     [JsonProperty("studentId")]
     public int StudentId { get; set; }

     [JsonProperty("name")]
     public string Name { get; set; }

     [JsonProperty("classId")]
     public int Class { get; set; }

     [JsonProperty("age")]
     public int Age { get; set; }
 }        

  • Then we have a student controller which contains the HTTP endpoints like GET, POST, PUT, DELETE to perform CRUD operations.
  • Here I have written only two endpoints which are GET and POST to keep it short. You can explore other end points as well.

[Route("api/student")]
[ApiController]
public class StudentController : ControllerBase
{
    private readonly IStudentService _studentService;
    public StudentController(IStudentService  studentService)
    {
        _studentService = studentService;
    }

    [HttpGet("getstudentbyid")]
    public async Task<ActionResult<Student>> GetStudentById(int classId, int id)
    {
        try
        {
            var student = await _studentService.getStudentByIdAsync(classId, id);
            if (student != null)
            {
                return Ok(student);
            }
            return NotFound();
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
        
    }

    [HttpPost]
    public async Task<ActionResult<Student>> CreateStudent([FromBody] Student student)
    {
        try
        {
            var response = await _studentService.createStudentAsync(student);
            if(response != null)
            {
                return Ok(response);
            }
            return BadRequest();
        }
        catch (Exception ex)
        {
            return BadRequest(ex.Message);
        }
    }
}        

  • The controller calls the service methods to perform various operations on data received from the user. Here, we are going to create an Interface called as IStudentService.cs for abstraction and StudentService.cs for respective implementation.

 public interface IStudentService
 {
     Task<Student> getStudentByIdAsync(int classId, int id);
     Task<Student> createStudentAsync(Student student);
 }        

  • In the implementation, we have to include the cosmos client and cosmos container using dependency injection while gives us access to the cosmos container we have created in azure.
  • And IConfiguration to get the value of database name from appsettings.json.

  public class StudentService : IStudentService
  {
      private readonly IConfiguration _configuration;
      private readonly CosmosClient _cosmosClient;
      private readonly Container _studentContainer;
      public StudentService(IConfiguration configuration, CosmosClient cosmosClient, Container studentContainer)
      {
          _configuration = configuration;
          _cosmosClient = cosmosClient;
          _studentContainer = studentContainer;
          var databaseName = configuration["CosmosDbSettings:DbName"];
          var containerName = "Student";
          _studentContainer = cosmosClient.GetContainer(databaseName, containerName);
      }

      public async Task<Student> createStudentAsync(Student student)
      {
          
          student.Id = Guid.NewGuid().ToString();

          var response = await _studentContainer.CreateItemAsync(student, new PartitionKey(student.Class));

          return response.Resource;
      }

      public async Task<Student> getStudentByIdAsync(int studentId, int classId)
      {
          var sqlQueryText = $"SELECT * FROM c WHERE c.studentid = {studentId} AND c.classId = {classId}";

          QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
          FeedIterator<Student> queryResultSetIterator = _studentContainer.GetItemQueryIterator<Student>(queryDefinition, requestOptions: new QueryRequestOptions
          {
              PartitionKey = new PartitionKey(classId)
          });

          List<Student> students = new List<Student>();

          while (queryResultSetIterator.HasMoreResults)
          {
              FeedResponse<Student> currentResultSet = await queryResultSetIterator.ReadNextAsync();
              foreach (Student student in currentResultSet)
              {
                  students.Add(student);
              }
          }

          return students.FirstOrDefault();
      }
        

Now, Our API is ready with Azure Cosmos DB connected to it with working controller.

Conclusion:

  • Congrats on finishing your tour and succeeding in meeting the goal of this article. Take a moment to celebrate your achievement.
  • Using Azure Cosmos DB with a .NET Web API is a smart choice for building fast and versatile web applications. This combo lets your apps store and access data quickly and easily, no matter where your users are. It's great for handling lots of data and users, making your app reliable and speedy. Plus, it's easier for developers to work with, saving time and effort when building and updating your app.
  • Take few more steps to explore further and experiment with different features and capabilities of .NET and Azure Cosmos DB.

References and Further Reading:

Check out this links that helped me to learn about Azure Cosmos which will definitely help you too.

Official Microsoft documentation - Tutorial: Develop an ASP.NET web application with Azure Cosmos DB for NoSQL | Microsoft Learn

Tutorial video - How to build .NET Core 7 Web API using Cosmos DB in an hour | WEB API Crash Course | .NET | LSC - YouTube

Ben Smith

Full Stack Developer

10 个月

Great explanation Meghana Bandi thanks for the tutorial!

Gangapuram vishal

Software Developer 1 @Ariqt International | .NET | C# | Azure | Web APIs | ASP.NET Core | Entity Framework | SQL | Python | HTML | CSS

11 个月

This would be really helpful in our journey of learning

Katta Amuktha Sai Sreeja

Software Engineer @Ariqt International

11 个月

That's a detailed explanation Meghana Bandi

要查看或添加评论,请登录

Meghana Bandi的更多文章

社区洞察

其他会员也浏览了