Couple of things.
- At least for .NET Framework you don't want to create
HttpClient
over and over again otherwise you'll run out of ports. Google for the issues around doing that. So you should create the client once and reuse it per URL. - When creating the
HttpClient
set the default request headers andBaseAddress
to what you're using in Postman as the base URL. Then use relative URLs in the individual get/post requests. -
API-Key
would be an authentication mechanism and depends upon the API you're calling. If your API doesn't need authentication then you don't need this. If it does then you'd already be doing that in Postman and you'd need to replicate it.
My preferred approach is to use an HttpClientFactory
to handle creation of clients by name and it handles the creation for you. NET Core ships with a version but for NF you have to build your own.
For authentication I tend to create an HttpMessageHandler
class that injects the API key into all requests sent by that client. But that is a slightly more advanced scenario.
For your very specific starter case something like this should work for .NET Core (and similar for .NET Framework).
class Program
{
static async Task Main ( string[] args )
{
var users = await PagerDutyClient.ListUsersAsync().ConfigureAwait(false);
foreach (var user in users)
{
};
}
private static PagerDutyClient CreateClient ()
{
//The uri MUST contain an ending slash otherwise HttpClient does not work correctly
var client = new HttpClient() {
BaseAddress = new Uri("https://api.pagerduty/"),
DefaultRequestHeaders = {
{ "api-key", "mykey" }
}
};
return new PagerDutyClient(client);
}
private static PagerDutyClient PagerDutyClient => _client.Value;
private static readonly Lazy<PagerDutyClient> _client = new Lazy<PagerDutyClient>(CreateClient);
}
public class PagerDutyClient
{
public PagerDutyClient ( HttpClient client )
{
_client = client;
}
public async Task<IEnumerable<User>> ListUsersAsync ( CancellationToken cancellationToken = default )
{
//Could also use a generic GetAsync<T> implementation if you have one
using (var response = await _client.GetAsync("users", cancellationToken).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
//Using default System.Net.Json, could also use JSON.NET via JsonConvert.
return await JsonSerializer.DeserializeAsync<IEnumerable<User>>(response.Content.ReadAsStream()
, cancellationToken: cancellationToken).ConfigureAwait(false);
};
}
private readonly HttpClient _client;
}
public class User
{
//Put your data here
}