Minimal WebAPIs offer a lightweight and streamlined approach to building web APIs in ASP.NET Core. In this beginner’s guide, we will explore the fundamental concepts of Minimal WebAPI development using C#. We’ll cover the basics of creating endpoints, handling requests, and returning responses.
Prerequisites
To follow along with this guide, you should have a basic understanding of C# and ASP.NET Core.
Setting Up the Project:
- Launch Visual Studio or your preferred code editor.
- Create a new ASP.NET Core project.
- Choose the “Minimal API” template to create a minimalistic API project.
Defining Endpoints
Minimal WebAPIs use lambda expressions and top-level statements to define endpoints concisely. Let’s create a simple “Hello, World!” endpoint:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
var app = WebApplication.Create();
app.MapGet("/", () => "Hello, World!");
app.Run();
Handling Requests
Minimal WebAPIs use the HttpContext object to access the request and response data. Let’s create an endpoint that receives a name parameter and returns a personalized greeting:
app.MapGet("/greet/{name}", (HttpContext context) =>
{
var name = context.Request.RouteValues["name"];
return $"Hello, {name}!";
});
Returning JSON Responses
To return JSON responses, we can utilize the JsonResult object and the System.Text.Json namespace:
using System.Text.Json;
app.MapGet("/api/data", () =>
{
var data = new { Name = "John Doe", Age = 30 };
return new JsonResult(data, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
});
Routing and Parameter Binding
Minimal WebAPIs support route-based parameter binding. Let’s create an endpoint that accepts query parameters:
app.MapGet("/api/books", (int id, string category) =>
{
// Retrieve book data based on the provided id and category
// ...
return new { BookId = id, Category = category };
});
Error Handling
To handle errors in Minimal WebAPIs, we can use the ProblemDetails class:
using Microsoft.AspNetCore.Http;
app.UseExceptionHandler(app =>
{
app.Run(async context =>
{
var ex = context.Features.Get<IExceptionHandlerFeature>().Error;
var problemDetails = new ProblemDetails
{
Title = "An error occurred",
Detail = ex.Message,
Status = StatusCodes.Status500InternalServerError
};
context.Response.StatusCode = problemDetails.Status.Value;
await context.Response.WriteAsJsonAsync(problemDetails);
});
});
Conclusion
In this beginner’s guide, we explored the basics of creating a Minimal WebAPI using C#. We covered defining endpoints, handling requests, returning responses, working with JSON, routing, parameter binding, and error handling. Armed with this knowledge, you can start building minimal and efficient WebAPIs with ease.
Remember, Minimal WebAPIs prioritize simplicity and conciseness, allowing you to focus on essential functionality while keeping your codebase minimal and maintainable. In future post, we will be diving deeper into each of these topics to see how to apply them in your next WebAPI.