0

I have a question and will appreciate it if anyone can answer me. I am new to C# programming so my question may be stupid. At my work, I been asked to create a C# app that can consume an external REST API. I have the URL for the API. I have also been given username , password, api key and secret key that is required to access the API. The request should be GET. Can someone tell me how to consume an API using api key, secret key, username and passowrd as authorization info? The project is supposed to be written in ASP.NET MVC.

  • I think you mean using Tokens for Authentication. If so, check out [JWT Authentication For ASP.Net Web API](https://stackoverflow.com/questions/40281050/jwt-authentication-for-asp-net-web-api/) – Reza Heidari Apr 08 '22 at 17:58
  • Doesn't the API provide some documentation? – David Apr 08 '22 at 18:03
  • https://aniks.xyz/how-to-secure-api-using-jwt-tokens-building-crud-api-using-jwt-tokens-with-asp-net-core-and-entity-framework-core-and-swagger/ – Amjad S. Apr 08 '22 at 18:07
  • I just need to get data from the API. Is there a way to do it using httpclient or httprequest class? – Steve Hall Apr 08 '22 at 18:19
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. – burnsi Apr 08 '22 at 20:08
  • @burnsi, I have edited the question and added a bit more detail to it. Thank you for the suggestion. – Steve Hall Apr 08 '22 at 22:07
  • Sorry but your question is Off-Topic. Stackoverflow is for having a specific problem with code and needing a solution for that. You just don´t know how to do this. There are plenty( and i mean plenty) of tutorials out there on how to consume an api with a c# Application. – burnsi Apr 08 '22 at 22:34

1 Answers1

0

You can use HttpClient and add the api key in the header as followed:

var apiKey = "the_API_key";
var apiBaseUrl = "https://baseURL.com";

HttpClient client = new();
client.BaseAddress = new Uri(apiBaseUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("apikey", apiKey);

HttpResponseMessage response = await client.GetAsync("the_requestURI");
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
   var objectModels = JsonConvert.DeserializeObject<ObjectModel>(await response.Content.ReadAsStringAsync());
}

At the end, if the response is received correctly, you can convert the received JSON content into your model. If needed, you can add some query string to the request-URI like: "Products?isActive=true"

Mahmood
  • 120
  • 2
  • 9