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:
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
2. Select ASP.NET Core Web API template.
3. Give a project name and click on next.
4. Click on create button.
5. Your Web API is ready.
Section 4: Creating Azure Cosmos DB and Container.
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.
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.
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; }
}
[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);
}
}
}
public interface IStudentService
{
Task<Student> getStudentByIdAsync(int classId, int id);
Task<Student> createStudentAsync(Student student);
}
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:
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
Full Stack Developer
10 个月Great explanation Meghana Bandi thanks for the tutorial!
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
Software Engineer @Ariqt International
11 个月That's a detailed explanation Meghana Bandi