Home Web Development Mastering Minimal APIs in ASP.NET Core

Mastering Minimal APIs in ASP.NET Core

By Andrea Tosato , Marco Minerva , Emanuele Bartolesi
books-svg-icon Book
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $33.99 $22.99
Print $41.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Introduction to Minimal APIs
About this book
The Minimal APIs feature, introduced in .NET 6, is the answer to code complexity and rising dependencies in creating even the simplest of APIs. Minimal APIs facilitate API development using compact code syntax and help you develop web APIs quickly. This practical guide explores Minimal APIs end-to-end and helps you take advantage of its features and benefits for your ASP.NET Core projects. The chapters in this book will help you speed up your development process by writing less code and maintaining fewer files using Minimal APIs. You’ll also learn how to enable Swagger for API documentation along with CORS and handle application errors. The book even promotes ideas to structure your code in a better way using the dependency injection library in .NET. Finally, you'll learn about performance and benchmarking improvements for your apps. By the end of this book, you’ll be able to fully leverage new features in .NET 6 for API development and explore how Minimal APIs are an evolution over classical web API development in ASP.NET Core.
Publication date:
October 2022
Publisher
Packt
Pages
240
ISBN
9781803237824

 

Introduction to Minimal APIs

In this chapter of the book, we will introduce some basic themes related to minimal APIs in .NET 6.0, showing how to set up a development environment for .NET 6 and more specifically for developing minimal APIs with ASP.NET Core.

We will first begin with a brief history of minimal APIs. Then, we will create a new minimal API project with Visual Studio 2022 and Visual Code Studio. At the end, we will take a look at the structure of our project.

By the end of this chapter, you will be able to create a new minimal API project and start to work with this new template for a REST API.

In this chapter, we will be covering the following topics:

  • A brief history of the Microsoft Web API
  • Creating a new minimal API project
  • Looking at the structure of the project
 

Technical requirements

To work with the ASP.NET Core 6 minimal APIs you need to install, first of all, .NET 6 on your development environment.

If you have not already installed it, let’s do that now:

  1. Navigate to the following link: https://dotnet.microsoft.com.
  2. Click on the Download button.
  3. By default, the browser chooses the right operating system for you, but if not, select your operating system at the top of the page.
  4. Download the LTS version of the .NET 6.0 SDK.
  5. Start the installer.
  6. Reboot the machine (this is not mandatory).

You can see which SDKs are installed on your development machine using the following command in a terminal:

dotnet –list-sdks

Before you start coding, you will need a code editor or an Integrated Development Environment (IDE). You can choose your favorite from the following list:

  • Visual Studio Code for Windows, Mac, or Linux
  • Visual Studio 2022
  • Visual Studio 2022 for Mac

In the last few years, Visual Studio Code has become very popular not only in the developer community but also in the Microsoft community. Even if you use Visual Studio 2022 for your day-to-day work, we recommend downloading and installing Visual Studio Code and giving it a try.

Let’s download and install Visual Studio Code and some extensions:

  1. Navigate to https://code.visualstudio.com.
  2. Download the Stable or the Insiders edition.
  3. Start the installer.
  4. Launch Visual Studio Code.
  5. Click on the Extensions icon.

You will see the C# extension at the top of the list.

  1. Click on the Install button and wait.

You can install other recommended extensions for developing with C# and ASP.NET Core. If you want to install them, you see our recommendations in the following table:

Additionally, if you want to proceed with the IDE that’s most widely used by .NET developers, you can download and install Visual Studio 2022.

If you don’t have a license, check if you can use the Community Edition. There are a few restrictions on getting a license, but you can use it if you are a student, have open source projects, or want to use it as an individual. Here’s how to download and install Visual Studio 2022:

  1. Navigate to https://visualstudio.microsoft.com/downloads/.
  2. Select Visual Studio 2022 version 17.0 or later and download it.
  3. Start the installer.
  4. On the Workloads tab, select the following:
    • ASP.NET and web development
    • Azure Development
  5. On the Individual Components tab, select the following:
    • Git for Windows

All the code samples in this chapter can be found in the GitHub repository for this book at https://github.com/PacktPublishing/Minimal-APIs-in-ASP.NET-Core-6/tree/main/Chapter01.

Now, you have an environment in which you can follow and try the code used in this book.

 

A brief history of the Microsoft Web API

A few years ago in 2007, .NET web applications went through an evolution with the introduction of ASP.NET MVC. Since then, .NET has provided native support for the Model-View-Controller pattern that was common in other languages.

Five years later, in 2012, RESTful APIs were the new trend on the internet and .NET responded to this with a new approach for developing APIs, called ASP.NET Web API. It was a significant improvement over Windows Communication Foundation (WCF) because it was easier to develop services for the web. Later, in ASP.NET Core these frameworks were unified under the name ASP.NET Core MVC: one single framework with which to develop web applications and APIs.

In ASP.NET Core MVC applications, the controller is responsible for accepting inputs, orchestrating operations, and at the end, returning a response. A developer can extend the entire pipeline with filters, binding, validation, and much more. It’s a fully featured framework for building modern web applications.

But in the real world, there are also scenarios and use cases where you don’t need all the features of the MVC framework or you have to factor in a constraint on performance. ASP.NET Core implements a lot of middleware that you can remove from or add to your applications at will, but there are a lot of common features that you would need to implement by yourself in this scenario.

At last, ASP.NET Core 6.0 has filled these gaps with minimal APIs.

Now that we have covered a brief history of minimal APIs, we will start creating a new minimal API project in the next section.

 

Creating a new minimal API project

Let’s start with our first project and try to analyze the new template for the minimal API approach when writing a RESTful API.

In this section, we will create our first minimal API project. We will start by using Visual Studio 2022 and then we will show how you can also create the project with Visual Studio Code and the .NET CLI.

Creating the project with Visual Studio 2022

Follow these steps to create a new project in Visual Studio 2022:

  1. Open Visual Studio 2022 and on the main screen, click on Create a new project:
Figure 1.1 – Visual Studio 2022 splash screen

Figure 1.1 – Visual Studio 2022 splash screen

  1. On the next screen, write API in the textbox at the top of the window and select the template called ASP.NET Core Web API:
Figure 1.2 – Create a new project screen

Figure 1.2 – Create a new project screen

  1. Next, on the Configure your new project screen, insert a name for the new project and select the root folder for your new solution:
    Figure 1.3 – Configure your new project screen

Figure 1.3 – Configure your new project screen

For this example we will use the name Chapter01, but you can choose any name that appeals to you.

  1. On the following Additional information screen, make sure to select .NET 6.0 (Long-term-support) from the Framework dropdown. And most important of all, uncheck the Use controllers (uncheck to use minimal APIs) option.
Figure 1.4 – Additional information screen

Figure 1.4 – Additional information screen

  1. Click Create and, after a few seconds, you will see the code of your new minimal API project.

Now we are going to show how to create the same project using Visual Studio Code and the .NET CLI.

Creating the project with Visual Studio Code

Creating a project with Visual Studio Code is easier and faster than with Visual Studio 2022 because you don’t have to use a UI or wizard, rather just a terminal and the .NET CLI.

You don’t need to install anything new for this because the .NET CLI is included with the .NET 6 installation (as in the previous versions of the .NET SDKs). Follow these steps to create a project using Visual Studio Code:

  1. Open your console, shell, or Bash terminal, and switch to your working directory.
  2. Use the following command to create a new Web API application:
    dotnet new webapi -minimal -o Chapter01

As you can see, we have inserted the -minimal parameter in the preceding command to use the minimal API project template instead of the ASP.NET Core template with the controllers.

  1. Now open the new project with Visual Studio Code using the following commands:
    cd Chapter01
    code.

Now that we know how to create a new minimal API project, we are going to have a quick look at the structure of this new template.

 

Looking at the structure of the project

Whether you are using Visual Studio or Visual Studio Code, you should see the following code in the Program.cs file:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", 
    "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
  var forecast = Enumerable.Range(1, 5).Select(index =>
      new WeatherForecast
      (
          DateTime.Now.AddDays(index),
          Random.Shared.Next(-20, 55),
          summaries[Random.Shared.Next(summaries.Length)]
      ))
      .ToArray();
      return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 
    0.5556);
}

First of all, with the minimal API approach, all of your code will be inside the Program.cs file. If you are a seasoned .NET developer, it’s easy to understand the preceding code, and you’ll find it similar to some of the things you’ve always used with the controller approach.

At the end of the day, it’s another way to write an API, but it’s based on ASP.NET Core.

However, if you are new to ASP.NET, this single file approach is easy to understand. It’s easy to understand how to extend the code in the template and add more features to this API.

Don’t forget that minimal means that it contains the minimum set of components needed to build an HTTP API but it doesn’t mean that the application you are going to build will be simple. It will require a good design like any other .NET application.

As a final point, the minimal API approach is not a replacement for the MVC approach. It’s just another way to write the same thing.

Let’s go back to the code.

Even the template of the minimal API uses the new approach of .NET 6 web applications: a top-level statement.

It means that the project has a Program.cs file only instead of using two files to configure an application.

If you don’t like this style of coding, you can convert your application to the old template for ASP.NET Core 3.x/5. This approach still continues to work in .NET as well.

Important note

We can find more information about the .NET 6 top-level statements template at https://docs.microsoft.com/dotnet/core/tutorials/top-level-templates.

By default, the new template includes support for the OpenAPI Specification and more specifically, Swagger.

Let’s say that we have our documentation and playground for the endpoints working out of the box without any additional configuration needed.

You can see the default configuration for Swagger in the following two lines of codes:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

Very often, you don’t want to expose Swagger and all the endpoints to the production or staging environments. The default template enables Swagger out of the box only in the development environment with the following lines of code:

if (app.Environment.IsDevelopment())
{
         app.UseSwagger();
         app.UseSwaggerUI();
}

If the application is running on the dev elopment environment, you must also include the Swagger documentation, but otherwise not.

Note

We’ll talk in detail about Swagger in Chapter 3, Working with Minimal APIs.

In these last few lines of code in the template, we are introducing another generic concept for .NET 6 web applications: environments.

Typically, when we develop a professional application, there are a lot of phases through which an application is developed, tested, and finally published to the end users.

By convention, these phases are regulated and called development, staging, and production. As developers, we might like to change the behavior of the application based on the current environment.

There are several ways to access this information but the typical way to retrieve the actual environment in modern .NET 6 applications is to use environment variables. You can access the environment variables directly from the app variable in the Program.cs file.

The following code block shows how to retrieve all the information about the environments directly from the startup point of the application:

if (app.Environment.IsDevelopment())
{
           // your code here
}
if (app.Environment.IsStaging())
{
           // your code here
}
if (app.Environment.IsProduction())
{
           // your code here
}

In many cases, you can define additional environments, and you can check your custom environment with the following code:

if (app.Environment.IsEnvironment("TestEnvironment"))
{
           // your code here
}

To define routes and handlers in minimal APIs, we use the MapGet, MapPost, MapPut, and MapDelete methods. If you are used to using HTTP verbs, you will have noticed that the verb Patch is not present, but you can define any set of verbs using MapMethods.

For instance, if you want to create a new endpoint to post some data to the API, you can write the following code:

app.MapPost("/weatherforecast", async (WeatherForecast 
    model, IWeatherService repo) =>
{
         // ...
});

As you can see in the short preceding code, it’s very easy to add a new endpoint with the new minimal API template.

It was more difficult previously, especially for a new developer, to code a new endpoint with binding parameters and use dependency injection.

Important note

We’ll talk in detail about routing in Chapter 2, Exploring Minimal APIs and Their Advantages, and about dependency injection in Chapter 4, Dependency Injection in a Minimal API Project.

 

Summary

In this chapter, we first started with a brief history of minimal APIs. Next, we saw how to create a project with Visual Studio 2022 as well as Visual Studio Code and the .NET CLI. After that, we examined the structure of the new template, how to access different environments, and how to start interacting with REST endpoints.

In the next chapter, we will see how to bind parameters, the new routing configuration, and how to customize a response.

About the Authors
  • Andrea Tosato

    Andrea Tosato is a full-stack software engineer and architect on .NET applications. Andrea successfully develops .NET applications in various industries, facing sometimes complex technological challenges. He deals with desktop, web, mobile development but with the arrival of the cloud, Azure, it becomes his passion. In 2017 he co-founded Cloudgen Verona, a .NET community based in Verona, Italy, with his friend Marco Zamana. In 2019 he is named Microsoft MVP for the first time for the Azure category. Andrea graduated from the University of Pavia with a degree in computer engineering in 2008 and successfully completed his master's degree, also in computer engineering, in Modena in 2011. Andrea was born in 1986 in Verona, Italy, where he currently works as a remote worker. You can find Andrea on Twitter.

    Browse publications by this author
  • Marco Minerva

    Computer enthusiast since elementary school, when he receives an old Commodore VIC-20 as a gift, Marco Minerva begins developing with GW-BASIC. After some experiences with Visual Basic, he has been using .NET since its first introduction. He got his master's degree in Information Technology in 2006. Today he proudly lives in Taggia, Italy, works as a freelance consultant and is involved in designing and developing solutions for the Microsoft ecosystem, building applications for Desktop, Mobile and Web. His greatest expertise is backend development as a software architect. He holds training courses. He is a speaker at technical events, writes articles for magazines and regularly makes live streaming about coding on Twitch. He is a Microsoft MVP since 2013. You can find Marco on Twitter.

    Browse publications by this author
  • Emanuele Bartolesi

    Emanuele is a Microsoft 365 Architect, passionate about frontend technologies and everything related to the cloud, especially Microsoft Azure. He is currently living in Zurich and actively participating in local and international community activities and events. Emanuele shares his love for technology through his blog. He has also became a Twitch Affiliate as a live coder and you can follow him at kasuken to write some code with him. Since 2014 Emanuele is a Microsoft MVP in the Developer Technologies category and since 2022 he is a GitHub Star. You can find Emanuele on Twitter.

    Browse publications by this author
Mastering Minimal APIs in ASP.NET Core
Unlock this book and the full library FREE for 7 days
Start now