Building a Simple ASP.NET Core Web API

A Step-by-Step Guide for Beginners

Introduction

This tutorial will guide you through creating a basic Web API using ASP.NET Core. Web APIs allow you to build HTTP services that can be consumed by a wide range of clients, including single-page applications, mobile apps, and other backend services.

Step 1: Create a New ASP.NET Core Web API Project

Open your terminal or command prompt and use the .NET CLI to create a new Web API project:

dotnet new webapi -n MySimpleApi
cd MySimpleApi

This command creates a new project named MySimpleApi with a default project structure and a sample controller.

Step 2: Define Your Data Model

Let's create a simple model to represent the data we'll be working with. Create a new folder named Models in your project root and add a new C# file called TodoItem.cs.

namespace MySimpleApi.Models
{
    public class TodoItem
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}

Step 3: Create a Web API Controller

ASP.NET Core uses controllers to handle incoming HTTP requests. Replace the contents of the generated Controllers/WeatherForecastController.cs file with the following code for a TodoItemsController. You can also create a new controller file in the Controllers folder.

using Microsoft.AspNetCore.Mvc;
using MySimpleApi.Models;
using System.Collections.Generic;
using System.Linq;

namespace MySimpleApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoItemsController : ControllerBase
    {
        private static List<TodoItem> _todoItems = new List<TodoItem>
        {
            new TodoItem { Id = 1, Name = "Learn ASP.NET Core", IsComplete = false },
            new TodoItem { Id = 2, Name = "Build a Web API", IsComplete = false },
            new TodoItem { Id = 3, Name = "Deploy the API", IsComplete = false }
        };

        // GET: api/TodoItems
        [HttpGet]
        public ActionResult<IEnumerable<TodoItem>> GetAllTodoItems()
        {
            return Ok(_todoItems);
        }

        // GET: api/TodoItems/5
        [HttpGet("{id}", Name = "GetTodoItem")]
        public ActionResult<TodoItem> GetTodoItem(long id)
        {
            var todoItem = _todoItems.FirstOrDefault(t => t.Id == id);
            if (todoItem == null)
            {
                return NotFound();
            }
            return Ok(todoItem);
        }

        // POST: api/TodoItems
        [HttpPost]
        public ActionResult<TodoItem> CreateTodoItem([FromBody] TodoItem todoItem)
        {
            todoItem.Id = _todoItems.Count + 1;
            _todoItems.Add(todoItem);
            return CreatedAtRoute("GetTodoItem", new { id = todoItem.Id }, todoItem);
        }

        // PUT: api/TodoItems/5
        [HttpPut("{id}")]
        public IActionResult UpdateTodoItem(long id, [FromBody] TodoItem updatedTodoItem)
        {
            var todoItem = _todoItems.FirstOrDefault(t => t.Id == id);
            if (todoItem == null)
            {
                return NotFound();
            }

            todoItem.Name = updatedTodoItem.Name;
            todoItem.IsComplete = updatedTodoItem.IsComplete;

            return NoContent();
        }

        // DELETE: api/TodoItems/5
        [HttpDelete("{id}")]
        public IActionResult DeleteTodoItem(long id)
        {
            var todoItem = _todoItems.FirstOrDefault(t => t.Id == id);
            if (todoItem == null)
            {
                return NotFound();
            }

            _todoItems.Remove(todoItem);
            return NoContent();
        }
    }
}

In this controller:

  • [Route("api/[controller]")] sets the base route for this controller to /api/TodoItems.
  • [ApiController] attribute enables API-specific behaviors.
  • We use a static list to simulate a database for simplicity.
  • HTTP methods like [HttpGet], [HttpPost], [HttpPut], and [HttpDelete] define the endpoints for different operations.

Step 4: Run Your API

Save your changes and run the application from your terminal:

dotnet run

The application will start, and you'll see output indicating the URLs where your API is listening. Typically, this will include a local URL like https://localhost:5001 or http://localhost:5000.

By default, ASP.NET Core Web API projects include Swagger/OpenAPI support. You can access the interactive API documentation by navigating to /swagger in your browser (e.g., https://localhost:5001/swagger). This provides a user-friendly interface to test your API endpoints directly.

Conclusion

Congratulations! You've successfully created and run a simple ASP.NET Core Web API. This basic setup demonstrates how to define models, create controllers with CRUD (Create, Read, Update, Delete) operations, and serve data over HTTP. From here, you can explore more advanced topics such as database integration, authentication, error handling, and more.