Reader small image

You're reading from  Mastering Blazor WebAssembly

Product typeBook
Published inAug 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803235103
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Ahmad Mozaffar
Ahmad Mozaffar
author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar

Right arrow

Consuming Web APIs from Blazor WebAssembly

It’s time to feed our application and the page we have built with a real data source, let the app communicate with an online service to list the books available, and create the functionality for an admin to add new ones.

We will start this chapter by explaining why you need to communicate with an API from your Blazor app, in addition to understanding the built-in .NET class HttpClient, as well as other extensions that will be used to implement the communication with the API.

Next, we will practice sending GET and POST requests to our API. We will also explore some more advanced techniques to manage and manipulate HttpClient instances. We will use IHttpClientFactory and delegating handlers to apply global logic to HTTP requests and responses. By the end of the chapter, we will have learned how to encapsulate the API calls and take them out of the components to keep them clean and testable.

This chapter will enable you to consume...

Technical requirements

The Blazor WebAssembly code used throughout this chapter is available in this book’s GitHub repository:

https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_08/Chapter_Content

Within this chapter, there will be a separate API project that you can clone from the GitHub repository too:

https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_08/API

The API project is required to test the calls, so after cloning the API solution, you can run the project just like running Blazor WebAssembly using either of these two options:

  • Open the terminal in the API project folder and run these commands:
    dotnet builddotnet run
  • Alternatively, run the project using the Start button in Visual Studio.

If the project runs successfully, navigate in the browser to https://localhost:7188 and you should see the Swagger (API documentation) page.

Figure 8.1 – BooksStore API documentation page

Figure 8.1 – BooksStore...

Understanding web API clients

Before we start consuming the BooksStore API, let’s talk a bit about web APIs. Basically, an API is a kind of interface for a set of functions, and this interface is accessible by code.

Let’s take smartphone notifications as an example. If you are developing an app for a smartphone, be it iOS or Android, the operating system provides you with an API to deal with its notification functionality for things such as showing a new notification or defining what should happen when you click on a notification.

A web API is also an application programming interface, as the name suggests, but it’s accessible over the web via HTTP. It’s a kind of web application that exposes certain functionalities and is hosted on a server somewhere in the world. Your application can consume the functions that the web API exposes by sending HTTP requests, and it will send you the status of the data received in an HTTP response.

Web APIs are a...

Calling a web API from Blazor WebAssembly

Making calls to the web API from the Blazor app involves the same steps as doing so from Postman. We start by defining the endpoint to call, prepare the data to send with the request if needed, submit the request, and, finally, receive and process the response.

.NET has a built-in class called HttpClient, which is a rich class that provides all the functionality and configuration needed to send any type of request (GET, POST, PUT, PATCH, DELETE, and more) to a given web API.

Understanding FetchData component logic

All Blazor WebAssembly projects have a default page called FetchData in the Pages folder. The logic of this page is to make a GET request to download the content of a JSON file that lives in the wwwroot folder, and that content also represents weather forecast data. So, let’s analyze the code of the FetchData component so that we understand it better:

@page "/fetchdata"@inject HttpClient Http
...
 ...

Sending a GET request

Let’s learn more about calling web APIs and improve our project even further. When you run the project, it redirects you by default to the index page, where a list of books will be shown on the UI. The books are fetched from a local in-memory collection inside the LocalBooksService.cs class within the Services folder. We need to replace that fixed data list with a web API call that retrieves the books from the API. Unlike the GET request we saw in the FetchData component, this one will be written step by step, and we will have better control over the response:

  1. As we learned earlier, before we write the code, we need to understand the targeted endpoint. Navigate to the web API Swagger page and expand the /Books GET request to see what it returns in both success and failure cases.
  2. You can open Postman and send a GET request to https://localhost:7188/books to see the response it retrieves.
Figure 8.8 – GET /Books request responses in web API

Figure 8.8 – GET...

Implementing a POST web API call in Blazor WebAssembly

We have developed the BookForm page, which has a form for entering the book details and a submit button that currently does nothing other than write some logs to the console window.

The BookForm page is for the store admin, who can insert new books. For now, we don’t have authentication either on the server side in the web API or on the client side; that’s the target of Chapter 9. But we need to complete the logic of this page so that when the admin clicks the Submit button, the book gets posted to the API, which stores it in its data source. When the app goes online in production and an admin adds a new book, all those users who navigate to the app will see the new book on the Index page because that web API is the main source of data for our project.

The BooksStore API exposes a POST endpoint, and according to the Swagger documentation, accepts a JSON object in the body of the POST request, as shown here:

...

Exploring IHttpClientFactory and delegating handlers

IHttpClientFactory is a service that supports creating single or multiple HttpClient instances with custom configuration. We have used the HttpClient instance configured in the previous section with the web API base URL. This was enough to meet our basic needs, but sometimes slightly more advanced techniques are needed to cover the scenarios you may face while developing more complex apps.

In this section, we will learn how to use the HttpClient factory to create and manage HttpClient instances. In addition, we will learn about DelegatingHandlers that allow for building a pipeline to process each HTTP request or response associated with a specific HttpClient instance and when we need such a capability.

To be able to utilize the IHttpClientFactory service, we need to install the Microsoft.Extensions.Http package. You can do that either using the NuGet package manager or through the .NET CLI command:

dotnet add package Microsoft...

Separating your API calls from the components

Back in the Dependency Injection in Blazor WebAssembly section in Chapter 1, we created the IBooksService interface and an implementation for it called LocalBooksService. The goal was to make the components rely on the IBooksService interface and not the implementation, which can be changed. The code to call the web API endpoints is somewhat long and repeatable, in addition to making the components depend on an instance of HttpClient, which makes the components hard to test and have longer code.

The goal in this section is to migrate the calls we made in the previous two sections to IBooksService and create a new implementation for it that communicates with the web API. Finally, we will write some code to fetch some book details from the API using book IDs.

So, let’s get started:

  1. In the IBooksService interface in the Services folder, we need to add a new method called AddBookAsync that takes a SubmitBook object as a...

Summary

We started this chapter by explaining the concept of web APIs regardless of your level of expertise so that you could get a deeper understanding of what they are and why you need them. Then, we moved on to the practical side of things by introducing the tools and utilities available to make API calls from a .NET app. We implemented two API calls: one to fetch data from the API and another to submit data to the API. Finally, we went over what we did, refactored it, and learned about the correct place for the API calls to reside so we have more testable code and better-coded components.

After going through the content and examples in this chapter, you should be able to consume your web APIs on your own and integrate your apps with third-party APIs to enrich the experience of your users.

The following is what you should have gained from this chapter:

  • The ability to identify what web APIs are from the client perspective and why they are needed
  • Read and understood...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Blazor WebAssembly
Published in: Aug 2023Publisher: PacktISBN-13: 9781803235103
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar