In this blog, we’ll explore the power of Minimal APIs and walk you through the process of building a basic API using ASP.NET Core.
Create a Project in .Net 7 version.
Uncheck Use Controllers
to use minimal API
Default project Structure of Minimal API project:
We’ll be doing all of our work in the Program.cs
file.
Defining the Employee Model
Our API will manage a list of employees, so we’ll define a simple Employee class with properties like Id, Name, and City
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
}
Adding Sample Employee Data
We’ll initialize a list of employees with sample data
var employees = new List<Employee>
{
new Employee { Id = 1,Name="Sam",City="Chennai"},
new Employee { Id = 2,Name="John",City="Coimbatore"},
new Employee { Id = 3,Name="Anu",City="Erode"},
new Employee { Id = 4,Name="Aarav",City="Chennai"}
};
Defining API Endpoints
Now, let’s define our API endpoints for performing CRUD (Create, Read, Update, Delete) operations on the Employee resource:
app.MapGet("/GetAllEmployees", () =>
{
return employee;
});
app.MapGet("/getEmployeeById", (int id) =>
{
var emp=employee.Find(x=>x.Id==id);
return emp;
});
app.MapPost("/CreateEmployee", (Employee Emp) =>
{
employee.Add(Emp);
});
app.MapPut("UpdateEmployee", (Employee update, int id) =>
{
var updateEmp = employee.Find(x => x.Id == id);
updateEmp.Name = update.Name;
updateEmp.City = update.City;
return employee;
});
app.MapDelete("/DeleteEmployee", (int id) =>
{
var emp = employee.Find(x => x.Id == id);
employee.Remove(emp);
});
GET /GetAllEmployees:
This endpoint retrieves and returns a list of all employees stored in the employee collection.
GET /getEmployeeById:
This endpoint expects an id parameter in the request.
It searches for an employee with the Id in the employee collection and returns that employee if found.
POST /CreateEmployee:
This endpoint expects a JSON object representing an employee in the request body (Employee Emp).
It adds the new employee to the employee collection.
PUT /UpdateEmployee:
This endpoint expects an id parameter in the request.
It finds the employee with the Id in the employee collection and updates their Name and City properties with the values from the update object.
It then returns the updated list of employees.
DELETE /DeleteEmployee:
This endpoint expects an id parameter in the request.
It searches for an employee with the Id in the employee collection and removes that employee from the list.
In this way, we can test all the APIs of our minimal API project.
No Comment! Be the first one.