> ## Documentation Index
> Fetch the complete documentation index at: https://www.ayrshare.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Analyse de sentiment

> Générez une analyse de sentiment sur une publication ou un commentaire sur les réseaux sociaux

export const HeaderAPI = ({noProfileKey, profileKeyRequired}) => <>
    <ParamField header="Authorization" type="string" required>
      <a href="/apis/overview#authorization">API Key</a> of the Primary Profile.
      <br />
      <br />
      Format: <code>Authorization: Bearer API_KEY</code>
    </ParamField>
    {!noProfileKey && (profileKeyRequired ? <ParamField header="Profile-Key" type="string" required>
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField> : <ParamField header="Profile-Key" type="string">
          <a href="/apis/overview#profile-key-format">Profile Key</a> of a User Profile.
          <br />
          <br />
          Format: <code>Profile-Key: PROFILE_KEY</code>
        </ParamField>)}
  </>;

export const PlansAvailable = ({plans = [], maxPackRequired}) => {
  let displayPlans = plans;
  if (plans && plans.length === 1) {
    const lowerCasePlan = plans[0].toLowerCase();
    if (lowerCasePlan === "business") {
      displayPlans = ["Launch", "Business", "Enterprise"];
    } else if (lowerCasePlan === "premium") {
      displayPlans = ["Premium", "Launch", "Business", "Enterprise"];
    }
  }
  return <Note>
Available on {displayPlans.length === 1 ? "the " : ""}
{displayPlans.join(", ").replace(/\b\w/g, l => l.toUpperCase())}{" "}
{displayPlans.length > 1 ? "plans" : "plan"}.

{maxPackRequired && <span onClick={() => window.open('https://www.ayrshare.com/docs/additional/maxpack', '_self')} className="flex items-center mt-2 cursor-pointer">
 <span className="px-1.5 py-0.5 rounded text-sm" style={{
    backgroundColor: '#C264B6',
    color: 'white',
    fontSize: '12px'
  }}>
   Max Pack required
 </span>
</span>}
</Note>;
};

<PlansAvailable plans={["premium"]} maxPackRequired={true} />

Générez une analyse de sentiment sur une publication ou un commentaire sur les réseaux sociaux pour comprendre si le texte est positif, négatif ou neutre, et obtenez des recommandations pour améliorer le texte afin d'obtenir une réaction plus positive.

## Paramètres d'en-tête

<HeaderAPI noProfileKey />

## Paramètres du corps

<ParamField body="text" type="string" required>
  La chaîne de texte sur laquelle effectuer l'analyse de sentiment.
</ParamField>

### Exemples de requêtes

<RequestExample>
  ```bash cURL theme={"system"}
  curl \
  -H "Authorization: Bearer API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"text": "These shoes aren't the best. The color has faded and they are uncomfortable to walk in."}' \
  -X POST https://api.ayrshare.com/api/generate/sentiment
  ```

  ```javascript JavaScript theme={"system"}
  const API_KEY = 'YOUR_API_KEY';
  const analyzeTextSentiment = async (text) => {
    try {
      const response = await fetch('https://api.ayrshare.com/api/generate/sentiment', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_KEY}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ text })
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      console.log('Sentiment Analysis Result:', data);
      return data;
    } catch (error) {
      console.error('Error analyzing sentiment:', error.message);
      throw error;
    }
  };
  ```

  ```python Python theme={"system"}
  import requests
  import json

  API_KEY = 'YOUR_API_KEY'
  def analyze_text_sentiment(text):
      url = 'https://api.ayrshare.com/api/generate/sentiment'
      headers = {
          'Authorization': f'Bearer {API_KEY}',
          'Content-Type': 'application/json'
      }
      data = {'text': text}

      try:
          response = requests.post(url, headers=headers, json=data)
          response.raise_for_status()  # Raises a HTTPError if the status is 4xx, 5xx
          result = response.json()
          print('Sentiment Analysis Result:', json.dumps(result, indent=2))
          return result
      except requests.exceptions.RequestException as e:
          print('Error analyzing sentiment:', e)
          raise
  ```

  ```php PHP theme={"system"}
  <?php

  $API_KEY = 'YOUR_API_KEY';
  function analyzeTextSentiment($text) {
      global $API_KEY;

      $url = 'https://api.ayrshare.com/api/generate/sentiment';
      $headers = [
          'Authorization: Bearer ' . $API_KEY,
          'Content-Type: application/json'
      ];
      $data = json_encode(['text' => $text]);

      $ch = curl_init($url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

      $response = curl_exec($ch);
      $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

      if (curl_errno($ch)) {
          echo 'Error analyzing sentiment: ' . curl_error($ch);
          return null;
      }
      curl_close($ch);

      if ($httpCode >= 200 && $httpCode < 300) {
          $result = json_decode($response, true);
          echo "Sentiment Analysis Result:\n";
          print_r($result);
          return $result;
      } else {
          echo "HTTP Error: " . $httpCode . "\n";
          echo "Response: " . $response . "\n";
          return null;
      }
  }
  ```

  ```csharp C# theme={"system"}
  using System;
  using System.Net.Http;
  using System.Text;
  using System.Threading.Tasks;
  using System.Text.Json;

  class Program
  {
      private const string API_KEY = "YOUR_API_KEY";
      private static readonly HttpClient client = new HttpClient();

      static async Task Main(string[] args)
      {
          string textToAnalyze = "These shoes aren't the best. The color has faded and they are uncomfortable to walk in.";

          try
          {
              var result = await AnalyzeTextSentimentAsync(textToAnalyze);
              Console.WriteLine("Sentiment Analysis Result:");
              Console.WriteLine(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
          }
          catch (Exception e)
          {
              Console.WriteLine($"An error occurred: {e.Message}");
          }
      }

      static async Task<JsonElement> AnalyzeTextSentimentAsync(string text)
      {
          var url = "https://api.ayrshare.com/api/generate/sentiment";
          var requestData = new { text = text };

          client.DefaultRequestHeaders.Clear();
          client.DefaultRequestHeaders.Add("Authorization", $"Bearer {API_KEY}");

          var json = JsonSerializer.Serialize(requestData);
          var content = new StringContent(json, Encoding.UTF8, "application/json");

          var response = await client.PostAsync(url, content);

          if (!response.IsSuccessStatusCode)
          {
              throw new HttpRequestException($"HTTP error! status: {response.StatusCode}");
          }

          var responseBody = await response.Content.ReadAsStringAsync();
          return JsonSerializer.Deserialize<JsonElement>(responseBody);
      }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 200: Success theme={"system"}
  {
      "status": "success",
      "text": "These shoes aren't the best. The color has faded and they are uncomfortable to walk in.",
      "sentimentAnalysis": {
          "sentiment": "negative", // positive, negative, or neutral
          "opportunities": [
              "Improve color durability",
              "Enhance comfort level"
          ],
          "recommendations": [
              {
                  "opportunity": "Improve color durability",
                  "recommendation": "Investigate and use higher-quality dyes or materials to prevent fading over time."
              },
              {
                  "opportunity": "Enhance comfort level",
                  "recommendation": "Review and possibly redesign the shoe's insole and cushioning to provide better support and comfort for walking."
              }
          ]
      }
  }
  ```

  ```json 400: Error theme={"system"}
  {
    "action": "request",
    "status": "error",
    "code": 101,
    "message": "Missing or incorrect parameters. Please verify with the docs. .../ayrshare.com/rest-api/endpoints"
  }
  ```
</ResponseExample>
