Skip to main content

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application.

Angular:

Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean.
  • Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs)
  • Components typescript file and HTML file support 2-way binding which means data flow is bi-directional
  • Component typescript file listens for all HTML events from the HTML file.

Create Angular(14) Application:

Let's create an Angular(14) application to begin our sample.

Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application.
Command To Install Angular CLI
npm install -g @angular/cli

Run the below command to create the angular application.
Command To Create Angular Application
ng new name_of_your_app

Note: While creating the app, you will see a notification to enable routing like '(y/n)' please enter 'y'(yes) For our demo we use routing as well.

Let's explore a few default files in the angular project:
  • package.json - contains commands like build, run, test, etc. It also contains packages or library references that our angular application requires.
  • angular.json - contains setup and configurations of angular.
  • src/index.html - Only HTML file of the angular application. It contains the root angular component element like <app-root></app-root>, area for our components to rendered.
  • src/main.ts - entry file of our angular application to execute.
  • src/app/app.modulet.ts - Entry module.
  • src/app/app-routing.module.ts - Entry route module
  • app(folder or root component folder) - contains root component like 'AppComponent' consist of files like 'app.component.ts', 'app.component.html', 'app.component.css'.

Setup JSON Server:

Let's set up a fake API by setting up the JSON server in our local machine.

Run the below command to install the JSON server global onto your local system.
npm install -g json-server

Now go to our angular application and add a command to run the JSON server into the 'package.json' file
"json-run":"json-server --watch db.json"

Now to invoke the above-added command, run the below command in the angular application root folder.
npm run json-run

After running the above command for the first time, a 'db.json' file gets created, so this file act as a database. So let's add some sample data into the file as below.
Now access API endpoint like 'http://localhost:3000/fruits'.

Install And Configure Bootstrap:

Let's install the bootstrap package into our angular application
npm install bootstrap

Add the bootstrap 'JS' & 'CSS' file path in 'angular.json'.

Add the bootstrap menu to the 'app.component.html' file
src/app/app.component.html:
<nav class="navbar navbar-expand-lg navbar-dark bg-warning">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Fruit Bowl</a>
  </div>
</nav>
<router-outlet></router-outlet>
  • (Line: 1-5) Render the bootstrap menu
  • (Line: 6) The 'router-outlet' is the default angular component. The content of every route is rendered into it.

Create A Example Module(Ex: Fruits Module):

Let's create a sample 'Fruits' module along with its route module. Run the below command.
ng generate module fruits --routing


Now add our 'FruitModule' into the imports of the 'AppModule'.

Create A Home Component:

Let's create a child component like 'Home' inside of the 'fruits' module. The 'Home' component will display all the items.
ng generate component fruits/home


Add HomeComponent rout in the 'FruitsRoutingModule'.
src/app/fruits/fruits-routing.module.ts:
// existing code hidden for display purpose

import { HomeComponent } from './home/home.component';

const routes: Routes = [
  {
    path: 'fruits/home',
    component: HomeComponent,
  },
];
Now make the 'fruits/home' route as the default route by adding a redirection in the 'AppRoutingModule'.
src/app/app-routing.modulet.ts:
// code hidden for display purpose

const routes: Routes = [
  {
    path: '',
    redirectTo: 'fruits/home',
    pathMatch: 'full',
  },
  
];

Create A Service File:

Create an angular service file where we are going to implement the logic for API calls.
ng generate service fruits/fruits

Now inject the 'HttpClient' instance into the service constructor. The 'HttpClient' provides in-built methods for invoking the API's
src/app/fruits/fruits.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class FruitsService {
  constructor(private http: HttpClient) {}
}
In 'AppModule' add 'HttpClientModule' to the imports array.
src/app/app.module.ts:
import { HttpClientModule } from '@angular/common/http';
// code hidden for display purpose

@NgModule({
  imports: [
    HttpClientModule
  ],
})
export class AppModule { }

Create API Response Model:

Let's create a model for the API response.
ng generate interface fruits/fruits
src/app/fruits/fruits.ts:
export interface Fruits {
  id: number;
  name: string;
  quantity: number;
  price: number;
}

Read Operation:

The Read operation means reading the data from the API.

In 'FruitService' let's implement logic to invoke the API call.
src/app/fruits/fruits.servicet.ts:
get() {
  return this.http.get<Fruits[]>('http://localhost:3000/fruits');
}
  • The 'HttpClient.get<T>()' is to invoke the HTTP Get endpoint.
Add the following logic into the 'HomeComponent'.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  allFruits: Fruits[] = [];

  constructor(private fruitService: FruitsService) {}

  ngOnInit(): void {
    this.get();
  }

  get() {
    this.fruitService.get().subscribe((data) => {
      this.allFruits = data;
    });
  }
}
  • (Line: 5-9) To make 'HomeComponent' as angular component it should be decorated with '@Component' decorator that loads from the '@angular/core'. The 'selector' property for define the component Html element tag. The 'templateUrl' property for to link the component Html file. The 'styleUrls' property for to link the component CSS file.
  • (Line: 11) Variable 'allFruits' is of  'Fruits' array type. This variable is to store all API response data into this variable.
  • (Line: 19-23) Here defined method like 'get()'. Invoking the get API call in service file. Here 'subscribe()' get executed after completion of the API call. On receiving response assign to the 'allFruits' variable.
  • (Line: 15-17) The 'ngOnInit()' is one of the angular component life cycle method. This method executed automatically on invoking our 'HomeComponent'. Inside of this method we invoke our 'get()' method.
Add the following HTML into the 'HomeComponent.html' file.
src/fruits/home/home.component.html:
<div class="container">
  <table class="table">
    <thead>
      <tr>
        <th scope="col">Id</th>
        <th scope="col">Name</th>
        <th scope="col">Quantity</th>
        <th scope="col">Price</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of allFruits">
        <th scope="row">{{ item.id }}</th>
        <td>{{ item.name }}</td>
        <td>{{ item.quantity }}</td>
        <td>{{ item.price }}</td>
      </tr>
    </tbody>
  </table>
</div>
  • Angular for databinding bind the we use '{{}}'(string interpolation) 
  • (Line: 12) The 'allFruits' is array, to loop it over the HTML content we have to use '*ngFor'. In *ngFor we will use array of object like 'allFruits', the 'of' keyword to popsout each item from  the array and assign to the variable 'item'
  • (Line: 13-16) Rendering the data to the bootstrap table.
Now run both angular(ng serve) and API (npm run json-run).

Generate A 'Create' Component:

Generate a new child component like 'Create' under the 'fruits' module. This component contains a form for creating the new items.
ng generate component fruits/create


Add route for 'Create' component into 'FruitRouteModule'.
src/app/fruits/fruits-routing.module.ts:
// existing code hidden for display puporse
import { CreateComponent } from './create/create.component';

const routes: Routes = [
  {
    path: 'fruits/home',
    component: HomeComponent,
  }
];

Create Operation:

Let's implement the logic for invoking the save API call in  'FruitsService'.
src/app/fruits/fruits.service.ts:
create(payload: Fruits) {
  return this.http.post<Fruits>('http://localhost:3000/fruits', payload);
}
  • The 'HttpClient.post<T>(payload)' method is invoke the HTTP Post endpoint for saving at the server.
Let's update the logic in the 'CreateComponent.ts' file.
src/app/fruits/create/create.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
})
export class CreateComponent implements OnInit {
  fruitForm: Fruits = {
    id: 0,
    name: '',
    price: 0,
    quantity: 0,
  };

  constructor(private fruitService:FruitsService,
    private router:Router) {}

  ngOnInit(): void {}

  create(){
    this.fruitService.create(this.fruitForm)
    .subscribe({
      next:(data) => {
        this.router.navigate(["/fruits/home"])
      },
      error:(err) => {
        console.log(err);
      }
    })
  }
}
  • (Line: 12-17) Declared the 'fruitForm' variable to store the user entered form data.
  • (Line: 19-20) Injected the 'FruitsService' and 'Router'.
  • (Line: 24-34) Invoking the API call to post the data.
  • (Line: 28) On successful saving data to the server, we navigate to the home page.
Add the following HTML code to the 'CreateComponent.html' file.
src/app/fruits/create/create.component.hmtl:
<div class="container">
  <legend>Create Item</legend>
  <form>
    <div class="mb-3">
      <label for="txtName" class="form-label">Name</label>
      <input type="text" name="name" [(ngModel)] = "fruitForm.name" class="form-control" id="txtName" />
    </div>
    <div class="mb-3">
      <label for="txtPrice" class="form-label">Price</label>
      <input type="number" name="price" [(ngModel)] = "fruitForm.price" class="form-control" id="txtPrice" />
    </div>
    <div class="mb-3">
      <label for="txtQuantity" class="form-label">Quantity</label>
      <input type="number" name="quantity" [(ngModel)] = "fruitForm.quantity" class="form-control" id="txtQuantity" />
    </div>
    <button type="button" (click)="create()" class="btn btn-primary">Create</button>
  </form>
</div>
  • Here enable 2-way model binding using '[(ngModel)]'. One more important thing here is that the input element must contain the 'name' attribute for 2-way model binding.
  • Click event can be a register like '(name_of_event)' and the event must register with the method so that on raise of event logic inside of the method gets executed.
Add the 'FormModule'(required for ngModel) into the import array of 'FruitsModule'.
src/app/fruits/fruits.module.ts:
// existing code hidden for display purpose
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    FormsModule
  ]
})
export class FruitsModule { }
In 'HomeComponent.html' add a button for navigating the 'CreateComponent'.
src/app/fruits/home/home.component.html:
<div class="container">
  <div class="row mt-2">
    <div class="col col-md-4 offset-md-4">
      <a class="btn btn-primary" routerLink="/fruits/create">Create</a>
    </div>
  </div>
  <table class="table">
	<!-- code hidden for display purpose -->
  </table>
</div>
  • Here 'routerLink' is an angular directive used for anchor tags for navigation.
(Step 1)

(Step 2)

(Step 3)

Generate A 'Edit' Component:

Generate new child components like 'Edit' under the 'Fruits' module. This component contains the form for updating the items 
ng generate component fruits/edit

Add route for 'Edit' component into 'FruitModule'.
src/app/fruits/fruits-routing.module.ts:
import { EditComponent } from './edit/edit.component';

// existing code hidden for display purpose

const routes: Routes = [
  {
    path:'fruits/edit/:id',
    component: EditComponent
  }
];

Update Operation:

In our 'FruitService' implement the logic for 2 API calls, one for fetching items by id and another for updating the data.
src/app/fruits/fruits.service.ts:
getById(id: number) {
 return this.http.get<Fruits>(`http://localhost:3000/fruits/${id}`);
}

update(payload:Fruits){
 return this.http.put(`http://localhost:3000/fruits/${payload.id}`,payload);
}
  • (Line: 1-3) Invokes the HTTP Get endpoint by 'id' value as a filtering parameter.
  • (Line: 5-7) Invokes the HTTP Put endpoint for updating the item. Here 'id' value needs to be passed in the URL and edited data as a payload.
Now add the following logic into the 'edit.component.ts' file
src/app/fruits/edit/edit.component.ts:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css'],
})
export class EditComponent implements OnInit {
  fruitForm: Fruits = {
    id: 0,
    name: '',
    price: 0,
    quantity: 0,
  };
  constructor(
    private route: ActivatedRoute,
    private router:Router,
    private fruitService: FruitsService
  ) {}

  ngOnInit(): void {
    this.route.paramMap.subscribe((param) => {
      var id = Number(param.get('id'));
      this.getById(id);
    });
  }

  getById(id: number) {
    this.fruitService.getById(id).subscribe((data) => {
      this.fruitForm = data;
    });
  }

  update() {
    this.fruitService.update(this.fruitForm)
    .subscribe({
      next:(data) => {
        this.router.navigate(["/fruits/home"]);
      },
      error:(err) => {
        console.log(err);
      }
    })
  }
}
  • (Line: 12-17) Declared the 'formFruits' variable to store the user form edited data.
  • (Line: 18-22) Injected the 'ActivatedRoute', 'Router', 'FruitService'.
  • (Line: 24-29) Inside of the 'ngOninit' life cycle method, we try to read the 'id' value from the route using the 'ActivatedRoute.paramMap.subscribe()', then we are invoking our get API call.
  • (Line: 31-35) Invokes the API call by 'id' value, on successful the response will be assigned to 'formFruit' variable, so that data gets rendered on the form.
  • (Line: 37-47) Invokes the update API, on success navigate back to the 'HomeComponent'.
Add the following HTML code to the 'edit.component.html'.
src/app/fruits/edit/edit.component.html:
<div class="container">
    <legend>Edit Item</legend>
    <form>
      <div class="mb-3">
        <label for="txtName" class="form-label">Name</label>
        <input type="text" name="name" [(ngModel)] = "fruitForm.name" class="form-control" id="txtName" />
      </div>
      <div class="mb-3">
        <label for="txtPrice" class="form-label">Price</label>
        <input type="number" name="price" [(ngModel)] = "fruitForm.price" class="form-control" id="txtPrice" />
      </div>
      <div class="mb-3">
        <label for="txtQuantity" class="form-label">Quantity</label>
        <input type="number" name="quantity" [(ngModel)] = "fruitForm.quantity" class="form-control" id="txtQuantity" />
      </div>
      <button type="button" (click)="update()" class="btn btn-primary">Update</button>
    </form>
</div>
Add the edit button in 'home.component.html' file
src/app/fruits/home/home.component.html:
<!-- existing code hidden for display -->
<tr *ngFor="let item of allFruits">

	<td>
	  <a class="btn btn-primary" [routerLink]="['/fruits/edit', item.id]">Edit</a>
	</td>
</tr>
  • Here we use 'routerLink' inside of  '[]' if the URL has a dynamic parameter. On render URL generated as eg:- 'fruits/edits/1'
(Step 1)

(Step 2)

(Step 3)

Delete Operation:

Let's implement delete API logic in 'FruitService'.
src/app/fruits/fruits.service.ts:
delete(id:number){
   return this.http.delete<Fruits>(`http://localhost:3000/fruits/${id}`);
}
  • The 'HttpClient.delete()' invokes the Http Delete request.
Let's update the 'home.component.ts' file as below.
src/app/fruits/home/home.component.ts:
import { Component, OnInit } from '@angular/core';
import { Fruits } from '../fruits';
import { FruitsService } from '../fruits.service';

declare var window: any;

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  allFruits: Fruits[] = [];
  deleteModal: any;
  idTodelete: number = 0;

  constructor(private fruitService: FruitsService) {}

  ngOnInit(): void {
    this.deleteModal = new window.bootstrap.Modal(
      document.getElementById('deleteModal')
    );

    this.get();
  }

  get() {
    this.fruitService.get().subscribe((data) => {
      this.allFruits = data;
    });
  }

  openDeleteModal(id: number) {
    this.idTodelete = id;
    this.deleteModal.show();
  }

  delete() {
    this.fruitService.delete(this.idTodelete).subscribe({
      next: (data) => {
        this.allFruits = this.allFruits.filter(_ => _.id != this.idTodelete)
        this.deleteModal.hide();
      },
    });
  }
}
  • (Line: 5) Declare window variable type.
  • (Line: 14) The variable 'deleteModal' to store the instance of the botstrap modal.
  • (Line: 15) The variable 'idToDelete' to store the 'id' value of the item to be deleted.
  • (Line: 20-22) Assign the bootstrap modal instance to our 'deleteModal' variable.
  • (Line: 33-36) The 'openDeleteModal()' method gets invoked by clicking the delete button. Here we open the delete confirmation modal.
  • (Line: 38-45) The 'delete()' method invokes the delete API call on the success we will hide our bootstrap modal and also exclude the item from the 'allFruits' variable.
Let's add 'Edit' button and 'Delete Confirmation' bootstrap modal HTML code to 'home.component.html'
src/app/fruits/home/home.component.html:
<!-- existing code hidden for display purpose -->
<div class="container">
  
  <table class="table">
   
    </thead>
    <tbody>
      <tr *ngFor="let item of allFruits">
        <td>
          <a class="btn btn-primary" [routerLink]="['/fruits/edit', item.id]">Edit</a> |
          <button type="button" (click)="openDeleteModal(item.id)" class="btn btn-danger">Delete</button>
          </td>
      </tr>
    </tbody>
  </table>
</div>


<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Warning!</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        Are you sure to delete the item?
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-danger" (click)="delete()">Confirm Delete</button>
      </div>
    </div>
  </div>
</div>
  • (Line: 11) Edit button registered with 'openDeleteModal()' for click event.
  • (Line: 20-36) Delete confirmation bootstrap modal, here we have to give 'id' attribute, based on that 'id' attribute we create the bootstrap instance in 'home.component.ts' file.
  • (Line: 32) Here 'Confirm Delete' button registered with 'delete()' method for click event.

Support Me!
Buy Me A Coffee PayPal Me

Video Session:

Wrapping Up:

Hopefully, I think this article delivered some useful information on Angular 14 CRUD. using I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:


Comments

  1. Great tutorial. There are some minor edits needed in the code, but everything works and I learned a lot. Thank you.

    ReplyDelete

Post a Comment

Popular posts from this blog

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Usage Of CancellationToken In Asp.Net Core Applications

When To Use CancellationToken?: In a web application request abortion or orphan, requests are quite common. On users disconnected by network interruption or navigating between multiple pages before proper response or closing of the browser, tabs make the request aborted or orphan. An orphan request can't deliver a response to the client, but it will execute all steps(like database calls, HTTP calls, etc) at the server. Complete execution of an orphan request at the server might not be a problem generally if at all requests need to work on time taking a job at the server in those cases might be nice to terminate the execution immediately. So CancellationToken can be used to terminate a request execution at the server immediately once the request is aborted or orphan. Here we are going to see some sample code snippets about implementing a CancellationToken for Entity FrameworkCore, Dapper ORM, and HttpClient calls in Asp.NetCore MVC application. Note: The sample codes I will show in

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Different HttpClient Techniques To Consume API Calls In Minimal API[.NET6]

In this article, we are going to implement different HttpClient techniques to consume API calls in minimal API. The different HttpClient techniques that we are going to explore are like: Register HttpClient Object Explicitly In DI(Dependency Injection Service) Named Client Type Client HttpRequestMessage Object Create A .NET6 Minimal API Project: Let's create a .Net6 Minimal API sample project to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. CLI command For Minimal API Project dotnet new webapi -minimal -o Your_Project_Name Create A Third Party API Response Model: Here I'm going to use a free third-party rest API that is "https://jsonplaceholder.typicode.com/posts". So to receive the response let's create a response model like 'Post.cs'. Program.cs:(Add Post.cs c

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl