Welcome to the course "Creating a REST API with Minimal APIs"! This is the second course in our course path on building minimal API applications with ASP.NET Core. In the first course, you learned the basics of ASP.NET Core, got familiar with its project structure, understood the concept of middleware, learned how to handle exceptions, and created your first minimal API application with a single GET endpoint. In this course, we will dive deeper into defining and handling API endpoints. By the end of this course, you will have a functional minimal API application that allows you to manage your To Do list: adding, retrieving, updating, and deleting tasks. This lesson specifically focuses on defining endpoints for various operations on ToDo items. Let's dive in!
Representational State Transfer (REST) is a simple yet powerful way to design communication between computers over the internet. Think of it as a set of rules that helps computers talk to each other clearly, using the web. REST uses HTTP, the same protocol that your web browser uses to look at websites.
In REST, resources like your to-do list items are identified by URLs. For instance:
- A URL like
http://example.com/todo/1
might represent the first item on your to-do list. - Another URL like
http://example.com/todo/2
could represent the second item.
The URL points to a specific resource, while the method (or HTTP verb) specifies the operation to be performed on that resource.
To interact with a web API and perform operations on resources identified by URLs, you use HTTP verbs. These verbs define the type of operation you are performing. The most common HTTP verbs and their corresponding ASP.NET Core methods are shown in the table below:
HTTP Verb | ASP.NET Core Method | Expected Operation |
---|---|---|
GET | MapGet | Retrieve data |
POST | MapPost | Create new data |
PUT | MapPut | Update existing data |
DELETE | MapDelete | Delete data |
PATCH | MapPatch | Partially update data |
Although PATCH is included for completeness in this lesson, we will not be practicing it in this course since it is less frequently used compared to the other methods.
In ASP.NET Core Minimal APIs, you can extract values from the URL using routing. For example, to retrieve a specific Todo item by its ID, you can define a route like /todo/{id}
. Here’s how you can extract the id
from the URL:
C#1app.MapGet("/todo/{id}", (string id) =>
2{
3 // Logic to handle the GET request using the extracted id
4});
In this example, {id}
is a placeholder in the URL that will be replaced with the actual ID when the request is made. Below are some examples of URLs that would match this endpoint:
/todo/1
whereid
will be1
/todo/abc-123
whereid
will beabc-123
/todo/42
whereid
will be42
To manage different operations on ToDo items, you need to define handlers for each HTTP verb. The following example shows how to set up the Program.cs
file with route handlers:
C#1var builder = WebApplication.CreateBuilder(args);
2var app = builder.Build();
3
4TodoHandlers handlers = new();
5
6app.MapGet("/todo", handlers.GetAllTodos);
7app.MapGet("/todo/{id}", handlers.GetTodo);
8app.MapPost("/todo", (TodoItem todo) => handlers.AddTodo(todo));
9app.MapPut("/todo/{id}", handlers.ReplaceTodo);
10app.MapDelete("/todo/{id}", handlers.DeleteTodo);
11
12app.Run();
Here, we first create a WebApplication
instance using the builder pattern. Then, we create an instance of the TodoHandlers
class. We define the routes using app.MapGet
, app.MapPost
, app.MapPut
, and app.MapDelete
, each mapped to the corresponding handler method. The application listens to HTTP requests and routes them to the appropriate handler based on the route and HTTP verb. Finally, we call app.Run()
to start the application.
The handlers are defined in the TodoHandlers
class as follows:
C#1public class TodoHandlers 2{ 3 public IEnumerable<TodoItem> GetAllTodos() 4 { 5 return TodoItem.All.Values; 6 } 7 8 public TodoItem GetTodo(string id) 9 { 10 return TodoItem.All[id]; 11 } 12 13 public void ReplaceTodo(string id, TodoItem todo) 14 { 15 TodoItem.All[id] = todo; 16 } 17 18 public void DeleteTodo(string id) 19 { 20 TodoItem.All.Remove(id); 21 } 22 23 public void AddTodo(TodoItem todo) 24 { 25 var id = Guid.NewGuid().ToString(); 26 var newTodo = new TodoItem(id, todo.Description, todo.IsCompleted); 27 TodoItem.All.Add(id, newTodo); 28 } 29}
Let’s break down the handlers defined in the TodoHandlers
class:
- Get All Todos: This handler retrieves all Todo items.
- Get Todo by ID: This handler retrieves a specific Todo item by its ID.
- Add Todo: This method adds a new Todo item to the collection. We generate a unique identifier for each new Todo item using the
Guid.NewGuid().ToString()
method. AGuid
(Globally Unique Identifier) is a 128-bit value used to uniquely identify information. In ASP.NET Core,Guid.NewGuid()
ensures a unique ID for new resources, avoiding duplicate identifiers. For example, a generated ID might look like3f1e4d29-2f10-4bdc-9a1c-6a6cbd1a20d9
. - Replace Todo: This handler updates an existing Todo item based on its ID.
- Delete Todo: This handler deletes a ToDo item by its ID.
In this lesson, we covered an overview of common HTTP verbs and their corresponding ASP.NET Core methods, how to extract values from URLs using routing, and how to define route handlers for different HTTP verbs. You are now equipped to define and handle API endpoints using ASP.NET Core Minimal APIs. Great job!