Building a CRUD Application with Minimal APIs in .NET

Building a CRUD Application with Minimal APIs in .NET

Create a simple CRUD application using Minimal APIs in .NET 6.0

Introduction

The world of web development is constantly evolving, and .NET developers are no strangers to these changes. In recent times, Microsoft has introduced Minimal APIs, a new way of building lightweight, fast, and efficient web APIs. In this blog post, we'll delve into the world of Minimal APIs in .NET, explore their benefits, explore their key features, and build a simple CRUD (Create, Read, Update, Delete) application.

In this tutorial, we'll create a simple CRUD (Create, Read, Update, Delete) application using Minimal APIs in .NET 6.0. We'll also guide you through testing these APIs using Postman.

Note: The same code can be used to create minimal API in .NET 7 too.

What are Minimal APIs?

Minimal APIs are a feature introduced in ASP.NET Core 6.0 that simplifies the process of building lightweight web APIs. They provide a minimalistic way to define and configure endpoints without the need for a full-fledged controller or routing setup. Let's dive into the key features of Minimal APIs:

  1. Lightweight: Minimal APIs eliminate the boilerplate code found in traditional ASP.NET MVC controllers, resulting in cleaner and more concise code.

  2. Fast Startup: They are designed for improved performance and faster application startup times, making them ideal for microservices and serverless architectures.

  3. Declarative Routing: Minimal APIs use attribute-based routing, making it easy to define routes directly on endpoints using attributes like [HttpGet], [HttpPost], etc.

  4. Dependency Injection: You can still use dependency injection to inject services into your Minimal API endpoints, just like in ASP.NET MVC.

Now, let's explore the advantages of Minimal APIs compared to traditional approaches.

Benefits of Minimal APIs

1. Reduced Boilerplate Code

Minimal APIs drastically reduce the amount of boilerplate code needed to create web APIs, making your codebase cleaner and more maintainable.

2. Improved Performance

With their focus on efficient startup times, Minimal APIs are well-suited for modern application architectures, such as microservices, where performance is critical.

3. Declarative Routing

The use of attributes for routing in Minimal APIs simplifies endpoint configuration and enhances code readability.

4. Easy Dependency Injection

You can still leverage the power of dependency injection in Minimal APIs, making it easy to manage and use services within your application.

Getting Started with Minimal APIs

Prerequisites:

  1. .NET SDK 6.0

  2. Visual Studio Code

  3. Postman

Step 1: Create a New Project

Open your terminal and run the following command to create a new .NET 6 Minimal API project:

dotnet new web -n MinimalApiCrud
cd MinimalApiCrud

Step 2: Define a Product Model

Inside your project folder, create a Product.cs file to define the Product model:

// Product.cs
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Step 3: Create the API Endpoints

Open the Program.cs file and define your Minimal API endpoints for CRUD operations

// Program.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;

var builder = WebApplication.CreateBuilder(args);

var products = new List<Product>();

builder.Services.AddSingleton(products);

builder.Services.AddEndpoints(endpoints =>
{
    // Get all products
    endpoints.MapGet("/products", () => products);

    // Get a product by Id
    endpoints.MapGet("/products/{id}", (int id) =>
    {
        var product = products.FirstOrDefault(p => p.Id == id);
        return product is not null ? Results.Ok(product) : Results.NotFound();
    });

    // Create a new product
    endpoints.MapPost("/products", (Product product) =>
    {
        product.Id = products.Count + 1;
        products.Add(product);
        return Results.Created($"/products/{product.Id}", product);
    });

    // Update a product by Id
    endpoints.MapPut("/products/{id}", (int id, Product updatedProduct) =>
    {
        var existingProduct = products.FirstOrDefault(p => p.Id == id);
        if (existingProduct is null)
            return Results.NotFound();

        existingProduct.Name = updatedProduct.Name;
        existingProduct.Price = updatedProduct.Price;
        return Results.Ok(existingProduct);
    });

    // Delete a product by Id
    endpoints.MapDelete("/products/{id}", (int id) =>
    {
        var product = products.FirstOrDefault(p => p.Id == id);
        if (product is null)
            return Results.NotFound();

        products.Remove(product);
        return Results.NoContent();
    });
});

var app = builder.Build();
app.Run();

Step 4: Start the Application

Open a terminal within your project folder and run the following command to start the application:

dotnet run

Step 5: Test the Endpoints with Postman

Now, let's test the CRUD operations using Postman.

5.1. Create a New Product (POST):

  • Open Postman.

  • Create a new request and set the request type to POST.

  • Enter the request URL: http://localhost:5000/products

  • In the Body section, select the "raw" option and set the content type to JSON (application/json).

  • Enter the JSON data for the new product, for example:

{
    "Name": "Product A",
    "Price": 19.99
}
  • Send the request. You should receive a 201 Created response with the new product data, including the generated Id.

5.2. Get All Products (GET):

  • Create a new request and set the request type to GET.

  • Enter the request URL: http://localhost:5000/products

  • Send the request. You should receive a list of all products in the response.

5.3. Get a Product by Id (GET):

  • Create a new request and set the request type to GET.

  • Enter the request URL, replacing {id} with the actual product Id (e.g., http://localhost:5000/products/1).

  • Send the request. You should receive the product details if it exist, or a 404 Not Found response if not.

5.4. Update a Product by Id (PUT):

  • Create a new request and set the request type to PUT.

  • Enter the request URL, replacing {id} with the actual product Id (e.g., http://localhost:5000/products/1).

  • In the Body section, select the "raw" option and set the content type to JSON (application/json).

  • Enter the JSON data with the updated product information, for example:

{
    "Name": "Updated Product A",
    "Price": 24.99
}
  • Send the request. You should receive the updated product details.

5.5. Delete a Product by Id (DELETE):

  • Create a new request and set the request type to DELETE.

  • Enter the request URL, replacing {id} with the actual product Id (e.g., http://localhost:5000/products/1).

  • Send the request. You should receive a 204 No Content response, indicating the successful deletion.

Conclusion

You've successfully built a simple CRUD application using Minimal APIs in .NET 6.0 with Visual Studio Code and tested the endpoints using Postman. This approach simplifies the development process, reduces boilerplate code, and offers efficient RESTful API endpoints.

To explore Minimal APIs further and access detailed documentation, visit the official Microsoft documentation.

Stay tuned to our newsletter for more insights into .NET development and Azure Cloud!

Subscribe to our newsletter for the latest updates on .NET, Azure and web development trends.