API Integration in Blazor

By Syncfusion®, Inc. · Last updated

Build and use a Web API: an ASP.NET Core Web API with a Tea model, TeasController and routes, GET, POST, PUT and DELETE endpoints, request and response data, HttpClient and an API service in Blazor, CRUD from components, loading states and friendly error messages.

What you will learn

  • Create a Web API with a model, a controller and routes
  • Write GET, POST, PUT and DELETE endpoints with status codes
  • Call the API from Blazor with HttpClient and an API service
  • Show loading states and friendly error messages

API Integration Overview

  • An API is a way for one program to ask another program for data. A Web API does this over the internet, using HTTP, like a browser asking for a web page.
  • The Blazor app sends a request to the API, and the API sends back a response with the data in JSON, a simple text format.
  • Each address of the API that does one job, like GET api/teas (get all teas), is called an endpoint.
  • Because the data sits behind the API, any app can use it: the Blazor site, a phone app, or a WebAssembly app that cannot reach the database itself.

Real-World Example:

In this lesson, you build the real thing step by step:

  1. TeaShopApi: a Web API with a Tea model and a TeasController that can list, add, change and remove teas.
  2. TeaShop: the Blazor app. A TeaApiService calls the API, and a page shows the teas and lets Ravi change them.

Animation: the Blazor app sends a request, GET api/teas, across HTTP to the Web API. The API reads the database and sends back a response with status 200 OK and JSON: a list of teas. The Blazor page then shows the teas.

TeaShop Blazor app Masala, Ginger...

TeaShopApi Web API TeasController

Database

request: GET api/teas response: 200 OK + JSON

The Blazor app asks the API. The API reads the data and answers in JSON.

Creating an ASP.NET Core Web API

  • ASP.NET Core is the .NET framework for web servers. Blazor runs on it, and so do Web APIs.
  • Make the API as its own project, next to the Blazor app. --use-controllers makes it use controllers, explained below.

Click Next to see each command.

Two project folders side by side. TeaShopApi holds Models/Tea.cs, Controllers/TeasController.cs and Program.cs. TeaShop, the Blazor app, holds Models/Tea.cs, Services/TeaApiService.cs, Components/Pages/TeaList.razor and Program.cs. An arrow labelled HTTP goes from TeaShop to TeaShopApi.

📁 TeaShopApi (Web API) 📄 Models/Tea.cs 📄 Controllers/TeasController.cs 📄 Program.cs

📁 TeaShop (Blazor) 📄 Models/Tea.cs 📄 Services/TeaApiService.cs 📄 Components/Pages/TeaList.razor 📄 Program.cs

HTTP

Two projects: the Web API and the Blazor app that calls it.

Models

  • A model is a class that describes the data the API sends and receives. You met models in Services.
  • Tea has an Id, a Name and a Price. The API turns each Tea into JSON like {"id":1,"name":"Masala Tea","price":20}.

Controllers

  • A controller is a class that answers requests. Each public method in it, called an action, handles one endpoint.
  • It inherits ControllerBase, which gives handy answers like Ok(), NotFound() and NoContent().
  • [ApiController] turns on Web API behaviour, like reading JSON from the request for you.
  • To keep the focus on the API, the teas live in a static list here. In your app, use the TeaShopContext from Database Handling instead.

Program.cs of the API turns on controllers and lets the Blazor app call it:

  • CORS (Cross-Origin Resource Sharing) is a browser safety rule. A page from one address may only call an API on another address if the API allows it. WithOrigins lists the Blazor app's address.

Routes

  • A route is the URL pattern that leads to an action.
  • [Route("api/[controller]")] on the class: [controller] is replaced by the class name without "Controller". So TeasController answers at api/teas.
  • [HttpGet("{id}")] on an action adds to that route. {id} is a route parameter: api/teas/2 gives id = 2.

The address https://localhost:7100/api/teas/2 split into parts. api/teas comes from [Route("api/[controller]")] on TeasController. The 2 is the id route parameter from the HttpGet attribute, and it becomes the id argument of the Get action.

https://localhost:7100/

api/teas /

2

[Route("api/[controller]")] TeasController → api/teas

[HttpGet("{id}")] Get(int id) gets id = 2

The controller route gives api/teas. The action route adds the id.

Creating API Endpoints

GET, POST, PUT, DELETE

  • Each HTTP request has a method (also called a verb). It says what kind of job you want.
  • The four main methods match the four CRUD jobs from Services:
HTTP methodCRUD jobRouteAction
GETRead allapi/teasGetAll()
GETRead oneapi/teas/2Get(2)
POSTCreateapi/teasCreate(tea)
PUTUpdateapi/teas/2Update(2, tea)
DELETEDeleteapi/teas/2Delete(2)

Add the five actions to TeasController:

  • ActionResult<Tea> means "a Tea, or an error answer like NotFound()".
  • CreatedAtAction answers 201 Created and says where the new tea can be found.

Request and Response Data

  • A request has a method, a URL and, for POST and PUT, a body: the data sent, as JSON.
  • A response has a status code (a number that says how it went) and often a JSON body.
  • [ApiController] reads the request body into the Tea parameter for you, and turns your return value into JSON.

Two cards. Request card: POST api/teas, header Content-Type application/json, a JSON body with the name Chai and price 10. Response card: 201 Created, with a JSON body that adds id 4. An arrow goes from the request to the API and back as the response.

Request POST api/teas Content-Type: application/json {"name":"Chai","price":10} body

Response 201 Created status code {"id":4,"name":"Chai","price":10} body

A request carries a method, a URL and a body. A response carries a status code and a body.

Status codeMeansSent by
200 OKIt worked, here is the dataGET
201 CreatedThe new item was madePOST with CreatedAtAction
204 No ContentIt worked, nothing to send backPUT, DELETE with NoContent()
400 Bad RequestThe request data is wrong[ApiController] when the JSON does not fit
404 Not FoundNo item with that idNotFound()
500 Internal Server ErrorThe server had a probleman unhandled error

Try the endpoints with curl, a command that sends HTTP requests from the terminal:

Click Next to see each request and its response.

Connecting Blazor to APIs

The API is running. Now switch to the Blazor app, TeaShop.

HttpClient

  • HttpClient is the .NET class that sends HTTP requests and reads the responses.
  • Set its BaseAddress to the API's address once. Then use short paths like "api/teas".
  • Handy methods that also turn JSON into C# objects: GetFromJsonAsync, PostAsJsonAsync, PutAsJsonAsync, DeleteAsync.

The code boxes cannot run the API server. So FakeTeaApi.cs answers inside the box with the same routes and status codes as TeasController. The HttpClient code is exactly what you write in your app.

FakeTeaApi exists only so the code boxes can run. In your app, HttpClient talks to the real TeaShopApi over the network.

In the below example, HttpClient sends GET api/teas and turns the JSON answer into a List<Tea>.

API Service

  • As in Services, components should not build URLs and read JSON themselves. Put all API calls into one class: TeaApiService.
  • It gets an HttpClient through its constructor (see Dependency Injection).
  • Register it in the Blazor app's Program.cs with AddHttpClient, which also sets the BaseAddress.
  • EnsureSuccessStatusCode() throws an error when the status code is not a success (not 2xx). You will catch it in the last section.
  • Pages now inject it: @inject TeaApiService Api.

Working with APIs in Blazor

In the boxes below, the page makes its own TeaApiService on the first line of @code, because the box has no Program.cs. In your app, that line is @inject TeaApiService Api.

Fetching and Sending Data

  • Fetching means getting data: GET, with Api.GetAllAsync().
  • Sending means posting new data: POST, with Api.AddAsync(tea). The API answers with the new tea, including its new Id.

In the below example, type a tea and click Add. The page sends it with POST and shows the tea the API sends back.

Updating and Deleting Data

  • Updating sends the changed tea with PUT api/teas/{id}: Api.UpdateAsync(tea).
  • Deleting sends DELETE api/teas/{id}: Api.DeleteAsync(id).
  • Both get 204 No Content back, so reload the list to see the result.

In the below example, +₹5 updates a price with PUT, and Delete removes a tea with DELETE.

Displaying API Data

  • Show the data in a clear layout, like a table, once it arrives.
  • Use the values from the API as they are: names, prices, ids.

In the below example, TeaList.razor shows the API data in a table, with a total at the bottom.

Handling API State and Errors

  • A call to an API can be waiting, done or failed. These are its states. The page should show the right thing for each one.

Animation: a request starts in the Loading state with a spinner. It then goes either to Done, which shows the tea list, or to Failed, which shows a friendly message and a Try again button.

Loading...

Done show the teas

Failed friendly message + Try again

An API call is Loading first, then Done or Failed.

Every call to an API can be slow or can fail. Plan for both on every page that uses the API.

Loading States

  • While waiting, show "Loading..." so the page does not look empty or broken.
  • Use a bool loading flag, or check if the data is still null.
  • Disable buttons while a request is running, so the user does not send it twice.

Error Handling

  • When the API cannot be reached or answers with an error, HttpClient throws an HttpRequestException.
  • Catch it with try / catch, and remember the failure in a field, like error.
  • finally runs in both cases. It is a good place to set loading = false.

User-Friendly Messages

  • Never show the raw error text to customers. "Response status code does not indicate success: 500" scares people.
  • Say what happened in plain words, and what they can do: "We could not load the menu. Please try again."
  • Give a Try again button that sends the request again.

In the below example, click Break the server and then Try again. The page shows "Loading...", then a friendly message. Click Fix the server and Try again to load the teas.

Write the real error to the log for yourself (for example with ILogger), and show the friendly text to the user.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
Forgetting [ApiController] or [Route] on the controllerAny class with methods is an APIAdd both attributes and inherit ControllerBase404 Not Found for every request
No app.MapControllers() in the API's Program.csControllers are found by themselvesCall AddControllers() and MapControllers()404 Not Found
No CORS rule for the Blazor app's addressThe browser can call any APIAdd AddCors with WithOrigins(...) and UseCors()The browser blocks the call (a CORS error)
A wrong BaseAddress or portThe Blazor app finds the API by itselfUse the address dotnet run prints for the API"Connection refused" errors
Not checking the status code after POST, PUT or DELETENo exception means it workedCall EnsureSuccessStatusCode()Failed changes look like they worked
Showing ex.Message to customersThe real error helps usersLog it, and show a plain, friendly messageConfused or worried users

Check Yourself

Exercises

What to Remember

  • A Web API is a door to your data over HTTP. Requests and responses carry JSON.
  • Make it with dotnet new webapi --use-controllers: a model (Tea), a controller (TeasController : ControllerBase with [ApiController]) and routes ([Route("api/[controller]")], [HttpGet("{id}")]).
  • GET reads, POST creates, PUT updates and DELETE removes. Status codes tell how it went: 200, 201, 204, 400, 404, 500.
  • In Blazor, HttpClient sends the requests. Put the calls in a TeaApiService and register it with AddHttpClient.
  • Load data in OnInitializedAsync, send changes with POST, PUT and DELETE, then reload.
  • Show "Loading..." while waiting, catch HttpRequestException, and show a friendly message with a Try again button.

Next: Middleware Pipeline