Building REST APIs is one of the most common tasks for modern backend developers. Whether you're creating an e-commerce platform, a content management system, or a mobile application backend, you'll need a reliable way to create, read, update, and delete data (commonly known as CRUD operations).
MongoDB is a popular NoSQL database that stores data in flexible JSON-like documents, making it an excellent choice for applications that require scalability and rapid development. Combined with .NET 10 and ASP.NET Core Web API, MongoDB provides a powerful and efficient stack for building modern web services.
In this beginner-friendly guide, you'll learn how to build a REST API with .NET 10 and MongoDB from scratch. We'll walk through setting up a new ASP.NET Core Web API project, configuring a MongoDB connection, creating data models, and implementing the four essential MongoDB CRUD operations using RESTful endpoints.
By the end of this tutorial, you'll have a fully functional API that can:- Create new records using HTTP POST requests
- Retrieve records using HTTP GET requests
- Update existing records using HTTP PUT requests
- Delete records using HTTP DELETE requests
We'll also use Swagger to test our endpoints and discuss some best practices for building maintainable and scalable MongoDB APIs in .NET.
Before diving to setting up our development environment and creating a new .NET 10 Web API project. Lets understand few things.
What is a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a way for applications to communicate with each other over HTTP. It exposes endpoints that allow clients, such as web applications or mobile apps, to create, retrieve, update, and delete data.
REST APIs use standard HTTP methods to perform operations:- GET – Retrieve data
- POST – Create new data
- PUT – Update existing data
- DELETE – Remove data
For example, a product API might expose the following endpoint:
GET /api/products
This request returns a list of products, usually in JSON format.REST APIs are popular because they are simple, scalable, and work across different platforms and programming languages. In this tutorial, we'll use .NET 10 and MongoDB to build a REST API that performs CRUD (Create, Read, Update, Delete) operations.
Before proceeding with CRUD operations, it is recommended to have a basic understanding of MongoDB concepts such as databases, collections, and document structure.
Prerequisites
Before proceeding, ensure you have:- .NET 10 SDK installed MongoDB installed locally or MongoDB Atlas account Visual Studio 2022 / VS Code Basic understanding of MongoDB CRUD operations
If you're new to MongoDB configuration, check out the previous article "Get Started with MongoDB Database in .NET. Core"
I covered the fundamentals of MongoDB, including:- What MongoDB is and how it differs from traditional relational databases.
- Installing and configuring MongoDB.
- Creating and selecting databases and many more.
Create a New Web API Project
Follow these steps to create a new ASP.NET Core Web API project using Microsoft Visual Studio.- Launch Visual Studio: Open Visual Studio 2022 (or a later version) from your system.
- Create a New Project: On the Visual Studio start screen, click Create a new project.
- Select the Web API Template
- Search for ASP.NET Core Web API.
- Select the ASP.NET Core Web API template.
- Click Next.
- Configure the Project
- Project Name:
MongoDbRestApi - Location: Choose your preferred folder.
- Solution Name:
MongoDbRestApi - Click Next.
- Project Name:
- Configure Additional Settings
- Framework: Select .NET 10 (or the latest available version).
- Authentication Type: None
- Configure for HTTPS: Checked
- Enable OpenAPI Support (Swagger): Checked
- Use Controllers: Checked
- Click Create.
- Explore the Generated Project Structure
Visual Studio generates a starter Web API project with files similar to:
MongoDbRestApi │ ├── Controllers ├── Properties ├── appsettings.json ├── Program.cs └── MongoDbRestApi.csproj - Run the Application
Press F5 or click the Start button. Visual Studio will:
- Build the project.
- Launch the API.
- Open the Swagger UI automatically in your browser.
Swagger provides an interactive interface for testing your API endpoints without using external tools such as Postman.https://localhost:xxxx/swagger
Now that your ASP.NET Core Web API project is ready, the next step is to install the MongoDB Driver package and configure the MongoDB connection settings.
check out the previous article "Get Started with MongoDB Database in .NET. Core" for Installing and configuring MongoDB in system level.
Configure MongoDB Settings in REST API
Add the following configuration toappsettings.json.
{
"MongoDbSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "ProductDb",
"CollectionName": "Products"
}
}
Create the Product Model
A model represents the structure of the data that will be stored and retrieved from the database. Since our API will manage product information, we need to create a Product model that defines the properties of a product document in MongoDB. Create a new file named Product.cs inside the Models folder with below code.
Product.cs
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace MongoDbRestApi.Models;
public class Product
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public string Category { get; set; } = string.Empty;
}
Understanding the Model Properties
- [BsonId] identifies this property as the primary key of the MongoDB document.
- MongoDB automatically generates a unique ObjectId for each document.
- [BsonRepresentation(BsonType.ObjectId)] allows the ObjectId to be represented as a string in your C# code, making it easier to work with API requests and responses.
{
"_id": "6852a4f7b9f3d8a1e6c7d9f2",
"name": "Laptop",
"price": 1200,
"category": "Electronics"
}
Create MongoDB Service
Now that we have defined the Product model, the next step is to create a service that handles all interactions with MongoDB.
Instead of placing database logic directly inside the controller, we'll create a dedicated ProductService class. This service will be responsible for performing all CRUD operations on the Products collection.
Create a new folder named Services and add a file calledProductService.cs.
using MongoDB.Driver;
using MongoDbRestApi.Models;
namespace MongoDbRestApi.Services;
public class ProductService
{
private readonly IMongoCollection<Product> _products;
public ProductService(IConfiguration configuration)
{
var client = new MongoClient( configuration["MongoDbSettings:ConnectionString"]);
var database = client.GetDatabase( configuration["MongoDbSettings:DatabaseName"]);
_products = database.GetCollection<Product>(configuration["MongoDbSettings:CollectionName"]);
}
public async Task<List<Product>> GetAsync() => await _products.Find(_ => true).ToListAsync();
public async Task<Product?> GetAsync(string id) => await _products.Find(x => x.Id == id).FirstOrDefaultAsync();
public async Task CreateAsync(Product product) => await _products.InsertOneAsync(product);
public async Task UpdateAsync(string id, Product product) => await _products.ReplaceOneAsync(x => x.Id == id, product);
public async Task DeleteAsync(string id) => await _products.DeleteOneAsync(x => x.Id == id);
}
Register Service
After creating the ProductService, we need to register it with ASP.NET Core's Dependency Injection (DI) container. This allows the framework to automatically create and provide an instance of the service whenever it is needed.
Program.cs and add the following line:
builder.Services.AddSingleton<ProductService>();
Your
Program.cs file should look similar to this:
var builder = WebApplication.CreateBuilder(args);
// Register Services
builder.Services.AddSingleton<ProductService>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers(); app.Run();
Create Products Controller
Now that we have created the Product model, ProductService, and registered the service with Dependency Injection, the next step is to create a controller.
A controller is responsible for handling incoming HTTP requests, calling the appropriate service methods, and returning HTTP responses to the client.
Create a new file namedProductsController.cs inside the Controllers folder.
using Microsoft.AspNetCore.Mvc;
using MongoDbRestApi.Models;
using MongoDbRestApi.Services;
namespace MongoDbRestApi.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ProductService _service;
public ProductsController(ProductService service)
{
_service = service;
}
[HttpGet]
public async Task<IActionResult> Get()
{
var products = await _service.GetAsync();
return Ok(products);
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var product = await _service.GetAsync(id);
if (product is null)
return NotFound();
return Ok(product);
}
[HttpPost]
public async Task<IActionResult> Post(Product product)
{
await _service.CreateAsync(product);
return CreatedAtAction( nameof(Get), new { id = product.Id }, product);
}
[HttpPut("{id}")]
public async Task<IActionResult> Put(string id, Product product)
{
var existing = await _service.GetAsync(id);
if (existing is null)
return NotFound();
product.Id = id;
await _service.UpdateAsync(id, product);
return NoContent();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
var existing = await _service.GetAsync(id);
if (existing is null)
return NotFound();
await _service.DeleteAsync(id);
return NoContent();
}
}
The ProductsController exposes RESTful endpoints for performing CRUD operations on MongoDB data. It acts as the bridge between client requests and the ProductService, handling HTTP methods such as GET, POST, PUT, and DELETE. By keeping database logic inside the service layer and request handling inside the controller, we achieve a clean, maintainable, and scalable API architecture.
Run the Application
After completing the setup of the model, service, dependency injection, and controller, the final step is to run and test the Web API application.
This step ensures that your ASP.NET Core Web API is correctly configured and properly connected to MongoDB.
You can run the application using any of the following methods:- Press F5 (Run with Debugging)
- Press Ctrl + F5 (Run without Debugging)
- Click the Green Play Button in Visual Studio
Once the application starts successfully, it automatically opens a command window displaying both the HTTP and HTTPS URLs along with their port numbers. Copy the HTTPS URL and open it in a Chrome or other web browser.
You will see the Swagger UI at a URL similar to the following:
https://localhost:xxxx/swagger
Swagger provides a user-friendly interface to test all your API endpoints without needing external tools like Postman. if you don't see swagger add the following code in Program.cs file
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
app.UseSwagger();
app.UseSwaggerUI();
Make sure that you have not unchecked the Opeai checkbox. After adding the above code your Program.cs file should look similar to this:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register Services
builder.Services.AddSingleton<ProductService>();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.MapControllers(); app.Run();
Summary
In this article, we built a REST API using ASP.NET Core and MongoDB that supports complete CRUD operations. We learned how to:- Configure MongoDB in .NET
- Create a service layer
- Build RESTful endpoints
- Perform Create, Read, Update, and Delete operations
- Test APIs using Swagger
This forms the foundation for building real-world applications where frontend clients communicate with MongoDB through REST APIs.
Thanks