Search code examples
c#ibm-watsonvisual-recognition

Watson Visual Recognition API C# Authorisation


Trying to get Watson Visual Recognition working with C# but I am getting an unauthorised error when attempting to classify an image through the API. The credentials I'm using are the "Auto-generated service credentials".

The error that I am receiving is: ServiceResponseException: The API query failed with status code Unauthorized: Unauthorized

Here is my code:

class Program
{
    static void Main(string[] args)
    {
        string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        string versionDate = "2018-03-19";
        string endpoint = "https://gateway.watsonplatform.net/visual-recognition/api";

        VisualRecognitionService visualRecognition = new VisualRecognitionService(apiKey, versionDate);
        visualRecognition.SetEndpoint(endpoint);

        // throws error here
        var result = visualRecognition.Classify(url: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Collage_of_Nine_Dogs.jpg/1023px-Collage_of_Nine_Dogs.jpg"); 
    }
}

Also, let me know if I can provide anymore information that might help


Solution

  • Ok, I have found a solution after looking at this answer for a node.js implementation: Watson Visual Recognition - Unauthorized

    The issue was that I needed to use Iam Api Key for authentication, which can be done like this:

    class Program
    {
        static void Main(string[] args)
        {
            string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
            string versionDate = "2018-03-19";
            string endpoint = "https://gateway.watsonplatform.net/visual-recognition/api";
    
            VisualRecognitionService visualRecognition = new VisualRecognitionService(apiKey, versionDate);
            visualRecognition.SetEndpoint(endpoint);
    
            // updated to include token options with Iam Api Key
            TokenOptions options = new TokenOptions
            {
                IamApiKey = apiKey
            };
            visualRecognition.SetCredential(options);
            // end edit
    
            var result = visualRecognition.Classify(url: "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d9/Collage_of_Nine_Dogs.jpg/1023px-Collage_of_Nine_Dogs.jpg");
        }
    }
    

    Hope this helps anyone with a similar issue