get list of characters in game of thrones in csharp

One way to get a list of characters in Game of Thrones is by utilizing the GoT API (https://anapioficeandfire.com/). The API provides a list of all the characters from the book series.

To access the API, you can use an HTTP client library like HttpClient from .NET:

main.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;

public class CharactersHttpClient
{
    private readonly HttpClient _httpClient;
    private const string ApiBaseUrl = "https://anapioficeandfire.com/api/";

    public CharactersHttpClient()
    {
        _httpClient = new HttpClient {BaseAddress = new Uri(ApiBaseUrl)};
    }

    public async Task<string> GetCharactersAsync(int page = 1, int pageSize = 50)
    {
        var url = $"characters?page={page}&pageSize={pageSize}";
        var response = await _httpClient.GetAsync(url);
        var content = await response.Content.ReadAsStringAsync();
        return content;
    }
}
654 chars
23 lines

You can then deserialize the response JSON into a list of characters:

main.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class Character
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("gender")]
    public string Gender { get; set; }

    [JsonProperty("culture")]
    public string Culture { get; set; }

    // Add other properties here as needed
}

public class CharactersService
{
    private readonly CharactersHttpClient _client;

    public CharactersService()
    {
        _client = new CharactersHttpClient();
    }

    public async Task<List<Character>> GetCharactersAsync(int page = 1, int pageSize = 50)
    {
        var content = await _client.GetCharactersAsync(page, pageSize);
        return JsonConvert.DeserializeObject<List<Character>>(content);
    }
}
802 chars
35 lines

You can then call GetCharactersAsync() method to get a list of characters:

main.cs
var service = new CharactersService();
var characters = await service.GetCharactersAsync();
foreach (var character in characters)
{
    Console.WriteLine(character.Name);
}
173 chars
7 lines

Note that the API can only return up to 50 characters per page. You can adjust the page and pageSize parameters to retrieve more characters.

gistlibby LogSnag