DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Empowering Real-World Solutions the Synergy of AI and .NET
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Router4j: A Free Alternative to Google Maps for Route and Distance Calculation
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI

Trending

  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Navigating Double and Triple Extortion Tactics
  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Minimal API Using .NET Core 6 Web API

Minimal API Using .NET Core 6 Web API

This article will go over the purpose of minimal APIs in.NET Core 6, as well as how to implement them step by step.

By 
Jaydeep Patil user avatar
Jaydeep Patil
·
Dec. 05, 22 · Code Snippet
Likes (2)
Comment
Save
Tweet
Share
2.7K Views

Join the DZone community and get the full member experience.

Join For Free

We will go over the purpose of minimal APIs in.NET Core 6, as well as how to implement them step by step.

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 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.


Create a new .NET Core Web API.

Step 2

Configure your project.

Configure your project.

Step 3

Provide additional information as I showed below.

Additional Information

Step 4

Install the following NuGet packages.

NuGet Packages

Project structure:

Project Structure


Step 5

Create a Product class inside the entities folder.

C#
 
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; }
    }
}


Step 6

Next, create DbContextClass inside the Data folder.

C#
 
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; }
    }
}


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 the database connection string inside the app settings file.

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


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.

C#
 
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();


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.

Run Application

GitHub URL

Conclusion

We discussed the minimal APIs and related topics using.NET Core 6 Web Application and Entity Framework with SQL Server.

Happy Learning!

API Web API Net (command) Data Types Microsoft SQL Server Microsoft Visual Studio

Published at DZone with permission of Jaydeep Patil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Empowering Real-World Solutions the Synergy of AI and .NET
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Router4j: A Free Alternative to Google Maps for Route and Distance Calculation
  • Implementing CRUD Operations With NLP Using Microsoft.Extensions.AI

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!