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:
- TeaShopApi: a Web API with a
Teamodel and aTeasControllerthat can list, add, change and remove teas. - TeaShop: the Blazor app. A
TeaApiServicecalls 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-controllersmakes 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.
Teahas anId, aNameand aPrice. The API turns eachTeainto 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 likeOk(),NotFound()andNoContent(). [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
TeaShopContextfrom 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.
WithOriginslists 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". SoTeasControlleranswers atapi/teas.[HttpGet("{id}")]on an action adds to that route.{id}is a route parameter:api/teas/2givesid = 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.
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 method | CRUD job | Route | Action |
|---|---|---|---|
GET | Read all | api/teas | GetAll() |
GET | Read one | api/teas/2 | Get(2) |
POST | Create | api/teas | Create(tea) |
PUT | Update | api/teas/2 | Update(2, tea) |
DELETE | Delete | api/teas/2 | Delete(2) |
Add the five actions to TeasController:
ActionResult<Tea>means "aTea, or an error answer likeNotFound()".CreatedAtActionanswers 201 Created and says where the new tea can be found.
Request and Response Data
- A request has a method, a URL and, for
POSTandPUT, 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 theTeaparameter 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 code | Means | Sent by |
|---|---|---|
| 200 OK | It worked, here is the data | GET |
| 201 Created | The new item was made | POST with CreatedAtAction |
| 204 No Content | It worked, nothing to send back | PUT, DELETE with NoContent() |
| 400 Bad Request | The request data is wrong | [ApiController] when the JSON does not fit |
| 404 Not Found | No item with that id | NotFound() |
| 500 Internal Server Error | The server had a problem | an 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
HttpClientis the .NET class that sends HTTP requests and reads the responses.- Set its
BaseAddressto 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
HttpClientthrough its constructor (see Dependency Injection). - Register it in the Blazor app's
Program.cswithAddHttpClient, which also sets theBaseAddress.
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, withApi.GetAllAsync(). - Sending means posting new data:
POST, withApi.AddAsync(tea). The API answers with the new tea, including its newId.
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 loadingflag, or check if the data is stillnull. - 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,
HttpClientthrows anHttpRequestException. - Catch it with
try/catch, and remember the failure in a field, likeerror. finallyruns in both cases. It is a good place to setloading = 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
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
Forgetting [ApiController] or [Route] on the controller | Any class with methods is an API | Add both attributes and inherit ControllerBase | 404 Not Found for every request |
No app.MapControllers() in the API's Program.cs | Controllers are found by themselves | Call AddControllers() and MapControllers() | 404 Not Found |
| No CORS rule for the Blazor app's address | The browser can call any API | Add AddCors with WithOrigins(...) and UseCors() | The browser blocks the call (a CORS error) |
A wrong BaseAddress or port | The Blazor app finds the API by itself | Use the address dotnet run prints for the API | "Connection refused" errors |
Not checking the status code after POST, PUT or DELETE | No exception means it worked | Call EnsureSuccessStatusCode() | Failed changes look like they worked |
Showing ex.Message to customers | The real error helps users | Log it, and show a plain, friendly message | Confused 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 : ControllerBasewith[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,
HttpClientsends the requests. Put the calls in aTeaApiServiceand register it withAddHttpClient. - 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