Explore 1.5M+ audiobooks & ebooks free for days

From $11.99/month after trial. Cancel anytime.

Minimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9
Minimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9
Minimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9
Ebook570 pages3 hours

Minimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateDec 6, 2024
ISBN9781805123545
Minimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9

Related to Minimal APIs in ASP.NET 9

Related ebooks

Programming For You

View More

Reviews for Minimal APIs in ASP.NET 9

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Minimal APIs in ASP.NET 9 - Nick Proud

    cover.jpg

    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

    Enjoying the preview?
    Page 1 of 1