Building a Customer API with .NET Minimal API Framework

Building a Customer API with .NET Minimal API Framework

Introduction

The .NET 6 Minimal API framework provides a streamlined approach to build lightweight APIs.

Here’s a basic example of how you could create a Customer API with endpoints to create, update, delete, and query customers from a database.

Setting Up the Project

  1. Create a new .NET 6 Web API project.
  2. Install Entity Framework Core if you plan to use it for database operations.

Defining the Customer Model

First, define a Customer model:

public class Customer 
{ 
    public int Id { get; set; } 
    public string Name { get; set; }
    public string Email { get; set; } 
    
    // Other relevant properties 
}

Configuring the Database Context (Using Entity Framework Core)

If using Entity Framework Core, configure the database context:

public class ApplicationDbContext : DbContext 

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : 
    base(options
    { } 
    
    public DbSet<Customer> Customersgetset; } 
}

In your Program.cs, configure the context:

var builder = WebApplication.CreateBuilder(args);       

builder.Services.AddDbContext<ApplicationDbContext>(options => 
    options.
      UseSqlServer(builder.Configuration
                    .GetConnectionString("DefaultConnection")));

// Add services to the container. 
builder.Services.AddControllers();

Creating the Endpoints

In the Program.cs, define the API endpoints:

var app = builder.Build(); 

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

// Endpoint to get all customers 
app.MapGet("/customers"async (ApplicationDbContext context) => await context.Customers.ToListAsync()); 

// Endpoint to get a customer by ID 
app.MapGet("/customers/{id}"async (int id, ApplicationDbContext context) => await context.Customers.FindAsync(idis Customer customer 
    ? Results.Ok(customer) 
    : Results.NotFound()); 

// Endpoint to create a new customer 
app.MapPost("/customers"
  async (Customer customer, ApplicationDbContext context) => 
  {       
      context.Customers.Add(customer); 
      await context.SaveChangesAsync(); 
    
      return Results.Created($"/customers/{customer.Id}", customer); 
  }); 

// Endpoint to update a customer 
app.MapPut("/customers/{id}"
  async (int id, Customer inputCustomer, ApplicationDbContext context) => 

      var customerawaitcontext.Customers.FindAsync(id); 
      if (customer == nullreturn Results.NotFound(); 
      
      customer.Name = inputCustomer.Name; 
      customer.Email = inputCustomer.Email
      await context.SaveChangesAsync(); 
      
      return Results.NoContent(); 
  }); 
  
// Endpoint to delete a customer 
app.MapDelete("/customers/{id}"
  async (int id, ApplicationDbContext context) => 

    if (await context.Customers.FindAsync(idis Customer customer) 
    {   
        context.Customers.Remove(customer); 
        await context.SaveChangesAsync(); 
        return Results.Ok(customer); 

    
    return Results.NotFound(); 
  }); 
  
app.Run();

Running the API

Run the application. You should now have a basic Customer API with the following endpoints:

  • GET /customers: Fetch all customers.
  • GET /customers/{id}: Fetch a single customer by ID.
  • POST /customers: Create a new customer.
  • PUT /customers/{id}: Update an existing customer.
  • DELETE /customers/{id}: Delete a customer.

Next Steps

  • Ensure proper error handling and validation.
  • Implement authentication and authorization as needed.
  • For a production environment, it’s crucial to secure your API endpoints.

Conclusion

The .NET 6 Minimal API framework simplifies the process of creating APIs with less boilerplate code.

This example provides a basic structure for a Customer API, demonstrating the ease with which you can create, read, update, and delete resources.

As with any API, consider security, validation, and error handling for a robust solution.

Stephen

Hi, my name is Stephen Finchett. I have been a software engineer for over 30 years and worked on complex, business critical, multi-user systems for all of my career. For the last 15 years, I have been concentrating on web based solutions using the Microsoft Stack including ASP.Net, C#, TypeScript, SQL Server and running everything at scale within Kubernetes.