Building APIs with C# and ASP.NET Core

Spencer Schneidenbach

Spencer Schneidenbach

Aviron Software, Microsoft MVP
5 hours, 10 minutes CC
Building APIs with C# and ASP.NET Core

Course Description

Build a robust API while leveraging the power of ASP.Net Core! Architect reliable JSON-based API routes with data validation and unit testing. Add middleware, pagination, and filters for more flexibility and explore the benefit of LINQ for querying and manipulating data. Connect to your data source with Entity Framework Core and learn techniques for securing your .NET applications.

This course and others like it are available as part of our Frontend Masters video subscription.

Preview
Close

Course Details

Published: November 5, 2024

Learning Paths

Learn Straight from the Experts Who Shape the Modern Web

Your Path to Senior Developer and Beyond
  • 200+ In-depth courses
  • 18 Learning Paths
  • Industry Leading Experts
  • Live Interactive Workshops
Get Unlimited Access Now

Table of Contents

Introduction

Section Duration: 18 minutes
  • Introduction
    Spencer Schneidenbach begins the course by sharing why .NET is a compelling platform for building backend web applications. The arguments for .NET include the robust ecosystem, security and stability, large job market, and scalability.
  • Tooling Overview
    Spencer walks through the tooling required for the course. VisualStudio Code will be the IDE, along with several C# and database extensions. The .NET CLI is installed and can be used with one of the VSCode extensions or run directly from the terminal.
  • HTTP Overview
    Spencer spends a few minutes discussing the HTTP protocol and reviewing verbs like GET, POST, PUT, PATCH, and DELETE. The APIs built throughout the course will follow these common practices and send back the correct status codes along with the results of the requests.

ASP.NET Core

Section Duration: 1 hour, 32 minutes
  • ASP.NET Core Overview
    Spencer introduces ASP.NET Core and explains that it's designed as a high-performance, modular web framework. ASP.NET Core allows developers to add middleware while putting together a robust pipeline for building web applications and APIs.
  • Setup Course API Project
    Spencer scaffolds the initial project files for the Employee API. The .NET CLI creates the directory and the base application files. The Employee class is created, and a route is added to the API to get a list of employees.
  • JSON API Routes
    Spencer continues building the employee API. Routes are created to get an employee by ID and create an employee. A route group is added to the application to simplify the shared URL pattern with the three routes.
  • Unit Testing the API
    Spencer demonstrates how to unit test the APIs. A separate project is created for the tests, and the employee API project is added as a dependency to the testing project. Four tests are written to test the endpoints. The tests can be run from the terminal with `dotnet test`.
  • Refactoring to a PUT Request
    Spencer refactors the API and adds a PUT request to update an employee. New request and response classes are created as an abstraction between the Employee entity and the data passed to and from the API. This abstraction gives developers more granular control over what's exposed through the API and what is available in the database.
  • Repository Pattern
    Spencer introduces the Repository Pattern, a design pattern that allows you to separate the concerns of data storage from the concerns of data access. With this abstraction, the data storage can be changed from an in-memory solution to a database solution without refactoring the core API logic.
  • Adding API Validation
    Spencer adds validation to the API. The out-of-the-box validation messages are not helpful for front-end applications to parse. An Extensions class is created, and a ValidationProblemDetails method is added to format the validation messages in an easy-to-parse JSON object.
  • FluentValidation
    Spencer introduces FluentValidation, an alternative to the validation patterns built into ASP.NET Core. FluentValidation allows developers to create separate validation classes from the request classes. It supports both sync and async validation, along with a clean API.

Controllers and Advanced API Topics

Section Duration: 1 hour, 23 minutes
  • Controllers
    Spencer introduces controllers which are classes that handle HTTP requests. They are more flexible than the minimal API architecture used up to this point in the course.
  • Refactor the API with Controllers
    Spencer refactors the Employee API project to use controllers. An EmployeeController.cs file is created, and the route logic is moved from the Program file to the controller. The BaseController class is also refactored to include a ValidateAsync method, which removes the need to inject validators into the controller methods.
  • Adding Logging to Controllers
    Spencer discusses the importance of logging, especially in production. In .NET, logging is handled through the ILogger interface, which can be injected into any class. This provides a unified API to write log messages at different levels, such as Information, Warning, and Error.
  • Middleware & Filters
    Spencer introduces middleware and filters. Middleware intercept and handle HTTP requests and responses in ASP.NET Core. Filters can modify the behavior of requests in ASP.NET Core, but only after the request has been routed to a controller method. The advantage of filters is they engage after the route has been matched and model binding has occurred.
  • Creating a Custom Filter
    Spencer creates a custom filter that eliminates the need to repeat boilerplate validation logic. The PUT request is refactored with a new validator and the tests are updated so they are using valid requests.
  • Configuring Controllers for OpenAPI
    Spencer adds documentation for the API. XML comments are also introduced and added to the API. The project settings are adjusted so the XML comments will appear, and warnings for uncommented classes will not prevent the build from running.
  • Querying Sub-Resources
    Spencer demonstrates strategies for querying subresources. Nested routes are a pattern well-supported by OpenAPI and most API clients. A better option is to create separate queries for the sub-resources. A GetBenefitsForEmployee route is created, and tests are added to ensure the route returns the correct employee benefits.

Entity Framework Core

Section Duration: 1 hour, 27 minutes
  • Entity Framework Overview
    Spencer introduces Entity Framework Core (EF Core), an object-relational mapping (ORM) framework for .NET. It allows developers to work with databases using .NET objects and provides a way to interact with databases in an object-oriented way rather than using raw SQL.
  • IQueryable & IEnumerable
    Spencer reviews the IQueryable and IEnumerable interfaces. IEnumerable<T> is an interface representing a collection of objects that can be enumerated. It's one of the main drivers of LINQ and is used to query, filter, and manipulate collections of data. IQueryable<T> is meant to be used for querying data from a non-in-memory data source.
  • DbContext and Migrations
    Spencer creates a DbContext class and adds it to the dependency injection system. Migrations are introduced and a directory for migrations is generated.
  • Seeding a Database
    Spencer creates a SeedData class to seed test data in the employees.db database. Because DbContext is registered as a scoped service by default, a temporary scope is created and disposed of after the seeding is complete.
  • Querying Basics
    Spencer refactors the application, removing the EmployeeRepository and replacing it with the AppDbContext. After refactoring, the API is tested to ensure the list of seeded employee data is returned from the GetAllEmployees task.
  • Filtering & Pagination
    Spencer demonstrates how to filter and paginate results returned from the database query. This reduces the payload and provides more flexibility in the GetAllEmployees API endpoint. The filter adds first and last name filtering via the query string. Pagination defaults to 100 records per page unless specified through another query string parameter.
  • Adding & Removing Objects
    Spencer implements the adding and removing of objects from the database through the DbContext Add and Remove methods. Change tracking, a feature of EF Core that allows you to track changes to your entities, is also discussed. It compares the current state of the entity to the original state of the entity when it was read from the database.
  • Extending Data Models
    Spencer explains why extending data models is important to manage complexity as the application grows. An EmployeeBenefits class is created to represent the joined data between the employees table and the benefits table.

Advanced Techniques

Section Duration: 27 minutes

Wrapping Up

Section Duration: 1 minute

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now