Creating and Consuming a Web API in C#

Creating and Consuming a Web API in C#

This simple tutorial will guide you through the steps to create a simple Web API using C# and .NET Core and then test it using Postman.

Step 1: Setting up the Web API Project

First, open Visual Studio and create a new ASP.NET Core Web API project.

  1. Open Visual Studio and select Create a new project.
  2. Choose ASP.NET Core Web API and click Next.
  3. Configure your new project by setting the project name, location, and solution name, then click Create.
  4. Select the target framework (.NET 6.0 or later) and click Create.

Step 2: Creating the API Controller

In the solution explorer, right-click the Controllers folder and add a new controller.

  1. Right-click the Controllers folder, select Add, then New Item.
  2. Choose API Controller - Empty and name it ProductsController, then click Add.

Replace the content of ProductsController.cs with the following code:


using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace YourNamespace.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private static readonly List Products = new List
        {
            "Product1",
            "Product2",
            "Product3"
        };

        [HttpGet]
        public ActionResult> Get()
        {
            return Products;
        }

        [HttpGet("{id}")]
        public ActionResult Get(int id)
        {
            if (id < 0 || id >= Products.Count)
            {
                return NotFound();
            }

            return Products[id];
        }

        [HttpPost]
        public void Post([FromBody] string value)
        {
            Products.Add(value);
        }

        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
            if (id >= 0 && id < Products.Count)
            {
                Products[id] = value;
            }
        }

        [HttpDelete("{id}")]
        public void Delete(int id)
        {
            if (id >= 0 && id < Products.Count)
            {
                Products.RemoveAt(id);
            }
        }
    }
}
        

Step 3: Running the API

Now, run the API by pressing F5 or clicking the Run button in Visual Studio. The API will start, and you should see a browser window open with the URL https://localhost:{port}/api/products.

You can test the API endpoints using a web browser or Postman.

Step 4: Consuming the API with Postman

Postman is a powerful tool for testing APIs. Follow these steps to test your API:

  1. Open Postman and create a new request.
  2. Set the request type to GET and enter the URL https://localhost:{port}/api/products. Click Send to get the list of products.
  3. To test other endpoints, change the request type and URL accordingly:
    • GET https://localhost:{port}/api/products/{id} to get a product by ID.
    • POST https://localhost:{port}/api/products with a JSON body to add a new product (e.g., {"value":"Product4"}).
    • PUT https://localhost:{port}/api/products/{id} with a JSON body to update a product (e.g., {"value":"UpdatedProduct"}).
    • DELETE https://localhost:{port}/api/products/{id} to delete a product by ID.

Note: Replace {port} with the actual port number your application is running on, which you can find in the browser address bar or in the application properties in Visual Studio.

Conclusion

In this tutorial, you learned how to create a simple Web API using C# and .NET Core and how to test it using Postman. This is just a starting point; you can extend the API with more complex logic, authentication, and other features as needed.

Any Query / Enrollment Request



Google Review Testimonials

.NET Online Training
Average Rating: 4.9
Votes: 50
Reviews: 50