अजपा योग क्रिया आणि ध्यान : श्वास, मंत्र, मुद्रा आणि ध्यान यांच्या सहाय्याने मनःशांती, एकाग्रता, चक्र संतुलन आणि कुंडलिनी जागृती. अधिक माहिती आणि आगामी तारखांसाठी येथे जा.


Test APIs using Endpoints Explorer and .http files

ASP.NET Core web developers often need to test the controller based APIs and minimal APIs they add in their projects. Typically developers use tools such as Postman or Swagger for this purpose. Visual Studio 2022 now has tools that can come handy for quickly testing your APIs. This article explains these tools with an example.

Visual Studio 2022 version 17.6 and later provide what is known as an Endpoint Explorer that can be used to view and test API endpoints defined in your project. This tool can be accessed using View -- Other Windows -- Endpoints Explorer menu option.

To see this tool in action we first need to create an API. So, begin by creating a new ASP.NET Core project based on Empty project template. You can also go for API project template if you want.

We will quickly create a controller based API and a minimal APIs. These APIs will perform CRUD operation on the Customers table of the Northwind database.

Open appsettings.json file and place the database connection string in the ConnectionStrings section as shown below.

"ConnectionStrings": {
    "AppDb": "data source=.;
              initial catalog=Northwind;
              integrated security=true;
              Encrypt=False"
}    

Make sure to change the connection string according to your database setup.

Then add a folder to the project named DataAccess and add two classes in it -- Customer and AppDbContext. These classes are shown below.

public class Customer
{
    [Key]
    [Required]
    public string CustomerID { get; set; }

    [Required]
    public string CompanyName { get; set; }

    [Required]
    public string ContactName { get; set; }

    [Required]
    public string Country { get; set; }
}

public class AppDbContext:DbContext
{
    public DbSet<Customer> 
        Customers { get; set; }

    public DbSet<Employee> 
        Employees { get; set; }

    public AppDbContext
    (DbContextOptions<AppDbContext> 
        options):base(options)
    {

    }
}

Now add a folder named ApiControllers and add a new controller based API class named CustomersController in it.

Add the following actions to the newly added CustomersController class.

[Route("api/[controller]")]
[ApiController]
public class CustomersController : ControllerBase
{
    private AppDbContext db = null;

    public CustomersController(AppDbContext db)
    {
        this.db = db;
    }

    [HttpGet]
    public async Task<IActionResult> 
        GetAsync()
    {
        List<Customer> data = await 
            db.Customers.ToListAsync();
        return Ok(data);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> 
        GetAsync(string id)
    {
        Customer emp = await 
        db.Customers.FindAsync(id);
        return Ok(emp);
    }

    [HttpPost]
    public async Task<IActionResult> 
        PostAsync([FromBody] Customer cust)
    {
        await db.Customers.AddAsync(cust);
        await db.SaveChangesAsync();
        return CreatedAtAction
        ("Get", new { id = cust.CustomerID }, cust);
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> 
        PutAsync(string id, [FromBody] Customer cust)
    {
        
        db.Customers.Update(cust);
        await db.SaveChangesAsync();
        return NoContent();
    }

    [HttpDelete("{id}")]
    public async Task<IActionResult> 
        DeleteAsync(string id)
    {
        Customer cust = await db.Customers.FindAsync(id);
        db.Customers.Remove(cust);
        await db.SaveChangesAsync();
        return NoContent();
    }
}    

I won't go in the details of this API since it's actions are quite straightforward. We will also add minimal API equivalent of these actions in Program.cs.

app.MapGet("/minimalapi/customers", 
async (AppDbContext db) =>
{
    List<Customer> data = await 
        db.Customers.ToListAsync();
    return Results.Ok(data);
});


app.MapGet("/minimalapi/customers/{id}", 
async (AppDbContext db, string id) =>
{
    Customer emp = await db.Customers.
    FindAsync(id);
    return Results.Ok(emp);
});


app.MapPost("/minimalapi/customers", 
async (AppDbContext db, Customer cust) =>
{
    await db.Customers.AddAsync(cust);
    await db.SaveChangesAsync();
    return Results.Created
    ("/minimalapi/employees", cust);
});


app.MapPut("/minimalapi/customers/{id}", 
async (AppDbContext db, string id, 
Customer cust) =>
{
    db.Customers.Update(cust);
    await db.SaveChangesAsync();
    return Results.NoContent();
});


app.MapDelete("/minimalapi/customers/{id}", 
async (AppDbContext db, string id) =>
{
    Customer cust = await db.Customers.
    FindAsync(id);
    db.Customers.Remove(cust);
    await db.SaveChangesAsync();
    return Results.NoContent();
});    

After adding the controller based API and minimal API, run the app to open a browser window. Navigate to /api/customers and /minimalapi/customers to quickly check whether the GET requests are returning data. The following figure shows a sample run of the app.

Now let's see all the API endpoints developed in the Endpoints Explorer. Open Endpoints Explorer as explained earlier and see whether all the endpoints are listed.

The following figure shows Endpoints Explorer with total ten endpoints - five from controller based API and five from minimal API.

You can expand each of the endpoint listed to see its details :

Next, we will test the CRUD functionality of the controller based API using Endpoints Explorer.

To do so, right click on the GET endpoint in the Endpoints Explorer to reveal a shortcut menu as shown below:

The Open in the editor option allows you to edit the endpoint in the respective file (CustomersController.cs in this case OR Program.cs for minimal APIs).

The Generate Request option allows you to generate an HTTP request to the endpoint. The request details are stored in a file <project_name>.http. This file gets automatically created if it doesn't exist already; otherwise an existing file is used. You can also add a .http file manually using Add New Item dialog.

Right click on the GET endpoint and click on the Generate Request menu option. This will add the following code to the .http file.

@WebApiHttpDemo_HostAddress = https://localhost:7078

GET {{WebApiHttpDemo_HostAddress}}/api/customers

###

The first line declares a variable called @WebApiHttpDemo_HostAddress and sets its value to the base URL of the API.

Then there is GET verb followed by the request URL. The {{WebApiHttpDemo_HostAddress}} will fill the value of @WebApiHttpDemo_HostAddress and /api/customers is appended to it.

Finally, you have comment line beginning with #.

To test the GET request, first run the application and then switch back to the .http file. The GET request will have Send Request link as shown below:

Click on the Send Request link to send a GET request to the specified URL.

When you do that a green indicator appears immediately before the Send Request link telling you that the request is in progress.

Upon successful completion of the request another green indicator confirms the completion.

You will also see the outcome in the response pane :

You can set breakpoints in the CustomersController.cs file so that you can confirm that an action is getting called as expected.

Once you successfully execute the GET request, repeat the process for GET by ID. This time Endpoints Explorer will generate this code :

GET {{WebApiHttpDemo_HostAddress}}/api/customers/string

###

Change the URL to have a real CustomerID from the database :

GET {{WebApiHttpDemo_HostAddress}}/api/customers/ALFKI

###

Run the request and confirm the working as before.

For the POST action, Endpoints Explorer generated code looks like this :

POST {{WebApiHttpDemo_HostAddress}}/api/customers
Content-Type: application/json

{
    //Customer
}

###    

As you can see, it makes a POST request to the specified URL and also specifies Content-Type header. The POST request needs a Customer JSON object that you need to fill.

POST {{WebApiHttpDemo_HostAddress}}/api/customers
Content-Type: application/json

{
    "customerID" : "ABCDE",
    "companyName" : "Company 1",
    "contactName" : "Contact 1",
    "country" : "Country 1"
}

###    

On the similar lines you can generate PUT and DELETE requests.

PUT {{WebApiHttpDemo_HostAddress}}/api/customers/ABCDE
Content-Type: application/json

{
    "customerID" : "ABCDE",
    "companyName" : "Company Changed",
    "contactName" : "Contact Changed",
    "country" : "Country 1"
}

###

DELETE {{WebApiHttpDemo_HostAddress}}/api/customers/ABCDE

###    

In the preceding example you used Endpoints Explorer to generate requests in the .http file. Let's create another .http file and add the code manually for testing the minimal APIs.

Add a new .http file named app.http to the project using Add New Item dialog.

Then write the following code into the app.http file :

@WebApiHttpDemo_HostAddress = https://localhost:7078

GET {{WebApiHttpDemo_HostAddress}}/minimalapi/customers

###

POST {{WebApiHttpDemo_HostAddress}}/minimalapi/customers
Content-Type: application/json

{
  "customerID" : "ABCDE",
  "companyName" : "Company 1",
  "contactName" : "Contact 1",
  "country" : "Country 1"
}

###

GET {{WebApiHttpDemo_HostAddress}}/minimalapi/customers/ALFKI

###

PUT {{WebApiHttpDemo_HostAddress}}/minimalapi/customers/ABCDE
Content-Type: application/json

{
  "customerID" : "ABCDE",
  "companyName" : "Company Changed",
  "contactName" : "Contact Changed",
  "country" : "Country 1"
}

###

DELETE {{WebApiHttpDemo_HostAddress}}/minimalapi/customers/ABCDE

###

This code is quite similar to the one we generated earlier using the Endpoints Explorer. The only difference is that all the URLs point to the minimal API endpoints rather than controller based API endpoints.

Save the file and test all the minimal API endpoints as before.

To read more about .http file syntax read official documentation here.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Ajapa Japa and Shambhavi Mudra online course are available here.

Posted On : 18 September 2023