Create a Web API in ASP.NET Core
This tutorial guides you through the process of creating a simple Web API using ASP.NET Core. We'll cover setting up the project, defining models, controllers, and handling HTTP requests.
1. Project Setup
Start by creating a new ASP.NET Core Web API project using the .NET CLI or Visual Studio.
dotnet new webapi -n MyWebApi
cd MyWebApi
This command creates a new project named MyWebApi with a default structure for building Web APIs.
2. Define Data Models
Let's define a simple model to represent the data we'll be working with. Create a new folder named Models and add a file named TodoItem.cs.
namespace MyWebApi.Models
{
public class TodoItem
{
public long Id { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
}
3. Create a Controller
Controllers are responsible for handling incoming requests and returning responses. Create a new folder named Controllers and add a file named TodoItemsController.cs.
using Microsoft.AspNetCore.Mvc;
using MyWebApi.Models;
using System.Collections.Generic;
using System.Linq;
namespace MyWebApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TodoItemsController : ControllerBase
{
private static List _todoItems = new List
{
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> GetTodoItems()
{
return _todoItems;
}
// GET: api/TodoItems/5
[HttpGet("{id}")]
public ActionResult GetTodoItem(long id)
{
var todoItem = _todoItems.FirstOrDefault(t => t.Id == id);
if (todoItem == null)
{
return NotFound();
}
return todoItem;
}
// POST: api/TodoItems
[HttpPost]
public ActionResult PostTodoItem(TodoItem todoItem)
{
todoItem.Id = _todoItems.Count + 1;
_todoItems.Add(todoItem);
return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);
}
// PUT: api/TodoItems/5
[HttpPut("{id}")]
public IActionResult PutTodoItem(long id, TodoItem todoItem)
{
var existingItem = _todoItems.FirstOrDefault(t => t.Id == id);
if (existingItem == null)
{
return NotFound();
}
existingItem.Name = todoItem.Name;
existingItem.IsComplete = todoItem.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();
}
}
}
Note: In a real-world application, you would typically use a database for persistent storage instead of an in-memory list.
4. Run the Application
You can now run your Web API project.
dotnet run
This will start the server, and you can access your API endpoints using tools like Postman or by navigating to the URLs in your browser (for GET requests).
5. Testing the API
Here are some examples of how you can interact with your API:
- GET all items:
GET /api/TodoItems - GET a specific item:
GET /api/TodoItems/1 - POST a new item: Send a POST request to
with a JSON body like:/api/TodoItems{ "name": "Test new item", "isComplete": false } - PUT an existing item: Send a PUT request to
with a JSON body to update it./api/TodoItems/1 - DELETE an item: Send a DELETE request to
./api/TodoItems/3
Tip: ASP.NET Core Web API provides built-in support for OpenAPI (Swagger), which you can enable to generate interactive API documentation.
Congratulations! You have successfully created a basic Web API in ASP.NET Core. You can now expand upon this foundation by adding more features, data persistence, and error handling.