DEV Community

Cover image for Create a Web API with ASP.NET Core 7 and MongoDB
Armin Afazeli
Armin Afazeli

Posted on

11 1 1 1 1

Create a Web API with ASP.NET Core 7 and MongoDB

In this tutorial, we will learn how to create a Web API using ASP.NET Core 7 and MongoDB. ASP.NET Core is a cross-platform, high-performance framework for building modern, cloud-based, Internet-connected applications. MongoDB is a popular NoSQL database that stores data in JSON-like documents, which makes it perfect for working with Web APIs.

We will create a simple CRUD (Create, Read, Update, Delete) API for managing a list of products. By the end of this tutorial, you'll have a fully functional Web API that you can use as a starting point for your own projects.

Prerequisites:

  1. Rider, Visual Studio or Visual Studio Code with .NET 7 or higher.
  2. MongoDB installed or MongoDB Atlas account (cloud-based MongoDB service).
  3. Basic knowledge of C# and ASP.NET Core.

Steps:

  • Create a new ASP.NET Core Web API project:

Open Visual Studio and create a new project. Select "ASP.NET Core Web Application" and name it "ProductsAPI". On the next screen, choose the "API" template and make sure you have .NET 7 selected as the target framework.

  • Install the MongoDB driver:

To interact with MongoDB, we need to install the MongoDB .NET driver. Open the terminal and navigate to your project folder. Run the following command to install the package:

dotnet add package MongoDB.Driver
Enter fullscreen mode Exit fullscreen mode
  • Configure MongoDB connection:

Open the "appsettings.json" file and add a "MongoDBSettings" section with the "ConnectionString" and "DatabaseName" properties:

{
  "MongoDBSettings": {
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "ProductsDB"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
Enter fullscreen mode Exit fullscreen mode
  • Create MongoDB settings model:

Create a new folder called "Models" in your project, and inside it, create a new class named "MongoDBSettings.cs". Define the properties for the MongoDB connection settings:

public class MongoDBSettings
{
    public string ConnectionString { get; set; }
    public string DatabaseName { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
  • Set up MongoDB context:

Create a new folder called "Data" in your project, and inside it, create a new class named "MongoDBContext.cs". This class will handle the database connection and provide access to the collections:

public class MongoDBContext
{
    private readonly IMongoDatabase _database;

    public MongoDBContext(string connectionString, string databaseName)
    {
        var client = new MongoClient(connectionString);
        _database = client.GetDatabase(databaseName);
    }

    public IMongoCollection<Product> Products => _database.GetCollection<Product>("Products");
}
Enter fullscreen mode Exit fullscreen mode
  • Create the Product model:

Inside the "Models" folder, create a Product model class named "Product.cs". Define the properties for the product:

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class Product
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

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

    [BsonElement("Category")]
    public string Category { get; set; }

    [BsonElement("Price")]
    public decimal Price { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
  • Update the Program.cs file:

Replace the content of the Program.cs file with the following code:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using ProductsAPI.Models;
using ProductsAPI.Data;
using MongoDB.Driver;

var builder = WebApplication.CreateBuilder(args);

// Register services here
builder.Services.Configure<MongoDBSettings>(builder.Configuration.GetSection(nameof(MongoDBSettings)));

builder.Services.AddSingleton<MongoDBContext>(serviceProvider =>
{
    var settings = serviceProvider.GetRequiredService<IOptions<MongoDBSettings>>().Value;
    return new MongoDBContext(settings.ConnectionString, settings.DatabaseName);
});

// Add controllers
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.Run();

Enter fullscreen mode Exit fullscreen mode
  • Create the ProductsController:

Create a new folder called "Controllers" in your project, and inside it, create a new class named "ProductsController.cs". Implement the CRUD operations for the Product model:

using Microsoft.AspNetCore.Mvc;
using ProductsAPI.Data;
using ProductsAPI.Models;
using MongoDB.Driver;
using System.Collections.Generic;
using System.Threading.Tasks;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly MongoDBContext _context;

    public ProductsController(MongoDBContext context)
    {
        _context = context;
    }

    [HttpGet]
    public async Task<IEnumerable<Product>> Get()
    {
        return await _context.Products.Find(_ => true).ToListAsync();
    }

    [HttpGet("{id}")]
    public async Task<ActionResult<Product>> Get(string id)
    {
        var product = await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();

        if (product == null)
        {
            return NotFound();
        }

        return product;
    }

    [HttpPost]
    public async Task<ActionResult<Product>> Create(Product product)
    {
        await _context.Products.InsertOneAsync(product);
        return CreatedAtRoute(new { id = product.Id }, product);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Update(string id, Product productIn)
    {
        var product = await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();

        if (product == null)
        {
            return NotFound();
        }

        await _context.Products.ReplaceOneAsync(p => p.Id == id, productIn);

        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> Delete(string id)
    {
        var product = await _context.Products.Find(p => p.Id == id).FirstOrDefaultAsync();

    if (product == null)
    {
        return NotFound();
    }

    await _context.Products.DeleteOneAsync(p => p.Id == id);

    return NoContent();
}

Enter fullscreen mode Exit fullscreen mode

Now you have a fully functional Web API with ASP.NET Core 7 and MongoDB. You can test the API using tools like Postman or Swagger. To add Swagger support, follow these steps:

  • Add Swagger support:

Install the required NuGet packages:

dotnet add package Swashbuckle.AspNetCore
Enter fullscreen mode Exit fullscreen mode

Add the following code in the Program.cs file, under the builder.Services.AddControllers(); line:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "ProductsAPI", Version = "v1" });
});
Enter fullscreen mode Exit fullscreen mode

Add the Swagger middleware in the Program.cs file, after the app.UseRouting(); line:

app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ProductsAPI v1"));

Enter fullscreen mode Exit fullscreen mode
  • Test the API:

Run the application and navigate to the Swagger UI by visiting https://localhost:/swagger in your browser. You should see the API documentation and be able to test the endpoints directly from the Swagger UI.

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay