> ## 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.

# Sentiment Analysis

> Run sentiment analysis on a social media post or comment to learn if the text is positive, negative, or neutral, with recommendations to improve it.

Generate a sentiment analysis on a social media post or comment to understand if the text is positive, negative, or neutral and recommendations on improving the text for a more positive reaction.

## Header Parameters

**Authorization** `string` *required*

[API Key](https://www.ayrshare.com/docs/apis/overview.md#authorization) of the Primary Profile.

Format: `Authorization: Bearer API_KEY`

## Body Parameters

**text** `string` *required*

The string of text to generate the sentiment analysis on.

### Request Examples

```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);
    }
}
```

```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"
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.