DEV Community

Jaydeep Patil
Jaydeep Patil

Posted on

4 2

Minimal API using .NET Core 6 Web API

We will discuss minimal APIs in .NET Core 6, their purpose, and step-by-step implementation.

Agenda

Introduction
Step-by-Step Implementation using .NET Core 6

Prerequisites

.NET Core 6 SDK
Visual Studio 2022
SQL Server

Introduction

  • Minimal APIs are used to create HTTP APIs with minimum dependencies and configuration.
  • Mostly it is used in microservices that have fewer files and functionality within a single file
  • But there are a few things that are not supported in minimal APIs like action filters, and built-in validation, also, a few more that are still in progress and will get in the future by .NET Team.

Step-by-Step Implementation using .NET Core 6

Step 1

Create a new .NET Core Web API

Image description

Step 2

Configure your project

Image description

Step 3

Provide additional information as I showed below

Image description

Step 4

Install the following NuGet packages

Image description

Project structure

Image description

Step 5

Create a Product class inside the entities folder

namespace MinimalAPIsDemo.Entities
{
    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public string ProductDescription { get; set; }
        public int ProductPrice { get; set; }
        public int ProductStock { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 6

Next, create DbContextClass inside the Data folder

using Microsoft.EntityFrameworkCore;
using MinimalAPIsDemo.Entities;
namespace MinimalAPIsDemo.Data
{
    public class DbContextClass : DbContext
    {
        protected readonly IConfiguration Configuration;
        public DbContextClass(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
        }
        public DbSet<Product> Product { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 7

Register the Db Context service in the DI container inside the Program class which is the entry point of our application

builder.Services.AddDbContext<DbContextClass>();

Step 8

Add database connection string inside the app settings file

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=DESKTOP;Initial Catalog=MinimalAPIDemo;User Id=sa;Password=database;"
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 9

Later on, add different API endpoints inside the Program class with the help of Map and specified routing pattern as I showed below

using Microsoft.EntityFrameworkCore;
using MinimalAPIsDemo.Data;
using MinimalAPIsDemo.Entities;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddDbContext<DbContextClass>();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
//get the list of product
app.MapGet("/productlist", async (DbContextClass dbContext) =>
{
    var products = await dbContext.Product.ToListAsync();
    if (products == null)
    {
        return Results.NoContent();
    }
    return Results.Ok(products);
});
//get product by id
app.MapGet("/getproductbyid", async (int id, DbContextClass dbContext) =>
{
    var product = await dbContext.Product.FindAsync(id);
    if (product == null)
    {
        return Results.NotFound();
    }
    return Results.Ok(product);
});
//create a new product
app.MapPost("/createproduct", async (Product product, DbContextClass dbContext) =>
{
    var result = dbContext.Product.Add(product);
    await dbContext.SaveChangesAsync();
    return Results.Ok(result.Entity);
});
//update the product
app.MapPut("/updateproduct", async (Product product, DbContextClass dbContext) =>
{
    var productDetail = await dbContext.Product.FindAsync(product.ProductId);
    if (product == null)
    {
        return Results.NotFound();
    }
    productDetail.ProductName = product.ProductName;
    productDetail.ProductDescription = product.ProductDescription;
    productDetail.ProductPrice = product.ProductPrice;
    productDetail.ProductStock = product.ProductStock;
    await dbContext.SaveChangesAsync();
    return Results.Ok(productDetail);
});
//delete the product by id
app.MapDelete("/deleteproduct/{id}", async (int id, DbContextClass dbContext) =>
{
    var product = await dbContext.Product.FindAsync(id);
    if (product == null)
    {
        return Results.NoContent();
    }
    dbContext.Product.Remove(product);
    await dbContext.SaveChangesAsync();
    return Results.Ok();
});
app.Run();
Enter fullscreen mode Exit fullscreen mode

Step 10

Run the following entity framework command to create migration and update the database

add-migration "initial"
update-database

Step 11

Finally, run your application

Image description

GitHub URL

https://github.com/Jaydeep-007/MinimalAPIsDemo

Conclusion

Here we discussed the minimal APIs and things related to that using .NET Core 6 Web Application and Entity Framework with the help of SQL Server.

Happy Learning!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs