###### tags: `Back-end`,`Restful API`,`ASP.NET CORE`,'Titanium'
# Day 04 - Service Layer and Postman
## Remove and Update Using DELETE and PUT
In previous lessons, we introduced CRUD operations (Create, Read, Update, Delete) for trainers and courses. We used methods like HttpPost, HttpGet, etc., to interact with data.
Now, let's focus on PUT and DELETE methods for updating and removing resources.
```csharp
// Update a trainer's details using PUT
[HttpPut("{id}")]
public IActionResult UpdateTrainer(int id, [FromBody] Trainer updatedTrainer)
{
var trainer = trainers.FirstOrDefault(t => t.Id == id);
if (trainer == null)
{
return NotFound();
}
trainer.Name = updatedTrainer.Name;
trainer.Specialization = updatedTrainer.Specialization;
trainer.Salary = updatedTrainer.Salary;
return Ok(trainer);
}
// Delete a trainer using DELETE
[HttpDelete("{id}")]
public IActionResult DeleteTrainer(int id)
{
var trainer = trainers.FirstOrDefault(t => t.Id == id);
if (trainer == null)
{
return NotFound();
}
trainers.Remove(trainer);
return NoContent();
}
```
* PUT: Used to update an existing resource. In this case, we update the trainer's information.
* DELETE: Used to delete a resource. Here, we delete the trainer if they exist in the list.
*
## Service Layer
Managing data directly in the controller (like the trainers list in our example) isn't a scalable or maintainable approach. We'll introduce a service layer to handle all business logic and data operations.
This layer separates concerns, moving data operations out of the controller and making the code more testable and reusable.
**Steps:**
* Create a service class TrainerService.
* Move all operations on trainers from the controller to the service.
* Inject the service into the controller using Dependency Injection (DI).
```csharp
public class TrainerService : ITrainerService
{
private List<Trainer> trainers = new List<Trainer>();
public List<Trainer> GetAll() => trainers;
public Trainer GetById(int id) => trainers.FirstOrDefault(t => t.Id == id);
public void Add(Trainer trainer)
{
trainer.Id = trainers.Count + 1;
trainers.Add(trainer);
}
public void Update(int id, Trainer updatedTrainer)
{
var trainer = GetById(id);
if (trainer != null)
{
trainer.Name = updatedTrainer.Name;
trainer.Specialization = updatedTrainer.Specialization;
trainer.Salary = updatedTrainer.Salary;
}
}
public void Delete(int id)
{
var trainer = GetById(id);
if (trainer != null)
{
trainers.Remove(trainer);
}
}
}
```
## Dependency Injection (DI)
Dependency Injection is a design pattern that allows for better code maintainability and testability. We inject dependencies (like services) into classes instead of having them create instances internally. ASP.NET Core handles DI via its built-in DI Container.
To implement DI:
Define an interface for the service.
Register the service in the Startup.cs or Program.cs file using AddScoped().
```csharp
// Service interface
public interface ITrainerService
{
List<Trainer> GetAll();
Trainer GetById(int id);
void Add(Trainer trainer);
void Update(int id, Trainer updatedTrainer);
void Delete(int id);
}
// Register the service in Program.cs
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the DI container
builder.Services.AddScoped<ITrainerService, TrainerService>();
var app = builder.Build();
app.Run();
}
}
```
`AddScoped():` This method registers the service in the DI container and ensures that a new instance is created per web request.
**Why Use an Interface for the Service Layer?**
Using an interface allows us to:
* Abstract the underlying implementation from the rest of the code.
* Enable easy testing by mocking the interface.
* Facilitate flexibility for future changes (you can change the service implementation without modifying the rest of the code).
For example, the ITrainerService defines the methods the service class must implement, but the consumer doesn't need to know the details of how they're implemented.
## Postman
We've already seen how Swagger provides us with an interactive UI to test our API. Now, let's introduce Postman, another powerful tool for API testing.
### Postman vs Swagger
Key Differences:
* Swagger: Integrated into the application, and useful for exploring APIs and documentation.
* Postman: A standalone tool that offers more advanced features like testing, environment variables, automation, and collections for organizing multiple requests.
**Why Use Postman?**
Postman provides several features beyond Swagger:
Environment management: You can store and manage variables, making it easier to switch between different setups.
API Testing: You can write automated tests to validate responses.
Collections: Organize groups of requests, which is useful for complex APIs.
### Testing API Endpoints with Postman
* Create a new request in Postman.
* Set the request method (GET, POST, PUT, DELETE).
* Enter the API URL, for example, http://localhost:36542/api/trainers.
* Add request headers if necessary (e.g., content-type: application/json).
* For POST/PUT, add the body (the JSON data).
* Send the request and check the response.
### Import and Export Between Swagger and Postman
you can import/export API requests between Swagger and Postman using the Swagger JSON file.
Steps to Import Swagger into Postman:
* Export the Swagger file as a JSON file.
* Open Postman.
* Click on Import and choose the JSON file.
* Postman will create a collection based on the Swagger documentation.
Steps to Export Postman to Swagger:
* Export the Postman collection as a JSON file.
* Use an API documentation generator (or manual conversion) to convert Postman JSON into Swagger format.
# Task Assignment: Task 04
## Objective:
In this task, you are required to expand the current solution by implementing a service layer for other entities (Trainees, Programs, Courses, Enrollment), utilizing the Dependency Injection (DI) concept, and interfaces. You will also create and test the CRUD operations using Postman, export the collection, and save it inside the project.
## Task Requirements:
Implement Service Layer for Other Classes:
1. Create a service layer for each of the following entities:
* Trainees
* Programs
* Courses
* Enrollment
* Utilize the DI concept and interfaces for each service class, following the example given for TrainerService.
* Ensure all business logic for CRUD operations is moved from controllers to the service layer.
2. Postman Collection for CRUD Operations:
* Create CRUD operations for all the above resources using Postman:
* GET, POST, PUT, DELETE for Trainees, Programs, Courses, and Enrollment.
* Test each operation to ensure it works correctly.
3. Export Postman Collection:
* After testing all the endpoints, export the Postman collection.
* Save the exported JSON file inside the project (for example, in a folder named PostmanCollections).
* Ensure that the Postman collection is included in the Git repository.
4. Push the Solution to GitHub:
* Ensure that the entire solution, including the new service layers, Postman collection, and any other changes, is pushed to your GitHub repository.
* Provide the link to the repository for review.