Use Scalar to invoke CRUD operations of a Web API
In the previous article we learned to add Swagger and Scalar to a Web API project. I have already explained Swagger integration in more detail here and here. So, it's time to focus on Scalar and learn how to test Web API CRUD operations.
We are going to use the same project that we used in the previous article. So, make sure you have all the necessary code files.
First, we will complete the Employees Web API controller that performs CRUD operations on the Employees table. We will then test those operations using Scalar.
Since we want to use EF Core for database operations, add Microsoft.EntityFrameworkCore.SqlServer NuGet package in your project.
Then add a folder named DataAccess under project root and four C# class files -- Employee.cs, AppDbContext.cs, IEmployeeRepository.cs, and EmployeeRepository.cs in the DataAccess folder.
The Employee.cs houses an entity class as shown below:
public class Employee
{
[Required]
public Guid EmployeeID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public DateOnly HireDate { get; set; }
}
The AppDbContext class represents a custom DbContext as required for EF Core operations.
public class AppDbContext : DbContext
{
public AppDbContext
(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Employee> Employees
{ get; set; } = default!;
}
The IEmployeeRepository interface defines a simple interface for performing CRUD operations and is shown below:
public interface IEmployeeRepository
{
List<Employee> SelectAll();
Employee SelectByID(Guid id);
void Insert(Employee emp);
void Update(Employee emp);
void Delete(Guid id);
}
The EmployeeRepository class implements IEmployeeRepository and uses EF Core methods such as Add(), Update(), Remove(), and SaveChanges() to perform the CRUD operations.
public class EmployeeRepository :
IEmployeeRepository
{
private readonly AppDbContext db;
public EmployeeRepository(AppDbContext db)
{
this.db = db;
}
public List<Employee> SelectAll()
{
return db.Employees.ToList();
}
public Employee SelectByID(Guid id)
{
return db.Employees.Find(id);
}
public void Insert(Employee emp)
{
db.Employees.Add(emp);
db.SaveChanges();
}
public void Update(Employee emp)
{
db.Employees.Update(emp);
db.SaveChanges();
}
public void Delete(Guid id)
{
db.Employees.Remove
(db.Employees.Find(id));
db.SaveChanges();
}
}
Next, create a new folder called ApiControllers under the project root and add an web API controller class named EmployeesController in it.
The EmployeesController will have actions to handle GET, POST, PUT, and DELETE verbs and is shown below:
[ApiController]
[Route("api/[controller]")]
public class EmployeesController
: ControllerBase
{
private readonly IEmployeeRepository
repository;
public EmployeesController
(IEmployeeRepository repository)
{
this.repository = repository;
}
[HttpGet]
public IActionResult Get()
{
return Ok(repository.SelectAll());
}
[HttpGet("{id}")]
public IActionResult Get(Guid id)
{
return Ok(repository.SelectByID(id));
}
[HttpPost]
public IActionResult Post(Employee emp)
{
repository.Insert(emp);
return CreatedAtAction("Get",
new { id = emp.EmployeeID }, emp);
}
[HttpPut("{id}")]
public IActionResult Put(Guid id, Employee emp)
{
repository.Update(emp);
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(Guid id)
{
repository.Delete(id);
return NoContent();
}
}
The five actions of the Web API controller -- SelectAll(), SelectByID(), Insert(), Update(), and Delete() deal with the GET, POST, PUT, and DELETE verbs respectively. The API actions use the EmployeeRepository to perform the CRUD operations.
Now that all the classes are ready, we will store database connection string in appsettings.json and also register the AppDbContext in Program.cs.
So, open appsettings.json and add the following:
"ConnectionStrings": {
"AppDb" : "Data Source=.;Initial Catalog=CodeDb;
User ID=*****;
Password=*****;
encrypt=false"
}
Make sure to substitute User ID and Password values as per your database setup.
Now open Program.cs and add this:
var builder = WebApplication.CreateBuilder(args);
var connStr = builder.Configuration.
GetConnectionString("AppDb");
builder.Services.AddDbContext
<AppDbContext>(options =>
options.UseSqlServer(connStr));
builder.Services.AddScoped
<IEmployeeRepository, EmployeeRepository>();
// other code
This code reads database connection string from appsettings.json and registers AppDbContext using the AddDbContext() method. It also registers repository class EmployeeRepository using AddScoped() method.
If you run the app and navigate to /Scalar/v1, you will see this:
As you can see, it now shows all the actions of EmployeesController. You can go to the individual action and invoke it by passing the required parameters and / or data. Let's do that one by one.
Let's assume that the Employees table is empty. So, we will use POST action to add a record. Click on the POST method from the Scalar user interface to go to that method. The left side of the UI shows the body and responses of the action.
On the right side you can see the code that can be used to call that method. Here you can pick programming language of your choice such as C# or Java. Select C# to see how HttpClient can be used to call this method.
There is also Test Request button to invoke that method. Clicking on the Test Request button opens this dialog.
Here, you can enter the JSON body of the request (Employee object) and click on the Send button to invoke the action. A sample JSON body is given below:
{
"employeeID": "1f02f618-eca6-4c37-a3e2-a0b3f7552516",
"firstName": "firstName1",
"lastName": "lastName1",
"hireDate": "1980-12-23"
}
The action will be executed and the response will be shown on the right hand side of the UI. A sample response is shown below:
Let's confirm whether the sample Employee got added to the database by invoking the SelectAll() action.
Click on the first GET action in the Scalar UI and click on the Test Request button.
Invoke the action and see whether the sample Employee appears in the response or not.
Let's try modifying an Employee record. Click on the PUT action to go to its details and then click on the Test Request button.
The PUT action requires an EmployeeID in a route parameter and the modified Employee object in the request body.
Click on the Send button to update the Employee.
Let's call SelectByID() to check whether our PUT request did the job of updating the employee details.
Click on the second GET action in the Scalar UI and further click on the Test Request button.
Enter employeeID in the Path Variables textbox (id) and click on the Send button. You will see the modified employee details as shown below:
Finally, it's time to test the Delete() action. Click on the DEL entry from the left hand side and then click on the Test Request button as before.
Enter an employee ID value in the Path Variables textbox and click on the Send button.
As you can see, Scalar allows you to quickly test your Web APIs using the builtin UI. You can also get C# code to invoke the Web API that can be used in your .NET client applications.
That's it for now! Keep coding!!