Search code examples
c#azurewebformstext-analytics-api

Why am I getting (400) Bad Request error when connecting to Text Analytics API?


I am new C# developer and I am trying to use Text Analytics API with Azure Machine Learning in my test ASP.NET application to define the sentiment and key phrases for the tweets I have in the database. I followed this useful article over here to be able to connect to Text Analytics API. While debugging my code, I was able to get the key phrases and sentiment for the first tweet in the list and then I got the following exception and I don't know why:

The remote server returned an error: (400) Bad Request.

Here's my code:

private const string apiKey = "XXXXXXXXX"; //Key 2 value of Text Analytics API from Azure Portal
        private const string sentimentUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment";
        private const string keyPhrasesUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/keyPhrases";
        private const string languageUri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/languages";

        protected void Page_Load(object sender, EventArgs e)
        {

        }


        private IEnumerable<T_Tweet> GetData()
        {
            TweetBL tweetBl = new TweetBL();
            IEnumerable<T_Tweet> tweetsList = tweetBl.GetTweets();
            return tweetsList;
        }


        protected void lbtnAnalyze_Click(object sender, EventArgs e)
        {
            var tweetsList = GetData();
            if (tweetsList != null)
            {
                List<TweetSentimentModel> tweetSenti = new List<TweetSentimentModel>();
                foreach (var tweet in tweetsList)
                {
                    try
                    {
                        // Prepare headers
                        var client = new WebClient();
                        client.Headers.Add("Ocp-Apim-Subscription-Key", apiKey);
                        client.Headers.Add("Content-Type", "application/json");
                        client.Headers.Add("Accept", "application/json");

                        // Detect language
                        var postData1 = @"{""documents"":[{""id"":""1"", ""text"":""@sampleText""}]}".Replace("@sampleText", tweet.TweetText);
                        var response1 = client.UploadString(languageUri, postData1);
                        var language = new Regex(@"""iso6391Name"":""(\w+)""").Match(response1).Groups[1].Value;

                        // Determine sentiment
                        var postData2 = @"{""documents"":[{""id"":""1"", ""language"":""@language"", ""text"":""@sampleText""}]}".Replace("@sampleText", tweet.TweetText).Replace("@language", language);
                        var response2 = client.UploadString(sentimentUri, postData2);
                        var sentimentStr = new Regex(@"""score"":([\d.]+)").Match(response2).Groups[1].Value;
                        var sentiment = Convert.ToDouble(sentimentStr, System.Globalization.CultureInfo.InvariantCulture);

                        // Detemine key phrases
                        var postData3 = postData2;
                        var response3 = client.UploadString(keyPhrasesUri, postData2);
                        var keyPhrases = new Regex(@"""keyPhrases"":(\[[^\]]*\])").Match(response3).Groups[1].Value;


                        TweetSentimentModel tweetSentiObj = new TweetSentimentModel();
                        tweetSentiObj.TweetId = tweet.Id;
                        tweetSentiObj.TweetText = tweet.TweetText;
                        tweetSentiObj.SentimentLabel = sentiment.ToString();
                        tweetSentiObj.KeyPhrases = keyPhrases;
                        tweetSentiObj.CreatedOn = DateTime.Now;
                        tweetSenti.Add(tweetSentiObj);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                if (tweetSenti != null)
                {
                    PrintAnalysisResults(tweetSenti);
                }
            }
        }

Could you please tell me why I am getting this error and how I can fix it?


Solution

  • I was able to get the key phrases and sentiment for the first tweet in the list and then I got the following exception and I don't know why:

    According to your description, the difference between second time and first time is the tweet object. And (400) Bad Request is also meaning that http request client paramters are not correct.

    I can repro it while tweet.TweetText equals null or tweet.TweetText.trim() equals string.empty. enter image description here

    Please have try to debug, if it is that case ,please have a try add logic to control it. The following is the demo code.

    if (!string.IsNullOrEmpty(tweet.TweetText?.Trim()))
      {
           // Determine sentiment
           var postData2 = @"{""documents"":[{""id"":""1"", ""language"":""@language"", ""text"":""@sampleText""}]}".Replace(
                                "@sampleText", tweet.TweetText).Replace("@language", language);
                        var response2 = client.UploadString(SentimentUri, postData2);
                        var sentimentStr = new Regex(@"""score"":([\d.]+)").Match(response2).Groups[1].Value;
                        var sentiment = Convert.ToDouble(sentimentStr, System.Globalization.CultureInfo.InvariantCulture);
    
                        // Detemine key phrases
                        var postData3 = postData2;
                        var response3 = client.UploadString(KeyPhrasesUri, postData2);
                        var keyPhrases = new Regex(@"""keyPhrases"":(\[[^\]]*\])").Match(response3).Groups[1].Value;
    
        }