Resolved API call which includes an API Key in C# application

ConsKa

Well-known member
Joined
Dec 11, 2020
Messages
140
Programming Experience
Beginner
Sorry if this is in the wrong place, I wasn't sure where to put it.

I honestly cannot believe how difficult I have found googling this question.

I would have thought it was really obvious, if you need to include an API key, then how do you go about putting that into your get request/application - there is a LOT of information about how to build an API which requires an API key, but I don't know whether I have entirely misunderstood the basis of the existence of the API key?

I found one topic on Stack Overflow about this, and the links are all dead, the documentation and code examples on MSDN are gone, searching for them reveals nothing. This may well be an old and dead method, but I still kinda need it.

Anyone have a good primer on this that isn't about building an API with an API key generation? I have put some code below that comes from I Am Tim Corey - whose demo on using API's I was learning from...

Thanks!

C#:
public static async Task<SunModel> LoadSunInformation()
        {
            string url = "https://api.sunrise-sunset.org/json?lat=51.531288&lng=0.017781&date=today";

            using (HttpResponseMessage response = await ApiHelper.ApiClient.GetAsync(url))
            {
                if (response.IsSuccessStatusCode)
                {
                    SunResultModel result = await response.Content.ReadAsAsync<SunResultModel>();

                    return result.Results;
                }
                else
                {
                    throw new Exception(response.ReasonPhrase);
                }
            }
        }
 
The reason for it being hard to get an answer is because it depends on the API that you are calling. You should be checking the documentation for the API that you are using. Some APIs have you only use the API key as part of the JSON payload during initial login, and then you are given a token that you should use put in you HTTP headers or cookie or as part of the payload for succeeding calls. Some APIs have you pass in the API key in the HTTP headers all the time. Others have you set a cookie. Others have you pass in the key naked in the URL.

Have you checked the documentation for that site you are accessing to see how it wants you to use the API key?
 
Yes I did, it states "an API key is sent along with the url for every operation"

It provides an example but just not in a language I program in:

JavaScript:
$ curl http://{SDP_BASE_URL}/api/v3/requests \
    - H "TECHNICIAN_KEY: XXXX-XXXX-XXXX-XXX (API key I believe)"
    - d "input_data= {
"request": {
    etc. etc.
}
}"

The documentation is written in a form that - this is obvious we don't need to tell you where to put it and I don't understand enough of what I think is javascript to convert the above to C# sharp.
 
The $ sign there represent the bash shell prompt. curl is a common *nix program used to send a web request. You can read the curl documentation to see what the various parameters passed to he program our, but my interpretation of the above is that -H means add an HTTP header that looks like:
C#:
TECHNICIAN_KEY: xxxx-xxxx-xxxx-xxx
 
So I am trying the below - good news, I am at least now getting a response, previously my code was throwing a null exception.

Bad news, the response is StatusCode 400 - so I am still a little off ....more reading to do. (that is not string interpolation simply a placeholder).

C#:
var client = new HttpClient();
var api = "xxx-xxx"

using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, "{site}/api/v3/etc."))
{
    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("TECHNICIAN_KEY", api);
    var itemInfo = client.SendAsync(requestMessage).Result;
    
    textbox1.Text = itemInfo.ToString();
}
 
Headers.Authorization add a "Authorization" header. Your curl example is adding a "TECHNICIAN_KEY" header.

curl -d (or --data) also means a POST request.
 
Yeah, it did say it was a post request, and it had a lot more information to include to "post" - but I was hoping that the information would be valid for the authorisation aspect - the TECHNICIAN_KEY - which it is now I read enough to work out how to add it to a header.

Found this, it worked with some tweaking:

C#:
HttpClient httpClient = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage();
    request.RequestUri = new Uri("Your_get_URI");
    request.Method = HttpMethod.Get;
    request.Headers.Add("TECHNICIAN_KEY", api);
    HttpResponseMessage response =  await httpClient.SendAsync(request);
    var responseString = await response.Content.ReadAsStringAsync();
 
Last edited:
Back
Top Bottom