Skip to content

Instantly share code, notes, and snippets.

@JamesIgoe
Last active May 30, 2023 12:40
Show Gist options
  • Save JamesIgoe/e7a233bbdb8a305423688476c7f682c4 to your computer and use it in GitHub Desktop.
Save JamesIgoe/e7a233bbdb8a305423688476c7f682c4 to your computer and use it in GitHub Desktop.
Basics of generic method for making API POST calls
public static async Task<bool> PostInfoAsync<T>(string url, T request, string apiKey)
{
try
{
byte[] reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(request, Newtonsoft.Json.Formatting.None));
using HttpClient client = new();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Referer", Environment.MachineName);
client.DefaultRequestHeaders.Add("X-API-KEY", apiKey);
ByteArrayContent content = new(reqString);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
return true;
}
catch (Exception)
{
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment