I was trying to write a post API call to watson tone analyzer service in C#. It seems that the way to authenticate a user was changed lately from username and password to an api key.
I was trying to pass the apikey through "Authorization" header, or through a header called "apikey".. In both cases I received error 401 Unauthorized.. The other header I was using is Content-Type sets to application/json..
This calls doesn't work in a .net project nor in postman.
How can I send an API request using C#, how shell I pass the api key, and what headers should I use ?
This is the code I tried(This code returns an error of internal server error 500, while the tests I did with postman returns 401 Unauthorized):
HttpClient client = new HttpClient();
string baseURL;
string apikey= "****************";
baseURL = "https://gateway-lon.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21";
string postData = "{\"text\": \"" + "hi hello" + "\"}";
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apikey", apikey);
var response = client.PostAsync(baseURL, new StringContent(postData, Encoding.UTF8, "application/json")).Result;
Console.WriteLine(response);
The error I am receiving:
StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Mime-Version: 1.0
Connection: close
Date: Sun, 17 Feb 2019 11:37:53 GMT
Server: AkamaiGHost
Content-Length: 177
Content-Type: text/html
Expires: Sun, 17 Feb 2019 11:37:53 GMT
}
var response = client.PostAsync(baseURL, new StringContent(postData, Encoding.UTF8, "application/json")).Result;
– ckuriAuthorization
headers username to "apikey" and the password to your apikey. Soclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("apikey", apikey);
. – ckuri