Consume The .NET Core 6 Web API In PowerShell Script And Perform CRUD Operation

In this article, we are going to discuss consuming REST API inside PowerShell and performing CRUD operations through PowerShell Script.

Agenda

  • Implementation of .NET Core 6 Web API
  • Create PowerShell Script and consume API to perform CRUD operation

Prerequisites

  • Visual Studio 2022
  • .NET Core SDK 6
  • SQL Server
  • PowerShell

Implementation of .NET Core 6 Web API

Here we implement a product offer application for demo purposes which is managed by the admin and performed CRUD operations

Project Structure

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Step 1

Create a new .NET Core Web API

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Step 2

Configure a new project

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Step 3

Provide additional information

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Step 4

Create an Offer class inside the Entities folder

namespace PowerShellDemo.Entities
{
    public class Offer
    {
        public int Id { get; set; }
        public string ProductName { get; set; }
        public string OfferDescription { get; set; }
    }
}

Step 5

Next, add DbContextClass inside the Data folder which provides a data context object to perform data-related all SQL operations

using Microsoft.EntityFrameworkCore;
using PowerShellDemo.Entities;

namespace PowerShellDemo.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<Offer> Offer { get; set; }
    }
}

Step 6

Create IProductOfferService and ProductOfferService files inside the Repositories

IProductOfferService

using PowerShellDemo.Entities;

namespace PowerShellDemo.Repositories
{
    public interface IProductOfferService
    {
        public Task<List<Offer>> GetOfferListAsync();
        public Task<Offer> GetOfferByIdAsync(int Id);
        public Task<Offer> AddOfferAsync(Offer offer);
        public Task<Offer> UpdateOfferAsync(Offer offer);
        public Task<bool> DeleteOfferAsync(int Id);
    }
}

ProductOfferService

using Microsoft.EntityFrameworkCore;
using PowerShellDemo.Data;
using PowerShellDemo.Entities;

namespace PowerShellDemo.Repositories
{
    public class ProductOfferService : IProductOfferService
    {
        private readonly DbContextClass _dbContext;

        public ProductOfferService(DbContextClass dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<List<Offer>> GetOfferListAsync()
        {
            return await _dbContext.Offer.ToListAsync();
        }

        public async Task<Offer> GetOfferByIdAsync(int Id)
        {
            return await _dbContext.Offer.Where(x => x.Id == Id).FirstOrDefaultAsync();
        }

        public async Task<Offer> AddOfferAsync(Offer offer)
        {
            var result = _dbContext.Offer.Add(offer);
            await _dbContext.SaveChangesAsync();
            return result.Entity;
        }

        public async Task<Offer> UpdateOfferAsync(Offer offer)
        {
            var result = _dbContext.Offer.Update(offer);
            await _dbContext.SaveChangesAsync();
            return result.Entity;
        }
        public async Task<bool> DeleteOfferAsync(int Id)
        {
            var filteredData = _dbContext.Offer.Where(x => x.Id == Id).FirstOrDefault();
            var result = _dbContext.Remove(filteredData);
            await _dbContext.SaveChangesAsync();
            return result != null ? true : false;
        }
    }
}

Step 7

Next, create a new product to offer a controller

using Microsoft.AspNetCore.Mvc;
using PowerShellDemo.Entities;
using PowerShellDemo.Repositories;

namespace PowerShellDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductOfferController : ControllerBase
    {
        private readonly IProductOfferService productOfferService;

        public ProductOfferController(IProductOfferService productOfferService)
        {
            this.productOfferService = productOfferService;
        }

        [HttpGet("getofferlist")]
        public async Task<List<Offer>> GetOfferListAsync()
        {
            try
            {
                var response = await productOfferService.GetOfferListAsync();

                return response;
            }
            catch
            {

            }
            return null;
        }

        [HttpGet("getofferbyid")]
        public async Task<Offer> GetOfferByIdAsync(int Id)
        {
            try
            {
                var response = await productOfferService.GetOfferByIdAsync(Id);

                return response;
            }
            catch
            {

            }
            return null;
        }

        [HttpPost("addoffer")]
        public async Task<Offer> AddOfferAsync(Offer offer)
        {
            try
            {
                var response = await productOfferService.AddOfferAsync(offer);

                return response;
            }
            catch
            {

            }
            return null;
        }

        [HttpPut("updateoffer")]
        public async Task<Offer> UpdateOfferAsync(Offer offer)
        {
            try
            {
                var response = await productOfferService.UpdateOfferAsync(offer);

                return response;
            }
            catch
            {

            }
            return null;
        }

        [HttpDelete("deleteoffer")]
        public async Task<bool> DeleteOfferAsync(int Id)
        {
            try
            {
                var response = await productOfferService.DeleteOfferAsync(Id);
                return response;
            }
            catch
            {

            }
            return false;
        }
    }
}

Step 8

Later on, register a few services in the DI container inside the Program class

using PowerShellDemo.Data;
using PowerShellDemo.Repositories;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IProductOfferService, ProductOfferService>();
builder.Services.AddDbContext<DbContextClass>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 9

Add the database connection string inside the appsettings.json file

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

Step 10

Execute the following commands which are going to create add migration and update the database

add-migration "initial"
update-database

Step 11

Finally, run web API

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Create PowerShell Script and consume API to perform CRUD operation

Step 1

Open Windows PowerShell ISE and create this script

#Product Application Demo

# Define api url
$apiBaseUrl = "http://localhost:5009/api/ProductOffer"

do
{

    Write-Host "================================================================================================================="
    write-host "`n"
    Write-Host "Following operation you can perform base on you input"
    Write-Host "1) Get list of product offer"
    Write-Host "2) Get product offer by offer id"
    Write-Host "3) Add a new product offer"
    Write-Host "4) Update existing product offer"
    Write-Host "5) Delete product offer by offer id"
    write-host "`n"
    write-host "========================================================================================================="
    
    $input = Read-Host "Enter action number which you want to perform from above "
    
    write-host "`n"

    try {
    
        switch($input){
        
             1{ 
                    #-------------------------------------------Get List of Prducts Offers--------------------------------------------------------
                    $offer_list_api_endpoint = $apiBaseUrl + "/getofferlist"
                    $offers_list = Invoke-RestMethod -Uri $offer_list_api_endpoint -Method Get -ContentType "application/json"

                    if($offers_list)
                    {
                        foreach($offer in $offers_list) 
                        {
                            Write-Host "Following offers are available"
                            Write-Host $offer
                            write-host "`n"
                        }
                    }
                    else
                    {
                            Write-Host "No product offers available"
                            write-host "`n"
                    } 
              }
                
             2{     #-------------------------------------------Get of Prduct Offer By ID--------------------------------------------------------
                    $input = Read-Host "Enter Offer ID | Ex - 1"
                    write-host "`n"
                    
                    $get_offer_api_endpoint = $apiBaseUrl + "/getofferbyid" +"?Id=$input"
                    
                    $offer = Invoke-RestMethod -Uri $get_offer_api_endpoint -Method Get -ContentType "application/json"

                    if($offer)
                    {
                        Write-Host $offer
                        write-host "`n"
                    }
                    else
                    {
                        Write-Host "Offer id not found"
                        write-host "`n"
                    }    
              }  
                
             3{     #-------------------------------------------Add a new product----------------------------------------------------------------
                    $product_description = @()
                    $product_description = Read-Host = "Enter the offer details | Ex- Samsung Smart TV, 5% off"
                    $product_description = $product_description.Split(",").Trim()
                    
                    $body = @{
                                "id" = 0
                                "productName" = $product_description[0]
                                "offerDescription" = $product_description[1]
                            }| ConvertTo-Json
                    
                    
                    $header = @{
                            "accept" = "application/json"
                            "Content-Type" = "application/json"
                            }
                    
                    $add_offer_api_endpoint = $apiBaseUrl + "/addoffer"
                    
                    $added_offer = Invoke-RestMethod -Uri $add_offer_api_endpoint -Method Post -Body $body -Headers $header
                    
                    if($added_offer)
                    {
                        Write-Host "Below Product Added Successfully"
                        Write-Host $added_offer
                        write-host "`n"
                    }
              }
                
             4{     #-------------------------------------------update product offer ----------------------------------------------------------------
                    $product_description = @()
                    $product_description = Read-Host = "Enter the offer details which you want to update | Ex- 2, Samsung Smart TV, 5% off"
                    $product_description = $product_description.Split(",").Trim()
                    
                    $body = @{
                                "id" = $product_description[0]
                                "productName" = $product_description[1]
                                "offerDescription" = $product_description[2]
                            }| ConvertTo-Json
                    
                    
                    $header = @{
                            "accept" = "application/json"
                            "Content-Type" = "application/json"
                            }
                    
                    $update_offer_api_endpoint = $apiBaseUrl + "/updateoffer"
                    
                    $updated_offer = Invoke-RestMethod -Uri $update_offer_api_endpoint -Method Put -Body $body -Headers $header
                    
                    if($updated_offer)
                    {
                        Write-Host "Below Product Offer Update Successfully"
                        Write-Host $updated_offer
                        write-host "`n"
                    }
              }
              
                
              5{    #-------------------------------------------delete product offer by id----------------------------------------------------------------
                    
                    $input = Read-Host "Enter Offer ID which you want to be delete | Ex- 1"
                    
                    $get_offer_api_endpoint = $apiBaseUrl + "/deleteoffer" +"?Id=$input"
                    
                    $offer = Invoke-RestMethod -Uri $get_offer_api_endpoint -Method Delete -ContentType "application/json"
                    
                    if($offer -eq "True")
                    {
                        Write-Host "Offer deleted successfully"
                        write-host "`n"
                    }
                    else
                    {
                        Write-Host "Offer id not found"
                        write-host "`n"
                    }
              }  

        }#switch
    }#try
    Catch
    {
        Write-OUtput $_.Exception.Message
    }
    $isContinue = Read-Host "Do you want to continue: Y/N"

}Until($isContinue -eq "N")
  • Here as you see we create five sections inside the switch case some are used for getting offers and some to add and update the offer details
  • Also, we configure the base API URL in each section and invoke their endpoint after providing the body, header, and type of HTTP method.
  • If you want to learn more about PowerShell like the syntaxes and installation then read Microsoft’s official document https://learn.microsoft.com/en-us/powershell/

Step 2

Finally, run your script and executes multiple operations as I have shown in below images

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Consume the .NET Core 6 Web API in PowerShell script and perform CRUD operation

Conclusion

In this article, we discussed REST API and PowerShell like how to consume APIs inside PowerShell script and implementation of that with the help of .NET Core 6 and Windows PowerShell ISE.

Happy Learning!


Similar Articles