Building Minimal API Endpoints in ASP.NET Core (.NET 7)

Building Minimal API Endpoints in ASP.NET Core (.NET 7)

ASP.NET Core is a powerful framework for building web applications, and it includes a built-in API framework that makes it easy to create RESTful API endpoints. In this article, we'll take a look at how to create minimal API endpoints in ASP.NET Core (.NET 7) using the built-in features.

Step 1: Creating a new ASP.NET Core Web API Project

The first step is to create a new ASP.NET Core Web API project. You can do this by opening Visual Studio and selecting "Create a new project." Select the "ASP.NET Core Web API" template and name your project.

Step 2: Defining the API Endpoints

Next, we'll define the API endpoints. In the "Startup" class, you'll find the "Configure" method. This is where you can define the routes for your API.

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/api/values", (context) =>
    {
        return context.Response.WriteAsync("Hello, World!");
    });
});

In this example, we're creating a single endpoint that responds to a GET request to the "/api/values" path. The anonymous function passed to "MapGet" is called when a request is made to that endpoint. In this example, we're simply returning "Hello, World!" as the response.

Step 3: Testing the API Endpoints

Now, you can run the application and test the API endpoints. You can use a tool like Postman to send a GET request to the "/api/values" endpoint and check the response.

Step 4: Adding Request and Response Models

In most cases, you'll want to add request and response models to your API endpoints. This allows you to define the structure of the data that's sent and received.

public class ValueRequest
{
    public string Name { get; set; }
}

public class ValueResponse
{
    public int Id { get; set; }
    public string Message { get; set; }
}

In this example, we're defining a "ValueRequest" model that includes a "Name" property and a "ValueResponse" model that includes an "Id" and "Message" property.

You can update the endpoint to use these models:

app.UseEndpoints(endpoints =>
{
    endpoints.MapPost("/api/values", async (context) =>
    {
        var request = await JsonSerializer.DeserializeAsync<ValueRequest>(context.Request.Body);

        var response = new ValueResponse
        {
            Id = 1,
            Message = $"Hello, {request.Name}!"
        };

        await JsonSerializer.SerializeAsync(context.Response.Body, response);
    });
});

In this example, we're using the "MapPost" method to handle a POST request to the "/api/values" endpoint. The request body is deserialized into the "ValueRequest" model and a new "ValueResponse" model is created with a message that includes the name from the request. The response is then serialized and returned to the client.

Step 5: Adding Error Handling

You should always add error handling to your API endpoints. You can use the built-in exception handling features of ASP.NET Core to catch and handle exceptions.

app.UseEndpoints(endpoints =>
{
    endpoints.MapPost("/api/values", async (context) =>
    {
        try
        {
            var request = await JsonSerializer.DeserializeAsync<ValueRequest>(context.Request.Body);

            var response = new ValueResponse
            {
                Id = 1,
                Message = $"Hello, {request.Name}!"
            };

            await JsonSerializer.SerializeAsync(context.Response.Body, response);
        }
        catch (Exception ex)
        {
            context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            await context.Response.WriteAsync(ex.Message);
        }
    });
});

In this example, we're wrapping the endpoint logic in a try-catch block. Any exceptions that are thrown will be caught and handled by the catch block. In this example, we're setting the response status code to "BadRequest" and returning the exception message to the client.

Conclusion

In this article, we've seen how to create minimal API endpoints in ASP.NET Core (.NET 7) using the built-in features. We've looked at how to define the routes, add request and response models, and handle errors. This is just the tip of the iceberg when it comes to building API endpoints in ASP.NET Core, but it should give you a good starting point for building your own APIs.

Post a Comment

Previous Post Next Post