Search icon CANCEL
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
$9.99 | ALL EBOOKS & VIDEOS
Save more on purchases! Buy 2 and save 10%, Buy 3 and save 15%, Buy 5 and save 20%
Mastering Minimal APIs in ASP.NET Core
Mastering Minimal APIs in ASP.NET Core

Mastering Minimal APIs in ASP.NET Core: Build, test, and prototype web APIs quickly using .NET and C#

By Andrea Tosato , Marco Minerva , Emanuele Bartolesi
$33.99 $9.99
Book Oct 2022 240 pages 1st Edition
eBook
$33.99 $9.99
Print
$41.99
Subscription
$15.99 Monthly
eBook
$33.99 $9.99
Print
$41.99
Subscription
$15.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now
Table of content icon View table of contents Preview book icon Preview Book

Mastering Minimal APIs in ASP.NET Core

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

Description

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.

What you will learn

Adopt new features in .NET 6 for building lightweight APIs Understand how to optimize API development with Minimal APIs in .NET 6 Discover best practices for accessing and using data in Minimal APIs Understand how to validate incoming data to an API and return error messages Get familiar with dependency injection and logging for identifying errors Leverage the translation system in Minimal APIs to provide messages and errors in regional languages

Product Details

Country selected

Publication date : Oct 21, 2022
Length 240 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803237824
Vendor :
Microsoft
Category :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Oct 21, 2022
Length 240 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781803237824
Vendor :
Microsoft
Category :

Table of Contents

16 Chapters
Preface Chevron down icon Chevron up icon
1. Part 1: Introduction Chevron down icon Chevron up icon
2. Chapter 1: Introduction to Minimal APIs Chevron down icon Chevron up icon
3. Chapter 2: Exploring Minimal APIs and Their Advantages Chevron down icon Chevron up icon
4. Chapter 3: Working with Minimal APIs Chevron down icon Chevron up icon
5. Part 2: What’s New in .NET 6? Chevron down icon Chevron up icon
6. Chapter 4: Dependency Injection in a Minimal API Project Chevron down icon Chevron up icon
7. Chapter 5: Using Logging to Identify Errors Chevron down icon Chevron up icon
8. Chapter 6: Exploring Validation and Mapping Chevron down icon Chevron up icon
9. Chapter 7: Integration with the Data Access Layer Chevron down icon Chevron up icon
10. Part 3: Advanced Development and Microservices Concepts Chevron down icon Chevron up icon
11. Chapter 8: Adding Authentication and Authorization Chevron down icon Chevron up icon
12. Chapter 9: Leveraging Globalization and Localization Chevron down icon Chevron up icon
13. Chapter 10: Evaluating and Benchmarking the Performance of Minimal APIs Chevron down icon Chevron up icon
14. Index Chevron down icon Chevron up icon
15. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.