Swagger UI for ASP.NET Core 8 Web API CRUD Tutorial

Learn How to create ASP.NET Core 8 Web API – Step-by-Step CRUD with SQL Server & EF Core

What is ASP.NET Core Web API?

Prerequisites

How to Build an ASP.NET Core 8 Web API Step-by-Step

Step 1: Create a New ASP.NET Core Web API Project

Step 2: Add the Item Model Class and Database Context

using System.ComponentModel.DataAnnotations;
namespace SmartInventoryApi.Models
{
    public class Item
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public int Quantity { get; set; }
        public decimal Price { get; set; }
    }
}

Create the ApplicationDbContext

using Microsoft.EntityFrameworkCore;
using SmartInventoryApi.Models;

namespace SmartInventoryApi.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Item> Items { get; set; }
    }
}

Step 3: Install Entity Framework Core Packages

Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 8.0.8
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 8.0.8
Install-Package Microsoft.EntityFrameworkCore.Design -Version 8.0.8

Step 4: Configure the Database

"ConnectionStrings": {
  "DefaultConnection": "Server=localhost;Database=SmartInventoryDb;Trusted_Connection=True;MultipleActiveResultSets=true"
}

Register DbContext

using Microsoft.EntityFrameworkCore;
using SmartInventoryApi.Data;
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
using Microsoft.EntityFrameworkCore;
using SmartInventoryApi.Data;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

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

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 5: Create Database Using Migrations

Add-Migration InitialCreate
Update-Database

Step 6: Create ItemsController with CRUD Endpoints

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SmartInventoryApi.Data;
using SmartInventoryApi.Models;

namespace SmartInventoryApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ItemsController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public ItemsController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/items
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Item>>> GetItems()
        {
            return await _context.Items.ToListAsync();
        }

        // GET: api/items/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Item>> GetItem(int id)
        {
            var item = await _context.Items.FindAsync(id);
            if (item == null) return NotFound();

            return item;
        }

        // POST: api/items
        [HttpPost]
        public async Task<ActionResult<Item>> PostItem(Item item)
        {
            _context.Items.Add(item);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetItem), new { id = item.Id }, item);
        }

        // PUT: api/items/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutItem(int id, Item item)
        {
            if (id != item.Id) return BadRequest();

            _context.Entry(item).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return NoContent();
        }

        // DELETE: api/items/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteItem(int id)
        {
            var item = await _context.Items.FindAsync(id);
            if (item == null) return NotFound();

            _context.Items.Remove(item);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
}

Step 7: Test Your Web API

Swagger UI for ASP.NET Core 8 Web API

Common Mistakes to Avoid

Frequently Asked Questions (FAQ)

How do I create a Web API in ASP.NET Core 8 using Visual Studio 2022?

2. How do I connect ASP.NET Core Web API to SQL Server?

3. How do I test ASP.NET Core Web API?

4. What is CRUD in ASP.NET Core Web API?

5. What should I learn after creating a basic Web API?

Conclusion

Related Blogs You Might Like

🚀 Subscribe for Tech Updates

📧

👤

We respect your privacy. Unsubscribe anytime.