Api

Here's a step-by-step guide to create a C# Console Application that uses Dependency Injection and makes an API call with headers (Authorization, Id).



---


Step 1: Create Console App


Open Visual Studio or terminal and run:


dotnet new console -n ApiConsoleApp

cd ApiConsoleApp



---


Step 2: Add Required Packages


dotnet add package Microsoft.Extensions.DependencyInjection

dotnet add package Microsoft.Extensions.Http



---


Step 3: Create Interfaces and Services


IApiService.cs


public interface IApiService

{

    Task CallApiAsync();

}


ApiService.cs


using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;


public class ApiService : IApiService

{

    private readonly HttpClient _httpClient;


    public ApiService(HttpClient httpClient)

    {

        _httpClient = httpClient;

    }


    public async Task CallApiAsync()

    {

        // Set headers

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_token_here");

        _httpClient.DefaultRequestHeaders.Add("Id", "your_id_value");


        // Call API

        var response = await _httpClient.GetAsync("https://yourapi.com/api/endpoint");


        if (response.IsSuccessStatusCode)

        {

            var content = await response.Content.ReadAsStringAsync();

            Console.WriteLine("Response: " + content);

        }

        else

        {

            Console.WriteLine("Error: " + response.StatusCode);

        }

    }

}



---


Step 4: Register Services in Program.cs


Program.cs


using Microsoft.Extensions.DependencyInjection;

using System;

using System.Threading.Tasks;


class Program

{

    static async Task Main(string[] args)

    {

        var serviceProvider = new ServiceCollection()

            .AddHttpClient<IApiService, ApiService>()

            .BuildServiceProvider();


        var apiService = serviceProvider.GetRequiredService<IApiService>();

        await apiService.CallApiAsync();

    }

}



---


Step 5: Run It


dotnet run



---


Notes:


Replace "https://yourapi.com/api/endpoint" with your actual API endpoint.


Replace "your_token_here" and "your_id_value" with your actual values.


You can also pull Authorization and Id from config

 or environment variables.



Want me to extend this with appsettings.json or configuration binding as well?


Yes, definitely! In a C# console app, it’s a good practice to organize your API URLs in a single place—similar to how you might centralize API endpoints in a TypeScript api.ts file.


Here’s how you can do it in C#:



---


Step 1: Create a Static Class for API URLs


Helpers/ApiEndpoints.cs


namespace ApiConsoleApp.Helpers

{

    public static class ApiEndpoints

    {

        public const string GetItems = "https://yourapi.com/api/items";

        public const string SendItemId = "https://yourapi.com/api/send-id";

    }

}



---


Step 2: Use It in Your ApiService


Update your ApiService.cs like this:


using ApiConsoleApp.Helpers;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Text;

using System.Text.Json;


public class ApiService : IApiService

{

    private readonly HttpClient _httpClient;


    public ApiService(HttpClient httpClient)

    {

        _httpClient = httpClient;

    }


    public async Task CallApiAsync()

    {

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "your_token_here");

        _httpClient.DefaultRequestHeaders.Add("Id", "your_id_value");


        var response = await _httpClient.GetAsync(ApiEndpoints.GetItems);


        if (response.IsSuccessStatusCode)

        {

            var json = await response.Content.ReadAsStringAsync();

            var items = JsonSerializer.Deserialize<List<ItemResponse>>(json);


            Console.WriteLine($"Fetched {items?.Count ?? 0} items.");


            foreach (var item in items)

            {

                await SendIdToSecondApi(item.Id);

            }

        }

        else

        {

            Console.WriteLine("Fetch API Error: " + response.StatusCode);

        }

    }


    private async Task SendIdToSecondApi(string id)

    {

        var requestData = new { Id = id };

        var json = JsonSerializer.Serialize(requestData);

        var content = new StringContent(json, Encoding.UTF8, "application/json");


        var response = await _httpClient.PostAsync(ApiEndpoints.SendItemId, content);


        if (response.IsSuccessStatusCode)

        {

            Console.WriteLine($"Sent ID {id} successfully.");

        }

        else

        {

            Console.WriteLine($"Error sending ID {id}: " + response.StatusCode);

        }

    }

}



---


Folder Structure


ApiConsoleApp/

├── Helpers/

│ └── ApiEndpoints.cs

├── Models/

│ └── ItemResponse.cs

├── Services/

│ ├── IApiService.cs

│ └── ApiService.cs

└── Program.cs



---


This structure is clean and scalable—just like your api.ts file in

 Angular.

Want me to also add support for appsettings.json so URLs and tokens are configurable?


Comments

Popular posts from this blog

String Program in C#

CSV using XmlNode

Extension Method & Partial Class