.NET Core Web API Basics: Building Your First API

1 February 2017

In this post, we’ll explore how to build a simple RESTful Web API using .NET Core. APIs are an essential part of modern web development, and knowing how to create them from scratch is a crucial skill. We’ll go step by step to set up a basic Web API, including defining controllers, setting up routes, and using common HTTP methods like GET, POST, PUT, and DELETE.

1. What Is a Web API?

A Web API (Application Programming Interface) is a set of rules and protocols that allow one piece of software to communicate with another. In the context of .NET Core, a Web API exposes functionality that can be accessed over HTTP, making it a common choice for building backend services that interact with web applications, mobile apps, or third-party services.

2. Setting Up a Simple .NET Core Web API

Before we start building the API, make sure you have .NET Core SDK installed on your machine. If you haven’t done so yet, follow the setup instructions in one of the earlier posts.

Once you have .NET Core set up, create a new Web API project using the dotnet new command:

dotnet new webapi -n MyFirstApi

This will create a new Web API project called MyFirstApi. Once the project is generated, navigate into the project directory:

cd MyFirstApi

Now, open the project in your favorite editor (Visual Studio Code, for example).

3. Creating a Simple Controller

Controllers are the heart of a Web API in .NET Core. They handle incoming HTTP requests and return responses. The default project template already includes a WeatherForecastController, but let’s create a custom controller for this tutorial.

Create a new file called ProductsController.cs in the Controllers folder. In this file, you’ll define a simple controller to handle requests related to products.

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

namespace MyFirstApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        // A simple in-memory list of products
        private static readonly List<string> Products = new List<string>
        {
            "Apple",
            "Banana",
            "Orange"
        };

        // GET: api/products
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return Ok(Products);
        }

        // POST: api/products
        [HttpPost]
        public ActionResult Post([FromBody] string product)
        {
            Products.Add(product);
            return CreatedAtAction(nameof(Get), new { name = product }, product);
        }

        // PUT: api/products/{name}
        [HttpPut("{name}")]
        public IActionResult Put(string name, [FromBody] string newName)
        {
            var product = Products.Find(p => p == name);
            if (product == null)
            {
                return NotFound();
            }

            Products.Remove(product);
            Products.Add(newName);
            return NoContent();
        }

        // DELETE: api/products/{name}
        [HttpDelete("{name}")]
        public IActionResult Delete(string name)
        {
            var product = Products.Find(p => p == name);
            if (product == null)
            {
                return NotFound();
            }

            Products.Remove(product);
            return NoContent();
        }
    }
}

4. Explanation of the Controller

  • Route: The [Route("api/[controller]")] attribute specifies the base route for the controller. In this case, it translates to api/products.
  • GET Method: The Get() method handles GET requests. It returns a list of products as a JSON array.
  • POST Method: The Post() method handles POST requests, allowing the user to add new products to the list. The [FromBody] attribute specifies that the product parameter should come from the request body.
  • PUT Method: The Put() method handles PUT requests to update a product. It takes the existing product name as part of the URL and the new name from the request body.
  • DELETE Method: The Delete() method handles DELETE requests to remove a product by its name.

5. Running the API

To run the Web API, use the following command:

dotnet run

The application should now be running on http://localhost:5000 (or another port if specified). You can test the API using Postman, curl, or simply your browser for the GET requests.

Here’s how you can test each HTTP method:

  • GET:
    Open your browser or use Postman to send a GET request to http://localhost:5000/api/products. It should return the list of products in JSON format.
  • POST:
    Use Postman or curl to send a POST request with the product name in the body to http://localhost:5000/api/products. For example, sending "Mango" will add it to the list.
  • PUT:
    Use Postman or curl to send a PUT request to http://localhost:5000/api/products/Apple with the new product name in the body (e.g., "Green Apple").
  • DELETE:
    Send a DELETE request to http://localhost:5000/api/products/Banana to remove "Banana" from the list.

6. Conclusion

In this tutorial, you’ve learned how to create a simple RESTful Web API using .NET Core. You now have a basic understanding of setting up controllers, defining routes, and handling basic HTTP methods like GET, POST, PUT, and DELETE.

This is just the beginning of what you can build with .NET Core Web APIs. In future posts, we’ll dive deeper into advanced concepts like authentication, database integration, and API documentation.

Happy coding!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *