CRUD Operation in Asp.Net Core Web API with Swagger

Introduction

In this article, I explain how to integrate our API with the swagger and execute our web API using swagger, In this article, I explain CRUD operation with a Repository pattern in .net Core Web API.

step 1: Create new Web API with using .Net core

Step 2: Now install the package of swagger

open your NuGet package manager console and write below command into it.

Install-Package Swashbuckle

if you need more details about this package please click here (https://www.nuget.org/packages/Swashbuckle/)

Step 3: register the swagger generator

now open the startup.cs file and go to ConfigureServices, add below code into it.

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Employee API",
                    Description = "A simple example ASP.NET Core Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "Bhavdip Talaviya",
                        Email = "talaviya.bhavdip@gmail.com",
                        Url = new Uri("https://bhavdip13.github.io/portfolio"),
                    }
                    
                });
            });

now go to the Configure in the same file and Enable middleware to serve generated Swagger as a JSON endpoint, paste the below code into it.

// Enable middleware to serve generated Swagger as a JSON endpoint.
           app.UseSwagger();
           // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
           // specifying the Swagger JSON endpoint.
           app.UseSwaggerUI(c =>
           {
               c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee.API V1");
               c.RoutePrefix = string.Empty;
           });

now build your web API and run it.

step 4: create a folder name is “Models” in your web API, right-click on the models and create a new class for the model.
make a model like given below code.

using System.ComponentModel.DataAnnotations;

namespace SwaggerDemoWebAPI.Models
{
    public class MEmployee
    {
        [Key]
        public int EmpID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Gender { get; set; }
        public string Password { get; set; }
    }
}

step 5: create a folder name is “Data” in your web API, right-click on the data and create a new class for the DB context.

now add the DB set in the DB context like give below code.

using Microsoft.EntityFrameworkCore;
using SwaggerDemoWebAPI.Models;

namespace Employee.API
{
    public class DBContext : DbContext
    {
        public DBContext(DbContextOptions<DBContext> options) : base(options) { }
        public DbSet<MEmployee> Emp { get; set; }
    }
}

step 6: make the connection

now open the appsettings.json file and add the connection string like given below code.

{
  "ConnectionStrings": {
    "IdentityConnection": "Data Source=DILIP\\SQLEXPRESS01;Initial Catalog=Employee;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  },
  "CatalogBaseUrl": "",
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning"
    }
  }
}

now we need to configure the connection string so please open the startups.cs file and go to the configure services, paste below line at the first

// Add Identity DbContext
 services.AddDbContext<DBContext>(options =>options.UseSqlServer(Configuration.GetConnectionString("IdentityConnection")));

make sure your connection string name same in both file (appsettings.json & startup.cs)

step 7: Add repository in our web API project, so you need to create a new folder Repository in your Web API project

In the repository create one interface like “IEmployeeRepository” please write the name of your register starting with I if that is interface then, copy below code and paste into your interface.

using SwaggerDemoWebAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SwaggerDemoWebAPI.Repository
{
   public interface IEmployeeRepository
    {
        void Create(MEmployee item);
        MEmployee GetById(int Id);
        List<MEmployee> GetAll();
        void Update(int id,MEmployee item);
        void Delete(int Id);

    }
}

now add the one class for the employee repository, copy below code into your employee repository

using System.Collections.Generic;
using System.Linq;
using Employee.API;
using SwaggerDemoWebAPI.Models;

namespace SwaggerDemoWebAPI.Repository
{
    public class EmployeeRepository : IEmployeeRepository
    {
        private readonly DBContext _context;

        public EmployeeRepository(DBContext context)
        {
            _context = context;

        }
        public void Create(MEmployee item)
        {
            _context.Emp.Add(item);
            _context.SaveChanges();
        }

        public MEmployee GetById(int Id)
        {
            return _context.Emp.FirstOrDefault(t => t.EmpID == Id);
        }
        public List<MEmployee> GetAll()
        {
            return _context.Emp.ToList();
        }

        public void Update(int id,MEmployee item)
        {
            var entity = _context.Emp.Find(id);
            if (entity == null)
            {
                return;
            }

            _context.Entry(entity).CurrentValues.SetValues(item);
            _context.SaveChanges();
        }

        public void Delete(int id)
        {
            var entity = _context.Emp.Find(id);
            if (entity == null)
            {
                return;
            }
            _context.Emp.Remove(entity);
            _context.SaveChanges();
        }
    }
}

step 8: Create Employee API, now you need to create a controller in your web API controller folder, copy below code and paste into your controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SwaggerDemoWebAPI.Models;
using SwaggerDemoWebAPI.Repository;

namespace SwaggerDemoWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        public EmployeeController(IEmployeeRepository emp)
        {
            _Emp = emp;
        }
        public IEmployeeRepository _Emp { get; set; }
        [HttpPost]
        public void Post([FromBody] MEmployee modal)
        {
            _Emp.Create(modal);
        }

        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            var item = _Emp.GetById(id);
            if (item == null)
            {
                return NotFound();
            }
            return new ObjectResult(item);
        }
        [HttpGet]
        public List<MEmployee> Get()
        {   
            return _Emp.GetAll();

        }
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] MEmployee modal)
        {
            _Emp.Update(id, modal);

        }
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            _Emp.Delete(id);

        }

    }
}

make sure don’t ambiguous the method, after all code complete please rebuild your solution explorer.

now Run your web API and test your web API with the swagger.

3 Comments

  1. Rajesh Kumar

    THE CODE HUBS,

    very useful for me to do my job as web API with a swagger.

    please provide swagger authentication on api launch.

    thanks

    0
    0
    Reply
  2. Christian

    just a comment, i installed these package
    Swashbuckle.AspNetCore

    thanks

    0
    0
    Reply
  3. binary king

    would you please provide swagger authentication on api launch ?

    0
    0
    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories