From 1393299e9348f6fb377e1b0d628a769311c3d060 Mon Sep 17 00:00:00 2001 From: Chad Bentz <1760475+felickz@users.noreply.github.com> Date: Thu, 26 Sep 2024 18:36:27 -0400 Subject: [PATCH] add api client --- ApiClient/ApiSettings.cs | 5 +++++ ApiClient/MyApiService.cs | 23 +++++++++++++++++++++++ Program.cs | 5 +++++ appsettings.Development.json | 6 +++++- 4 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 ApiClient/ApiSettings.cs create mode 100644 ApiClient/MyApiService.cs diff --git a/ApiClient/ApiSettings.cs b/ApiClient/ApiSettings.cs new file mode 100644 index 0000000..a895a81 --- /dev/null +++ b/ApiClient/ApiSettings.cs @@ -0,0 +1,5 @@ +public class ApiSettings +{ + public string BaseUrl { get; set; } + public string BearerToken { get; set; } +} diff --git a/ApiClient/MyApiService.cs b/ApiClient/MyApiService.cs new file mode 100644 index 0000000..912724a --- /dev/null +++ b/ApiClient/MyApiService.cs @@ -0,0 +1,23 @@ +public class MyApiService +{ + private readonly ApiSettings _apiSettings; + + public MyApiService(IOptions apiSettings) + { + _apiSettings = apiSettings.Value; + } + + public async Task GetApiDataAsync() + { + using (var client = new HttpClient()) + { + client.BaseAddress = new Uri(_apiSettings.BaseUrl); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiSettings.BearerToken); + + var response = await client.GetAsync("endpoint"); + response.EnsureSuccessStatusCode(); + + return await response.Content.ReadAsStringAsync(); + } + } +} diff --git a/Program.cs b/Program.cs index 11dd935..4affa2e 100644 --- a/Program.cs +++ b/Program.cs @@ -13,6 +13,9 @@ builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); +builder.Services.Configure(Configuration.GetSection("ApiSettings")); + + var app = builder.Build(); // Configure the HTTP request pipeline. @@ -22,6 +25,8 @@ app.UseSwaggerUI(); } + + app.UseHttpsRedirection(); app.UseAuthorization(); diff --git a/appsettings.Development.json b/appsettings.Development.json index 0c208ae..57bd502 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -4,5 +4,9 @@ "Default": "Information", "Microsoft.AspNetCore": "Warning" } + }, + "ApiSettings": { + "BaseUrl": "https://api.example.com", + "BearerToken": "your-bearer-token-here", } -} +} \ No newline at end of file