25,99 €
Written by an esteemed technology leader, a .NET specialist, and Microsoft MVP for Developer Technologies, Minimal APIs in ASP.NET 9 provides you with specialized insights into the latest advancements in .NET technology, particularly minimal APIs.
You’ll get your first minimal API set up and running, before exploring the anatomy of a typical minimal API project, seeing how the framework can be used to create various HTTP endpoints, route, and validate requests, as well as enhancing those requests with custom middleware. After covering the basics, you’ll move on to data mapping, managing important dependencies through dependency injection and integrating your minimal APIs with data sources such as Entity Framework, Dapper, and SQL databases for creating CRUD operations. The chapters also walk you through performance optimization, asynchronous programming, and caching, which’ll allow you to examine the more advanced aspects of minimal API development, with code examples reflecting real-world scenarios.
By the end of this book, you’ll be armed with the necessary best practices and skills needed for deploying performant, elegant, and scalable minimal APIs in .NET.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 290
Veröffentlichungsjahr: 2024
Minimal APIs in ASP.NET 9
Design, implement, and optimize robust APIs in C# with .NET 9
Nick Proud
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
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.
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.
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.
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.
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.
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.
Topics covered in the book
Required Skill Level
C#
.NET 9 SDK (Software Development Kit)
SQL
Microsoft SQL Server
MongoDB Server
Microsoft SQL Server Management Studio
MongoDB Compass
None – setup and configuration for Minimal APIs is covered in the book
Visual Studio 2022
Basic
Visual Studio Code
Basic (if used – Visual Studio can be used alternatively)
Object-Oriented Programming
Basic
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.
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!
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/MyCompanyBold: 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.
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.
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.
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 belowhttps://packt.link/free-ebook/978-1-80512-912-7
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyIn this part, we lay the foundation for understanding minimal APIs. We’ll explore how to quickly get started with development and examine the fundamental building blocks that make up a minimal API. Whether you are new to APIs or experienced, this part will ensure you have a solid grasp of the core concepts.
This part has the following chapters:
Chapter 1, Getting Up and Running with Minimal API DevelopmentChapter 2, Creating Your First Minimal APIChapter 3, The Anatomy of a Minimal API