0

There are multiple examples of on how to call API's with Blazor, such as

var request = new HttpRequestMessage(HttpMethod.Get, "https://api.github.com/repos/dotnet/AspNetCore.Docs/branches");
request.Headers.Add("Accept", "application/vnd.github.v3+json");
request.Headers.Add("User-Agent", "HttpClientFactory-Sample");

var client = ClientFactory.CreateClient();

var response = await client.SendAsync(request);

if (response.IsSuccessStatusCode)
{
     using var responseStream = await response.Content.ReadAsStreamAsync();
     branches = await JsonSerializer.DeserializeAsync<IEnumerable<GitHubBranch>>(responseStream);
}

or

await this.httpClient.GetFromJsonAsync<TblMenus[]>("https://xxxxx.com/BLZ/api/GETData/x,x,x,x");

To me these seem the equivalent of using

$.get( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

That is it works, but it's as far away from how you would use an API in a modern way as you can get. Especially if you are building anything more then a hello world script.

If you look at any of the TS/JS frameworks (Angular, React, Vue) you publish some sort of API specifications (OpenAPI/Swagger) and then generate strongly typed client code from this (in typescript or whatever you fancy). There is no casting, or going over all your code every time the API is updated as its just encapsulated in the client class and gets updated when you update the generated client.

So my question is this. What options exist or are there any examples of how one can use Blazor without writing API calls manually or engraining them in the HTML code (which pretty much all modern JS/TS frame works have moved away from).

Just to clarify, I'm not looking for opinions, but examples of how one could encapsulate, generate, or use APIs within Blazor in a more durable way that wont have HTTP calls spread all throughout the app.

JensB
  • 6,663
  • 2
  • 55
  • 94
  • 1
    If you would like something that automatically generates your C# code I found [this](https://www.c-sharpcorner.com/article/generate-the-client-code-of-web-api-using-swagger-api-specification/). Personally, I have found that this usually results in having to edit multiple files and does not speed up development. I am working alone though, not in an org. – Grizzlly Jan 23 '22 at 19:49

1 Answers1

0

Something as simple as this can be used.

IApiService is a singleton service. You can inject this wherever you need it.

using ...

namespace App.Shared.Data.Services
{
    public class ApiService : IApiService
    {
        private readonly HttpClient httpClient;

        public ApiService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public static StringContent PrepareStringContent(object obj)
        {
            return new(JsonSerializer.Serialize(obj), Encoding.UTF8, "application/json");
        }

        public async Task<bool> DeleteProblem(Guid problemid)
        {
            using (HttpResponseMessage responseMessage = await httpClient.DeleteAsync($"api/admin/deleteproblem/{problemid}"))
            {
                return responseMessage.IsSuccessStatusCode;
            }
        }
        ...
    }
}

I use the PrepareStringContent method to send objects as JSON in POST requests, PUT, etc. where HttpContent is required.

Grizzlly
  • 486
  • 3
  • 14