# API Integration

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Data Access
Source: https://www.devtutorials.ai/learn/blazor/data-access/api-integration

> 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.

## 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 175" role="img" aria-labelledby="fig-api-flow">
  <title id="fig-api-flow">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.</title>
  <defs><marker id="fig-api-flow-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="10" y="50" width="160" height="100" rx="12" />
  <text className="t m" x="90" y="76" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>TeaShop</text>
  <text className="t" x="90" y="94" textAnchor="middle" style={{ fontSize: 11 }}>Blazor app</text>
  <text className="t" x="90" y="128" textAnchor="middle" style={{ fontSize: 11 }}>Masala, Ginger...<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.85;0.9;1" dur="6s" repeatCount="indefinite" /></text>
  <rect className="pur" x="320" y="50" width="160" height="100" rx="12" />
  <text className="t m" x="400" y="76" textAnchor="middle" style={{ fontSize: 12, fontWeight: 700 }}>TeaShopApi</text>
  <text className="t" x="400" y="94" textAnchor="middle" style={{ fontSize: 11 }}>Web API</text>
  <text className="t" x="400" y="122" textAnchor="middle" style={{ fontSize: 10 }}>TeasController</text>
  <rect className="box" x="530" y="65" width="100" height="70" rx="12" />
  <text className="t m" x="580" y="104" textAnchor="middle" style={{ fontSize: 12 }}>Database</text>
  <path className="line" d="M170 80 H316" markerEnd="url(#fig-api-flow-a)" />
  <path className="line" d="M316 125 H174" markerEnd="url(#fig-api-flow-a)" />
  <path className="line" d="M480 100 H526" markerEnd="url(#fig-api-flow-a)" />
  <text className="t m" x="243" y="70" textAnchor="middle" style={{ fontSize: 11 }}>request: GET api/teas</text>
  <text className="t m" x="243" y="145" textAnchor="middle" style={{ fontSize: 11 }}>response: 200 OK + JSON</text>
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="170;316;580;580;316;174;174" keyTimes="0;0.25;0.45;0.5;0.65;0.85;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="80;80;100;100;125;125;125" keyTimes="0;0.25;0.45;0.5;0.65;0.85;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>The Blazor app asks the API. The API reads the data and answers in JSON.</figcaption>
</figure>

## 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 200" role="img" aria-labelledby="fig-api-projects">
  <title id="fig-api-projects">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.</title>
  <defs><marker id="fig-api-projects-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="20" width="270" height="160" rx="12" />
  <text className="t m" x="155" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>📁 TeaShopApi (Web API)</text>
  <text className="t m" x="40" y="76" style={{ fontSize: 12 }}>📄 Models/Tea.cs</text>
  <text className="t m" x="40" y="100" style={{ fontSize: 12 }}>📄 Controllers/TeasController.cs</text>
  <text className="t m" x="40" y="124" style={{ fontSize: 12 }}>📄 Program.cs</text>
  <rect className="blu" x="350" y="20" width="270" height="160" rx="12" />
  <text className="t m" x="485" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>📁 TeaShop (Blazor)</text>
  <text className="t m" x="370" y="76" style={{ fontSize: 12 }}>📄 Models/Tea.cs</text>
  <text className="t m" x="370" y="100" style={{ fontSize: 12 }}>📄 Services/TeaApiService.cs</text>
  <text className="t m" x="370" y="124" style={{ fontSize: 12 }}>📄 Components/Pages/TeaList.razor</text>
  <text className="t m" x="370" y="148" style={{ fontSize: 12 }}>📄 Program.cs</text>
  <path className="line" d="M350 165 H294" markerEnd="url(#fig-api-projects-a)" />
  <text className="t" x="322" y="160" textAnchor="middle" style={{ fontSize: 11 }}>HTTP</text>
</svg>
<figcaption>Two projects: the Web API and the Blazor app that calls it.</figcaption>
</figure>

### 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:

      options.AddDefaultPolicy(policy =>
          policy.WithOrigins("https://localhost:7090")
                .AllowAnyHeader()
                .AllowAnyMethod()));

var app = builder.Build();

app.UseHttpsRedirection();
app.UseCors();
app.MapControllers();

app.Run();
`}
/>

- **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`.

<figure className="blz-fig">
<svg viewBox="0 0 640 165" role="img" aria-labelledby="fig-api-route">
  <title id="fig-api-route">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.</title>
  <defs><marker id="fig-api-route-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="20" y="20" width="600" height="44" rx="8" />
  <text className="t m" x="40" y="48" style={{ fontSize: 14 }}>https://localhost:7100/</text>
  <rect className="pur" x="235" y="26" width="92" height="32" rx="6" />
  <text className="t m" x="281" y="48" textAnchor="middle" style={{ fontSize: 14 }}>api/teas</text>
  <text className="t m" x="335" y="48" style={{ fontSize: 14 }}>/</text>
  <rect className="org" x="345" y="26" width="30" height="32" rx="6" />
  <text className="t m" x="360" y="48" textAnchor="middle" style={{ fontSize: 14 }}>2</text>
  <path className="line" d="M281 58 V96" markerEnd="url(#fig-api-route-a)" />
  <path className="line" d="M360 58 L440 96" markerEnd="url(#fig-api-route-a)" />
  <rect className="pur" x="120" y="100" width="260" height="50" rx="8" />
  <text className="t m" x="250" y="122" textAnchor="middle" style={{ fontSize: 11 }}>[Route("api/[controller]")]</text>
  <text className="t" x="250" y="140" textAnchor="middle" style={{ fontSize: 11 }}>TeasController → api/teas</text>
  <rect className="org" x="400" y="100" width="220" height="50" rx="8" />
  <text className="t m" x="510" y="122" textAnchor="middle" style={{ fontSize: 11 }}>[HttpGet("&#123;id&#125;")]</text>
  <text className="t" x="510" y="140" textAnchor="middle" style={{ fontSize: 11 }}>Get(int id) gets id = 2</text>
</svg>
<figcaption>The controller route gives api/teas. The action route adds the id.</figcaption>
</figure>

## 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**:

<div className="tscroll">

| 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)` |

</div>

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.

<figure className="blz-fig">
<svg viewBox="0 0 640 185" role="img" aria-labelledby="fig-api-msg">
  <title id="fig-api-msg">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.</title>
  <defs><marker id="fig-api-msg-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="blu" x="20" y="20" width="270" height="150" rx="12" />
  <text className="t m" x="155" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Request</text>
  <text className="t m" x="40" y="74" style={{ fontSize: 12 }}>POST api/teas</text>
  <text className="t" x="40" y="96" style={{ fontSize: 11 }}>Content-Type: application/json</text>
  <text className="t m" x="40" y="128" style={{ fontSize: 12 }}>&#123;"name":"Chai","price":10&#125;</text>
  <text className="t" x="40" y="152" style={{ fontSize: 10 }}>body</text>
  <rect className="grn" x="350" y="20" width="270" height="150" rx="12" />
  <text className="t m" x="485" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Response</text>
  <text className="t m" x="370" y="74" style={{ fontSize: 12 }}>201 Created</text>
  <text className="t" x="370" y="96" style={{ fontSize: 11 }}>status code</text>
  <text className="t m" x="370" y="128" style={{ fontSize: 12 }}>&#123;"id":4,"name":"Chai","price":10&#125;</text>
  <text className="t" x="370" y="152" style={{ fontSize: 10 }}>body</text>
  <path className="line" d="M290 95 H346" markerEnd="url(#fig-api-msg-a)" />
</svg>
<figcaption>A request carries a method, a URL and a body. A response carries a status code and a body.</figcaption>
</figure>

<div className="tscroll">

| 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 |

</div>

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

## 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>`.

}
else
{
      @foreach (var tea in teas)
      {
          <p>@tea.Name: ₹@tea.Price</p>
      }
}

@code {
      // In your app, HttpClient is injected (see API Service below)
      private HttpClient Http = new(new FakeTeaApi()) { BaseAddress = new Uri("https://localhost:7100/") };
      private List<Tea>? teas;

      protected override async Task OnInitializedAsync()
      {
          teas = await Http.GetFromJsonAsync<List<Tea>>("api/teas");
      }
}
`,
    "Services/FakeTeaApi.cs": `using System.Net;
using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for TeasController on the server, so the code box runs
// without a server. It answers the same routes in the same way.
public class FakeTeaApi : HttpMessageHandler
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public bool Broken { get; set; } // true = the server has a problem

      protected override async Task<HttpResponseMessage> SendAsync(
          HttpRequestMessage request, CancellationToken token)
      {
          await Task.Delay(400, token); // the network takes a moment
          if (Broken) return new HttpResponseMessage(HttpStatusCode.InternalServerError);

          var parts = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
          if (parts.Length < 2 || parts[0] != "api" || parts[1] != "teas")
              return new HttpResponseMessage(HttpStatusCode.NotFound);
          int id = parts.Length > 2 ? int.Parse(parts[2]) : 0;

          switch (request.Method.Method)
          {
              case "GET" when id == 0:
                  return Json(HttpStatusCode.OK, teas);
              case "GET":
                  var found = teas.Find(t => t.Id == id);
                  return found == null ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(HttpStatusCode.OK, found);
              case "POST":
                  var created = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  created.Id = nextId++;
                  teas.Add(created);
                  return Json(HttpStatusCode.Created, created);
              case "PUT":
                  var changed = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  var old = teas.Find(t => t.Id == id);
                  if (old == null) return new HttpResponseMessage(HttpStatusCode.NotFound);
                  old.Name = changed.Name;
                  old.Price = changed.Price;
                  return new HttpResponseMessage(HttpStatusCode.NoContent);
              case "DELETE":
                  return teas.RemoveAll(t => t.Id == id) > 0
                      ? new HttpResponseMessage(HttpStatusCode.NoContent)
                      : new HttpResponseMessage(HttpStatusCode.NotFound);
          }
          return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
      }

      private static HttpResponseMessage Json(HttpStatusCode code, object body) =>
          new(code) { Content = JsonContent.Create(body) };
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

### 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`.

          await http.GetFromJsonAsync<List<Tea>>("api/teas") ?? new();

      public async Task<Tea?> AddAsync(Tea tea)
      {
          var response = await http.PostAsJsonAsync("api/teas", tea);
          response.EnsureSuccessStatusCode();
          return await response.Content.ReadFromJsonAsync<Tea>();
      }

      public async Task UpdateAsync(Tea tea)
      {
          var response = await http.PutAsJsonAsync($"api/teas/{tea.Id}", tea);
          response.EnsureSuccessStatusCode();
      }

      public async Task DeleteAsync(int id)
      {
          var response = await http.DeleteAsync($"api/teas/{id}");
          response.EnsureSuccessStatusCode();
      }
}
`}
/>

      client.BaseAddress = new Uri("https://localhost:7100/"));

var app = builder.Build();
`}
/>

- `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.

      <input @bind="name" placeholder="Tea name" />
      <button @onclick="Add">Add</button>
</p>
<p>@sent</p>

@foreach (var tea in teas)
{
      <p>#@tea.Id @tea.Name</p>
}

@code {
      private TeaApiService Api = new TeaApiService(new HttpClient(new FakeTeaApi()) { BaseAddress = new Uri("https://localhost:7100/") }); // In your app: @inject TeaApiService Api
      private List<Tea> teas = new();
      private string name = "Chai";
      private string sent = "";

      protected override async Task OnInitializedAsync() => teas = await Api.GetAllAsync();

      private async Task Add()
      {
          var created = await Api.AddAsync(new Tea { Name = name, Price = 10 });   // POST
          sent = $"The API answered: id {created?.Id}, {created?.Name}";
          teas = await Api.GetAllAsync();                                          // GET
      }
}
`,
    "Services/TeaApiService.cs": `using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

public class TeaApiService
{
      private readonly HttpClient http;

      public TeaApiService(HttpClient http) => this.http = http;

      public async Task<List<Tea>> GetAllAsync() =>
          await http.GetFromJsonAsync<List<Tea>>("api/teas") ?? new();

      public async Task<Tea?> AddAsync(Tea tea)
      {
          var response = await http.PostAsJsonAsync("api/teas", tea);
          response.EnsureSuccessStatusCode();
          return await response.Content.ReadFromJsonAsync<Tea>();
      }

      public async Task UpdateAsync(Tea tea)
      {
          var response = await http.PutAsJsonAsync($"api/teas/{tea.Id}", tea);
          response.EnsureSuccessStatusCode();
      }

      public async Task DeleteAsync(int id)
      {
          var response = await http.DeleteAsync($"api/teas/{id}");
          response.EnsureSuccessStatusCode();
      }
}
`,
    "Services/FakeTeaApi.cs": `using System.Net;
using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for TeasController on the server, so the code box runs
// without a server. It answers the same routes in the same way.
public class FakeTeaApi : HttpMessageHandler
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public bool Broken { get; set; } // true = the server has a problem

      protected override async Task<HttpResponseMessage> SendAsync(
          HttpRequestMessage request, CancellationToken token)
      {
          await Task.Delay(400, token); // the network takes a moment
          if (Broken) return new HttpResponseMessage(HttpStatusCode.InternalServerError);

          var parts = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
          if (parts.Length < 2 || parts[0] != "api" || parts[1] != "teas")
              return new HttpResponseMessage(HttpStatusCode.NotFound);
          int id = parts.Length > 2 ? int.Parse(parts[2]) : 0;

          switch (request.Method.Method)
          {
              case "GET" when id == 0:
                  return Json(HttpStatusCode.OK, teas);
              case "GET":
                  var found = teas.Find(t => t.Id == id);
                  return found == null ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(HttpStatusCode.OK, found);
              case "POST":
                  var created = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  created.Id = nextId++;
                  teas.Add(created);
                  return Json(HttpStatusCode.Created, created);
              case "PUT":
                  var changed = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  var old = teas.Find(t => t.Id == id);
                  if (old == null) return new HttpResponseMessage(HttpStatusCode.NotFound);
                  old.Name = changed.Name;
                  old.Price = changed.Price;
                  return new HttpResponseMessage(HttpStatusCode.NoContent);
              case "DELETE":
                  return teas.RemoveAll(t => t.Id == id) > 0
                      ? new HttpResponseMessage(HttpStatusCode.NoContent)
                      : new HttpResponseMessage(HttpStatusCode.NotFound);
          }
          return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
      }

      private static HttpResponseMessage Json(HttpStatusCode code, object body) =>
          new(code) { Content = JsonContent.Create(body) };
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

### 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`.

          @tea.Name: ₹@tea.Price
          <button @onclick="() => RaisePrice(tea)">+₹5</button>
          <button @onclick="() => Delete(tea.Id)">Delete</button>
      </p>
}

@code {
      private TeaApiService Api = new TeaApiService(new HttpClient(new FakeTeaApi()) { BaseAddress = new Uri("https://localhost:7100/") }); // In your app: @inject TeaApiService Api
      private List<Tea> teas = new();

      protected override async Task OnInitializedAsync() => teas = await Api.GetAllAsync();

      private async Task RaisePrice(Tea tea)
      {
          tea.Price += 5;
          await Api.UpdateAsync(tea);       // PUT api/teas/{id}
          teas = await Api.GetAllAsync();
      }

      private async Task Delete(int id)
      {
          await Api.DeleteAsync(id);        // DELETE api/teas/{id}
          teas = await Api.GetAllAsync();
      }
}
`,
    "Services/TeaApiService.cs": `using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

public class TeaApiService
{
      private readonly HttpClient http;

      public TeaApiService(HttpClient http) => this.http = http;

      public async Task<List<Tea>> GetAllAsync() =>
          await http.GetFromJsonAsync<List<Tea>>("api/teas") ?? new();

      public async Task<Tea?> AddAsync(Tea tea)
      {
          var response = await http.PostAsJsonAsync("api/teas", tea);
          response.EnsureSuccessStatusCode();
          return await response.Content.ReadFromJsonAsync<Tea>();
      }

      public async Task UpdateAsync(Tea tea)
      {
          var response = await http.PutAsJsonAsync($"api/teas/{tea.Id}", tea);
          response.EnsureSuccessStatusCode();
      }

      public async Task DeleteAsync(int id)
      {
          var response = await http.DeleteAsync($"api/teas/{id}");
          response.EnsureSuccessStatusCode();
      }
}
`,
    "Services/FakeTeaApi.cs": `using System.Net;
using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for TeasController on the server, so the code box runs
// without a server. It answers the same routes in the same way.
public class FakeTeaApi : HttpMessageHandler
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public bool Broken { get; set; } // true = the server has a problem

      protected override async Task<HttpResponseMessage> SendAsync(
          HttpRequestMessage request, CancellationToken token)
      {
          await Task.Delay(400, token); // the network takes a moment
          if (Broken) return new HttpResponseMessage(HttpStatusCode.InternalServerError);

          var parts = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
          if (parts.Length < 2 || parts[0] != "api" || parts[1] != "teas")
              return new HttpResponseMessage(HttpStatusCode.NotFound);
          int id = parts.Length > 2 ? int.Parse(parts[2]) : 0;

          switch (request.Method.Method)
          {
              case "GET" when id == 0:
                  return Json(HttpStatusCode.OK, teas);
              case "GET":
                  var found = teas.Find(t => t.Id == id);
                  return found == null ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(HttpStatusCode.OK, found);
              case "POST":
                  var created = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  created.Id = nextId++;
                  teas.Add(created);
                  return Json(HttpStatusCode.Created, created);
              case "PUT":
                  var changed = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  var old = teas.Find(t => t.Id == id);
                  if (old == null) return new HttpResponseMessage(HttpStatusCode.NotFound);
                  old.Name = changed.Name;
                  old.Price = changed.Price;
                  return new HttpResponseMessage(HttpStatusCode.NoContent);
              case "DELETE":
                  return teas.RemoveAll(t => t.Id == id) > 0
                      ? new HttpResponseMessage(HttpStatusCode.NoContent)
                      : new HttpResponseMessage(HttpStatusCode.NotFound);
          }
          return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
      }

      private static HttpResponseMessage Json(HttpStatusCode code, object body) =>
          new(code) { Content = JsonContent.Create(body) };
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

### 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.

}
else
{
      <table>
          <tr><th>#</th><th>Tea</th><th>Price</th></tr>
          @foreach (var tea in teas)
          {
              <tr><td>@tea.Id</td><td>@tea.Name</td><td>₹@tea.Price</td></tr>
          }
      </table>
      <p>@teas.Count teas on the menu.</p>
}

@code {
      private TeaApiService Api = new TeaApiService(new HttpClient(new FakeTeaApi()) { BaseAddress = new Uri("https://localhost:7100/") }); // In your app: @inject TeaApiService Api
      private List<Tea>? teas;

      protected override async Task OnInitializedAsync() => teas = await Api.GetAllAsync();
}
`,
    "Services/TeaApiService.cs": `using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

public class TeaApiService
{
      private readonly HttpClient http;

      public TeaApiService(HttpClient http) => this.http = http;

      public async Task<List<Tea>> GetAllAsync() =>
          await http.GetFromJsonAsync<List<Tea>>("api/teas") ?? new();

      public async Task<Tea?> AddAsync(Tea tea)
      {
          var response = await http.PostAsJsonAsync("api/teas", tea);
          response.EnsureSuccessStatusCode();
          return await response.Content.ReadFromJsonAsync<Tea>();
      }

      public async Task UpdateAsync(Tea tea)
      {
          var response = await http.PutAsJsonAsync($"api/teas/{tea.Id}", tea);
          response.EnsureSuccessStatusCode();
      }

      public async Task DeleteAsync(int id)
      {
          var response = await http.DeleteAsync($"api/teas/{id}");
          response.EnsureSuccessStatusCode();
      }
}
`,
    "Services/FakeTeaApi.cs": `using System.Net;
using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for TeasController on the server, so the code box runs
// without a server. It answers the same routes in the same way.
public class FakeTeaApi : HttpMessageHandler
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public bool Broken { get; set; } // true = the server has a problem

      protected override async Task<HttpResponseMessage> SendAsync(
          HttpRequestMessage request, CancellationToken token)
      {
          await Task.Delay(400, token); // the network takes a moment
          if (Broken) return new HttpResponseMessage(HttpStatusCode.InternalServerError);

          var parts = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
          if (parts.Length < 2 || parts[0] != "api" || parts[1] != "teas")
              return new HttpResponseMessage(HttpStatusCode.NotFound);
          int id = parts.Length > 2 ? int.Parse(parts[2]) : 0;

          switch (request.Method.Method)
          {
              case "GET" when id == 0:
                  return Json(HttpStatusCode.OK, teas);
              case "GET":
                  var found = teas.Find(t => t.Id == id);
                  return found == null ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(HttpStatusCode.OK, found);
              case "POST":
                  var created = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  created.Id = nextId++;
                  teas.Add(created);
                  return Json(HttpStatusCode.Created, created);
              case "PUT":
                  var changed = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  var old = teas.Find(t => t.Id == id);
                  if (old == null) return new HttpResponseMessage(HttpStatusCode.NotFound);
                  old.Name = changed.Name;
                  old.Price = changed.Price;
                  return new HttpResponseMessage(HttpStatusCode.NoContent);
              case "DELETE":
                  return teas.RemoveAll(t => t.Id == id) > 0
                      ? new HttpResponseMessage(HttpStatusCode.NoContent)
                      : new HttpResponseMessage(HttpStatusCode.NotFound);
          }
          return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
      }

      private static HttpResponseMessage Json(HttpStatusCode code, object body) =>
          new(code) { Content = JsonContent.Create(body) };
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

## 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.

<figure className="blz-fig">
<svg viewBox="0 0 640 195" role="img" aria-labelledby="fig-api-states">
  <title id="fig-api-states">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.</title>
  <defs><marker id="fig-api-states-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="org" x="20" y="70" width="150" height="56" rx="10" />
  <text className="t m" x="95" y="96" textAnchor="middle" style={{ fontSize: 12 }}>Loading...</text>
  <circle cx="95" cy="112" r="6" style={{ fill: "none", stroke: "#ea580c", strokeWidth: 2, strokeDasharray: "20 10" }}><animateTransform attributeName="transform" type="rotate" from="0 95 112" to="360 95 112" dur="1s" repeatCount="indefinite" /></circle>
  <rect className="grn" x="400" y="15" width="220" height="56" rx="10" />
  <text className="t m" x="510" y="40" textAnchor="middle" style={{ fontSize: 12 }}>Done</text>
  <text className="t" x="510" y="58" textAnchor="middle" style={{ fontSize: 11 }}>show the teas</text>
  <rect x="400" y="125" width="220" height="56" rx="10" style={{ fill: "#fee2e2", stroke: "#dc2626" }} />
  <text className="t m" x="510" y="150" textAnchor="middle" style={{ fontSize: 12 }}>Failed</text>
  <text className="t" x="510" y="168" textAnchor="middle" style={{ fontSize: 11 }}>friendly message + Try again</text>
  <path className="line" d="M170 90 L396 45" markerEnd="url(#fig-api-states-a)" />
  <path className="line" d="M170 105 L396 150" markerEnd="url(#fig-api-states-a)" />
  <circle r="7" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="95;510;510;95;510;510" keyTimes="0;0.3;0.5;0.5;0.8;1" dur="6s" repeatCount="indefinite" />
    <animate attributeName="cy" values="98;43;43;98;153;153" keyTimes="0;0.3;0.5;0.5;0.8;1" dur="6s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>An API call is Loading first, then Done or Failed.</figcaption>
</figure>

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.

      @(server.Broken ? "Fix the server" : "Break the server")
</button>
<button @onclick="Load" disabled="@loading">Try again</button>

@if (loading)
{
      <p>Loading...</p>
}
else if (error != null)
{
      <p style="color: #b91c1c;">@error</p>
}
else
{
      @foreach (var tea in teas)
      {
          <p>@tea.Name: ₹@tea.Price</p>
      }
}

@code {
      private static FakeTeaApi server = new();
      private TeaApiService Api = new(new HttpClient(server) { BaseAddress = new Uri("https://localhost:7100/") });
      private List<Tea> teas = new();
      private bool loading;
      private string? error;

      protected override async Task OnInitializedAsync() => await Load();

      private async Task Load()
      {
          loading = true;
          error = null;
          try
          {
              teas = await Api.GetAllAsync();
          }
          catch (HttpRequestException)
          {
              error = "We could not load the menu. Please try again in a moment.";
          }
          finally
          {
              loading = false;
          }
      }
}
`,
    "Services/TeaApiService.cs": `using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

public class TeaApiService
{
      private readonly HttpClient http;

      public TeaApiService(HttpClient http) => this.http = http;

      public async Task<List<Tea>> GetAllAsync() =>
          await http.GetFromJsonAsync<List<Tea>>("api/teas") ?? new();

      public async Task<Tea?> AddAsync(Tea tea)
      {
          var response = await http.PostAsJsonAsync("api/teas", tea);
          response.EnsureSuccessStatusCode();
          return await response.Content.ReadFromJsonAsync<Tea>();
      }

      public async Task UpdateAsync(Tea tea)
      {
          var response = await http.PutAsJsonAsync($"api/teas/{tea.Id}", tea);
          response.EnsureSuccessStatusCode();
      }

      public async Task DeleteAsync(int id)
      {
          var response = await http.DeleteAsync($"api/teas/{id}");
          response.EnsureSuccessStatusCode();
      }
}
`,
    "Services/FakeTeaApi.cs": `using System.Net;
using System.Net.Http.Json;
using BlazorApp.Models;

namespace BlazorApp.Services;

// Stands in for TeasController on the server, so the code box runs
// without a server. It answers the same routes in the same way.
public class FakeTeaApi : HttpMessageHandler
{
      private readonly List<Tea> teas = new()
      {
          new Tea { Id = 1, Name = "Masala Tea", Price = 20 },
          new Tea { Id = 2, Name = "Ginger Tea", Price = 25 },
          new Tea { Id = 3, Name = "Lemon Tea", Price = 15 },
      };
      private int nextId = 4;

      public bool Broken { get; set; } // true = the server has a problem

      protected override async Task<HttpResponseMessage> SendAsync(
          HttpRequestMessage request, CancellationToken token)
      {
          await Task.Delay(400, token); // the network takes a moment
          if (Broken) return new HttpResponseMessage(HttpStatusCode.InternalServerError);

          var parts = request.RequestUri!.AbsolutePath.Trim('/').Split('/');
          if (parts.Length < 2 || parts[0] != "api" || parts[1] != "teas")
              return new HttpResponseMessage(HttpStatusCode.NotFound);
          int id = parts.Length > 2 ? int.Parse(parts[2]) : 0;

          switch (request.Method.Method)
          {
              case "GET" when id == 0:
                  return Json(HttpStatusCode.OK, teas);
              case "GET":
                  var found = teas.Find(t => t.Id == id);
                  return found == null ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(HttpStatusCode.OK, found);
              case "POST":
                  var created = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  created.Id = nextId++;
                  teas.Add(created);
                  return Json(HttpStatusCode.Created, created);
              case "PUT":
                  var changed = (await request.Content!.ReadFromJsonAsync<Tea>(token))!;
                  var old = teas.Find(t => t.Id == id);
                  if (old == null) return new HttpResponseMessage(HttpStatusCode.NotFound);
                  old.Name = changed.Name;
                  old.Price = changed.Price;
                  return new HttpResponseMessage(HttpStatusCode.NoContent);
              case "DELETE":
                  return teas.RemoveAll(t => t.Id == id) > 0
                      ? new HttpResponseMessage(HttpStatusCode.NoContent)
                      : new HttpResponseMessage(HttpStatusCode.NotFound);
          }
          return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
      }

      private static HttpResponseMessage Json(HttpStatusCode code, object body) =>
          new(code) { Content = JsonContent.Create(body) };
}
`,
    "Models/Tea.cs": `namespace BlazorApp.Models;

public class Tea
{
      public int Id { get; set; }
      public string Name { get; set; } = "";
      public int Price { get; set; }
}
`,
  }}
/>

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

## Common mistakes

<div className="tscroll">

| 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 |

</div>

## 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**
