Minimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9
By Nick Proud
()
Related to Minimal APIs in ASP.NET 9
Related ebooks
Software Architecture with C# 12 and .NET 8: Build enterprise applications using microservices, DevOps, EF Core, and design patterns for Azure Rating: 0 out of 5 stars0 ratingsSpring Boot 3.0 Cookbook: Proven recipes for building modern and robust Java web applications with Spring Boot Rating: 0 out of 5 stars0 ratingsFastAPI Cookbook: Develop high-performance APIs and web applications with Python Rating: 0 out of 5 stars0 ratingsConquer the Azure Developer Interview: From Basics to Advanced: Dot Net Interview Preparation Rating: 0 out of 5 stars0 ratingsWeb Development with Blazor: A practical guide to building interactive UIs with C# 12 and .NET 8 Rating: 0 out of 5 stars0 ratingsBuilding an API Product: Design, implement, release, and maintain API products that meet user needs Rating: 0 out of 5 stars0 ratingsMastering Spring Boot 3.0: A comprehensive guide to building scalable and efficient backend systems with Java and Spring Rating: 0 out of 5 stars0 ratingsPractical Rust 1.x Cookbook: 100+ Solutions across Command Line, CI/CD, Kubernetes, Networking, Code Performance and Microservices Rating: 0 out of 5 stars0 ratingsEnterprise By Design: Principles of Enterprise Architecture: Enterprise By Design, #1 Rating: 0 out of 5 stars0 ratingsService-Oriented Architecture: A Planning and Implementation Guide for Business and Technology Rating: 4 out of 5 stars4/5The TOGAF® Standard, 10th Edition Content, Capability, and Governance Rating: 0 out of 5 stars0 ratingsManaging the Unmanageable: 13 Tips for Building and Leading a Successful Innovation Team Rating: 0 out of 5 stars0 ratingsKey Principles of IT Architecture Rating: 0 out of 5 stars0 ratingsChef Infrastructure Automation Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsIf the Cloud Isn't in the Sky, Where Is It? Rating: 5 out of 5 stars5/5The Ansible Workshop: Hands-On Learning For Rapid Mastery Rating: 0 out of 5 stars0 ratingsMastering Microsoft Azure Fundamentals AZ-900 Exam Prep Rating: 5 out of 5 stars5/5Mainframe to Cloud Mastery: Best Practices: Mainframes Rating: 0 out of 5 stars0 ratingsThe Dangers of Online Casinos: Gambling, #1 Rating: 0 out of 5 stars0 ratingsFinOps : RoadMap to Cloud Efficiency: Mentoring Cloud and Finance Professionals to Drive Cloud Productivity (English Edition) Rating: 0 out of 5 stars0 ratingsData Structure and Algorithms in Java: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsData Engineering with Databricks Cookbook: Build effective data and AI solutions using Apache Spark, Databricks, and Delta Lake Rating: 0 out of 5 stars0 ratingsSharePoint 2013 WCM Advanced Cookbook Rating: 0 out of 5 stars0 ratingsRuby on Rails for Agile Web Development Rating: 0 out of 5 stars0 ratings
Programming For You
Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsPython Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsBeginning Programming with Python For Dummies Rating: 3 out of 5 stars3/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsPYTHON PROGRAMMING Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5The Complete C++ Programming Guide Rating: 0 out of 5 stars0 ratingsPython 3 Object Oriented Programming Rating: 4 out of 5 stars4/5PHP for Beginners: Your Guide to Easily Learn PHP In 7 Days Rating: 4 out of 5 stars4/5
Reviews for Minimal APIs in ASP.NET 9
0 ratings0 reviews
Book preview
Minimal APIs in ASP.NET 9 - Nick Proud
Minimal APIs in ASP.NET 9
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Kaustubh Manglurkar
Publishing Product Manager: Bhavya Rao
Book Project Manager: Sonam Pandey
Senior Editor: Ayushi Bulani
Technical Editor: Simran Ali
Copy Editor: Safis Editing
Indexer: Tejal Soni
Production Designer: Alishon Mendonca
DevRel Marketing Coordinator: Nivedita Pandey
First published: October 2022
Second edition: December 2024
Production reference: 1251024
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN: 978-1-80512-912-7
www.packtpub.com
To my wife, Kerrie, and my daughter, Neave. You gave me the strength to write, and you waited patiently for me to finish. I love you both with all my heart.
To Chris, Gemma, and Charlotte, my comrades at NexBotix. Thanks for your encouragement and support throughout the whole process.
– Nick
Contributors
About the author
Nick Proud is a software engineer, technology leader, and Microsoft MVP for Developer Technologies, specializing in robotic process automation and .NET. He is currently the director of software engineering at NexBotix an intelligent automation firm, as well as a technical content creator, producing educational video content about C# and Microsoft Azure.
I want to thank the people who have supported me on this journey, especially my family and colleagues at NexBotix. I also want to thank Peter Bull and Daniel Tallentire for their thorough technical review and the LinkedIn/YouTube community for their continued support of my content.
About the reviewers
Daniel Tallentire is a software engineer and engineering manager with two decades of experience developing SaaS software, using the Microsoft development ecosystem. He has a passion for learning and development and has mentored and coached multiple engineers and managers throughout his career. He speaks on these topics at meetups and conferences. Daniel currently works as an engineering manager at Citation Group, supporting multiple teams in developing software in the HR and employment software fields. In his spare time, Daniel likes to walk the hills of the Peak District, read books, and spend time with his family.
Peter Bull is a Microsoft MVP, software developer, presenter, content creator, and Microsoft technology enthusiast. Peter has over three decades of personal software development experience and more than two decades of professional software development expertise, including web, mobile, and desktop. His journey began with BASIC on the Commodore 64, evolving through every major release of .NET to modern .NET, and beyond! Peter, aka RoguePlanetoid, enjoys sharing what he knows with the community, aiming to mentor new or existing developers and inspire them with his tutorials, talks, and workshops with Tutorialr. He is also an avid content creator who enjoys engaging with the tech community through writing, speaking, and his RoguePlanetoid podcast.
I want to express my gratitude to those who have inspired and taught me throughout my journey as a software developer. Their support and guidance have been invaluable in helping me reach where I am today. In return, I aspire to inspire and teach others, sharing the knowledge and experiences I have gained. My goal is to help others on their own software developer journey by offering the same encouragement and mentorship I was fortunate to receive.
Table of Contents
Preface
Part 1 - Introduction to Minimal APIs
1
Getting Up and Running with Minimal API Development
Technical requirements
Understanding minimal APIs
Contrasting minimal APIs with traditional API approaches
The significance of minimal APIs in modern development
Installing required tools and dependencies
Installing Visual Studio for Windows
Installing Visual Studio Code for Mac and Linux
Configuring development environments
Creating a project in Visual Studio
Creating a project in Visual Studio Code
Summary
2
Creating Your First Minimal API
Technical requirements
Project structure and organization
Endpoints
Models
Routes
Defining endpoints and routes
GET methods
POST methods
PUT methods
PATCH methods
DELETE method
Building the employee management API
Creating the API
Creating the first endpoint
Handling HTTP requests
Summary
3
The Anatomy of a Minimal API
Anatomy of a minimal API
Components of a minimal API application
The API request lifecycle
Summary
Part 2 - Data and Execution Flow
4
Handling HTTP Methods and Routing
Technical requirements
Handling requests
Defining endpoints in the Todo API
Getting todo items
Creating Todo items
Updating existing Todo items
Managing route parameters
Request validation and error handling
Manual validation
Validation with data annotations and model binding
Summary
5
The Middleware Pipeline
Technical requirements
An introduction to middleware
Configuring middleware pipelines
Middleware classes
Inline middleware
Implementing custom middleware
Terminal middleware
Handling errors within the middleware pipeline
Summary
6
Parameter Binding
Parameter binding sources
Route values
Query strings
Optional query string parameters
Headers
Strongly typed object binding
Form values
Explicit binding with attributes
Binding parameters through dependency injection
Binding precedence
Creating custom binding logic
Summary
7
Dependency Injection in Minimal APIs
Understanding DI
The DI container
The case for DI
Configuring DI in minimal APIs
Setting up a scoped DI project
Creating a singleton DI project
DI best practices
Avoiding the service locator pattern
Registering services with an extension method
Using sensible service lifetimes
Summary
8
Integrating Minimal APIs with Data Sources
Technical requirements
Understanding data integration in minimal APIs
Connecting to and integrating with SQL databases
Configuring the connection to the database and retrieving records
Inserting Employee records
Executing database transactions from API endpoints
Connecting to MongoDB
Summary
9
Object Relational Mapping with Entity Framework Core and Dapper
Technical requirements
Introduction to ORMs
Configuring Dapper in minimal API projects
Performing CRUD operations with Dapper
Configuring Entity Framework in minimal API projects
Performing CRUD operations with Entity Framework
Summary
Part 3 - Optimal Minimal APIs
10
Profiling and Identifying Bottlenecks
Technical requirements
An introduction to profiling and performance monitoring
Introducing the profiler
Performance metrics
Profiling tools and techniques
Profiling in Visual Studio
Benchmarking with BenchmarkDotNet
Common performance bottlenecks
Summary
11
Utilizing Asynchronous Programming for Scalability
Technical requirements
Understanding and implementing asynchronous patterns in a minimal API
Task-based asynchronous pattern
TAP with async/await
Asynchronous processing pattern
Common pitfalls and challenges
Summary
12
Caching Strategies for Enhanced Performance
Technical requirements
Introduction to caching in minimal APIs
In-memory caching techniques
Distributed caching strategies
Response caching
Summary
Part 4 - Best Practices, Design, and Deployment
13
Best Practices for Minimal API Resiliency
Technical requirements
Code organization and structure
Exploring folder structures
Feature-based modular structure
Layered modular structure
Design patterns
The factory pattern
The repository pattern
The strategy pattern
Error Handling
Security considerations
Authentication
Authorization
Rate limiting
Summary
14
Unit Testing, Compatibility, and Deployment of Minimal APIs
Technical requirements
Unit testing and integration testing for minimal APIs
Compatibility and migrating minimal APIs to .NET 9
Deploying minimal APIs
Deploying to Microsoft Azure App Service (cloud deployment)
Deploying to a Docker container
Deploying on-premises with Kestrel
Summary
Index
Other Books You May Enjoy
Preface
This book is a comprehensive guide that delves into the world of building streamlined and efficient web services with ASP.NET using minimal APIs.
As the landscape of web development continues to evolve, there is a growing demand for simplicity, speed, and maintainability. I wrote this book to introduce developers—whether experienced or new to the ASP.NET ecosystem—to the power of minimal APIs, an approach that allows for the creation of lightweight and performance-oriented applications.
Why minimal APIs?
With the release of .NET 6 in 2021, Microsoft introduced minimal APIs as a new way to define HTTP APIs with less ceremony and boilerplate code. Minimal APIs focus on reducing the overhead traditionally associated with larger frameworks such as ASP.NET MVC, while still maintaining the robustness of the .NET platform. By stripping away unnecessary complexity, minimal APIs empower developers to rapidly prototype, iterate, and deploy applications that scale with their needs.
In this book, I will walk you through the essentials of minimal APIs, from basic routing and endpoint structure to advanced features such as dependency injection, authentication, and middleware integration.
I’ll also introduce you to some core design principles, providing an overview of some best practices designed to keep your minimal APIs maintainable, secure, and scalable over time.
Each chapter is structured to provide hands-on examples, ensuring that by the end, you’ll not only understand how to use minimal APIs but also why they matter in modern software development.
At the time of writing, .NET 9 had reached its first release candidate phase (RC1), and .NET 9 was very close to general availability. I’ve included information throughout the book on new minimal API features in .NET 9.
Who this book is for
The book is intended to serve as an introduction to Minimal APIs, allowing developers with a basic understanding of C# and object-oriented programming (OOP) to explore the main concepts and begin their Minimal API development journey.
Whether you are an experienced ASP.NET developer looking to leverage new tools or a newcomer seeking to understand web development, this book will guide you step by step. It’s ideal for developers seeking to build microservices, start-ups prototyping new ideas, or even established enterprises looking for a more efficient way to handle specific API needs.
What this book covers
Chapter 1
, Getting Up and Running with Minimal API Development, introduces the world of minimal APIs, helping you to understand their relevance in modern software development and how they differ from traditional API approaches. It also instructs you on how to set up their development environment.
Chapter 2
, Creating Your First Minimal API, introduces the core elements of a minimal API, such as endpoints, models, and routes, before getting you building endpoints using varying HTTP methods.
Chapter 3
, The Anatomy of a Minimal API, delves into more detail on the building blocks of a minimal API, outlining the various components found within, along with an overview of the request lifecycle.
Chapter 4
, Handling HTTP Methods and Routing, focuses on how incoming requests are handled and how this can differ based on different HTTP methods used. It covers the management of route parameters and introduces request validation and error handling in minimal API endpoints.
Chapter 5
, The Middleware Pipeline, explains the concept of middleware in ASP.NET, before instructing you on how you can configure and implement it in the context of minimal APIs.
Chapter 6
, Parameter Binding, discusses the ways in which parameters can be sent into minimal API endpoints. The various parameter binding sources are explored, along with examples of how custom bindings can be created.
Chapter 7
, Dependency Injection in Minimal APIs, introduces dependency injection as a software development concept before exploring its usage in minimal APIs. Best practices for dependency injection are also outlined.
Chapter 8
, Integrating Minimal APIs with Data Sources, helps you understand how data can be integrated into a minimal API, with examples focusing on SQL Server and MongoDB.
Chapter 9
, Objected-Relational Mapping with Entity Framework Core and Dapper, takes the learning points from Chapter 8
further, introducing object-relational mapping (ORM) frameworks such as Entity Framework Core and Dapper. The chapter provides examples of the configuration of the respective frameworks and how they can be used to create CRUD operations.
Chapter 10
, Profiling and Identifying Bottlenecks, focuses on managing and optimizing the performance of minimal APIs. Various profiling tools are explored and we explore several common performance bottlenecks.
Chapter 11
, Utilizing Asynchronous Programming for Scalability, demonstrates the benefits of asynchronous programming in minimal APIs, providing examples of various asynchronous patterns. The chapter also provides examples of common pitfalls and challenges associated with asynchronous execution within minimal APIs.
Chapter 12
, Caching Strategies for Enhanced Performance, takes the theme of performance further by introducing you to caching and its place within minimal APIs. Various caching techniques are demonstrated, using caching technologies such as ASP.NET’s in-memory cache and Redis.
Chapter 13
, Best Practices for Minimal API Resiliency, turns our attention from performance to resiliency, suggesting ways in which code can be structured in a minimal API to encourage long-term functionality. Topics such as error handling and security considerations are also explored.
Chapter 14
, Unit Testing, Compatibility, and Deployment of Minimal APIs, closes out the book with topics related to the latter phases of minimal API development. Unit testing and integration testing are demonstrated using xUnit, specific compatibility requirements are outlined, and there are hands-on examples of how minimal APIs can be deployed to various hosting platforms.
To get the most out of this book
You will need to have a basic understanding of OOP languages and C# to understand the examples in this book. You will also need to have a basic understanding of what an API is, as well as how relational databases such as SQL work.
As .NET is cross-platform, it is assumed that your operating system is either Windows, MacOS or Linux, all of which are compatible.
Readers using MacOS or Linux
For readers on these operating systems, it is recommended that Visual Studio Code is used as an alternative to Visual Studio 2022.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Minimal-APIs-in-ASP.NET-9
. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/
. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: In the Employees table, we have set the Id column as an identity column, meaning that it will be populated by SQL Server on insertion of any record, with the Id value incrementing by 1 on each insert.
A block of code is set as follows:
app.MapPut(/employees
, (Employee employee) =>
{
EmployeeManager.Update(employee);
return Results.Ok();
});
Any command-line input or output is written as follows:
mongodb://localhost:27017/MyCompany
Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: You can do this by going to Tools | Manage NuGet Packages | Package Manager Console.
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected]
and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata
and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected]
with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com
.
Share Your Thoughts
Once you’ve read Minimal APIs in ASP.NET 9, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page
for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Download a free PDF copy of this book
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link below