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

# Working with Azure AI Services

> Guide to creating Azure AI Language services and performing sentiment analysis using Python SDK and REST API, comparing approaches and covering endpoints, keys, security, and best practices.

This guide demonstrates how to create an Azure AI Language service in the Azure portal and call its sentiment analysis capability using both the Python SDK and the REST API. You’ll see that the SDK provides a more concise developer experience, while the REST example shows the underlying HTTP payloads and is useful when SDKs are unavailable.

What you'll learn:

* How to create an Azure AI service (multi-service account vs. single dedicated service)
* Where to find endpoints and keys
* Example code for sentiment analysis using the Python SDK
* Example code for sentiment analysis using the REST API
* When to choose SDK vs. REST

## Create an Azure AI service in the portal

If you already have a multi-service account, it exposes multiple capabilities (OpenAI, Speech, Vision, Language, etc.) under the same account-level keys. The portal lists AI service resources like this:

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GllRB2BDGSXhqELa/images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-ai-services-aiservicesai900.jpg?fit=max&auto=format&n=GllRB2BDGSXhqELa&q=85&s=84657ee3554146fb369283c9d2595346" alt="A screenshot of the Microsoft Azure portal showing the &#x22;Azure AI services&#x22; page, with a left-hand menu of AI service options and a single listed resource named &#x22;aiservicesai900&#x22; in the main pane." width="1920" height="1080" data-path="images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-ai-services-aiservicesai900.jpg" />
</Frame>

If you open a multi-service account and look at Keys and Endpoint, you'll see the shared account-level keys and multiple capability endpoints (OpenAI, Speech, Content Safety, Computer Vision, Content Understanding, etc.).

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GllRB2BDGSXhqELa/images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-ai-keys-endpoint-openai-aiservicesai900.jpg?fit=max&auto=format&n=GllRB2BDGSXhqELa&q=85&s=3c7d61b698bf100c311bcee472f7b971" alt="A screenshot of the Azure AI Services &#x22;Keys and Endpoint&#x22; page for the resource &#x22;aiservicesai900.&#x22; It shows masked API keys, the location &#x22;eastus,&#x22; and OpenAI endpoints for Language, Dall‑E, and Whisper." width="1920" height="1080" data-path="images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-ai-keys-endpoint-openai-aiservicesai900.jpg" />
</Frame>

If you prefer a single-purpose resource (for example, a dedicated Language resource), create it from the Language service blade. During creation:

* Select a subscription and resource group (e.g., rg-ai102-get-started-sdk)
* Choose a region (e.g., East US)
* Provide a globally unique resource name (this becomes \<service-name>.cognitiveservices.azure.com)
* Pick a pricing tier (for example S1)

Create the resource and then check the resource group/overview to confirm creation.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GllRB2BDGSXhqELa/images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-create-rg-rg-ai102-get-star.jpg?fit=max&auto=format&n=GllRB2BDGSXhqELa&q=85&s=92f090dc6cd8dd75ba8a37561f8a2c53" alt="A screenshot of the Azure portal showing the Project Details form and a pop-up to create a new resource group, with the name field filled as &#x22;rg-ai102-get-star&#x22; and OK/Cancel buttons. The Subscription is set to &#x22;Kodekloud Labs&#x22; and a notice about the free tier/pricing is visible below." width="1920" height="1080" data-path="images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-create-rg-rg-ai102-get-star.jpg" />
</Frame>

Once created, open the resource and go to **Keys and Endpoint** to copy the endpoint URL and one of the two keys for use in your client code.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/GllRB2BDGSXhqELa/images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-portal-rg-ai102-overview.jpg?fit=max&auto=format&n=GllRB2BDGSXhqELa&q=85&s=14c1ea8f56c95002879b730b094b0363" alt="A screenshot of the Microsoft Azure portal showing the Overview page for a resource group named &#x22;rg-ai102-get-started-sdk.&#x22; The page displays subscription details, filters and a single listed resource, plus the left-hand navigation menu with settings and monitoring options." width="1920" height="1080" data-path="images/AI-102-Microsoft-Certified-Azure-AI-Engineer-Associate/Get-Started-with-Azure-AI-Services/Working-with-Azure-AI-Services/azure-portal-rg-ai102-overview.jpg" />
</Frame>

<Callout icon="lightbulb" color="#1CB2FE">
  Do NOT embed long-lived keys directly in source code for production. Use Azure Key Vault, managed identities, or environment variables to secure secrets.
</Callout>

## Choose: SDK vs REST

Both approaches return a sentiment label and confidence scores. Use SDKs when available for a cleaner, idiomatic interface and automatic authentication helpers. Use REST when SDKs are not available or you need direct HTTP access.

Comparison at a glance:

| Resource                            | Use case                                          | Pros                                                       |
| ----------------------------------- | ------------------------------------------------- | ---------------------------------------------------------- |
| Python SDK (azure-ai-textanalytics) | Typical development on Python                     | Concise code, structured objects, handles auth and retries |
| REST API (HTTP POST)                | Direct HTTP integrations, non-supported languages | Shows exact payload and headers, no SDK dependency         |

Useful links:

* [Azure AI Language service overview](https://learn.microsoft.com/azure/ai-services/)
* [Azure SDK for Python - Text Analytics docs](https://learn.microsoft.com/azure/cognitive-services/text-analytics/overview)
* [Language REST API reference (analyze-text)](https://learn.microsoft.com/azure/cognitive-services/language-service/rest-api)

## SDK approach (Python)

Install the SDK packages:

pip install azure-core azure-ai-textanalytics

Example Python SDK usage. Replace endpoint and key with your values (do not hard-code in production).

```python theme={null}
# python
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

def authenticate_client(endpoint: str, key: str) -> TextAnalyticsClient:
    """
    Authenticate and return a TextAnalyticsClient using the provided endpoint and key.
    """
    credential = AzureKeyCredential(key)
    client = TextAnalyticsClient(endpoint=endpoint, credential=credential)
    return client

def sentiment_analysis(client: TextAnalyticsClient, text: str):
    """
    Perform sentiment analysis on a single document string.
    """
    try:
        response = client.analyze_sentiment([text])[0]
        print(f"\nDocument Sentiment: {response.sentiment}")
        print(
            f"Overall scores: positive={response.confidence_scores.positive:.2f}, "
            f"neutral={response.confidence_scores.neutral:.2f}, "
            f"negative={response.confidence_scores.negative:.2f}"
        )
        return response
    except Exception as err:
        print(f"Encountered exception: {err}")
        return None

def main():
    # Replace with your endpoint and key (do not hard-code in production)
    endpoint = "https://ai102cogservices909.cognitiveservices.azure.com/"
    key = "<YOUR_KEY>"
    sample_text = "Learning AI is good for career growth."
    client = authenticate_client(endpoint, key)
    print("Performing sentiment analysis:")
    sentiment_result = sentiment_analysis(client, sample_text)

if __name__ == "__main__":
    main()
```

What the SDK returns:

* Document-level sentiment (positive / neutral / negative)
* Confidence scores for each class
* Optional per-sentence sentiment and additional metadata if requested

## REST approach (Python + requests)

The REST approach requires building the analyze-text URL and POSTing a JSON body. Ensure boolean values in the JSON are proper booleans (true / false), not strings. Use the endpoint that you copied from Keys and Endpoint. The endpoint should usually end with a trailing slash (or adjust URL concatenation accordingly).

Example Python REST code:

```python theme={null}
# python
import requests
import json

def sentiment_analysis(endpoint: str, key: str, text: str):
    """
    Call the Azure Language analyze-text REST API for sentiment analysis.
    The endpoint should include the trailing slash, e.g. "https://<name>.cognitiveservices.azure.com/".
    """
    url = f"{endpoint}language/:analyze-text?api-version=2023-04-15-preview"

    headers = {
        "Ocp-Apim-Subscription-Key": key,
        "Content-Type": "application/json"
    }

    body = {
        "kind": "SentimentAnalysis",
        "parameters": {
            "modelVersion": "latest",
            "opinionMining": True
        },
        "analysisInput": {
            "documents": [
                {
                    "id": "1",
                    "language": "en",
                    "text": text
                }
            ]
        }
    }

    try:
        response = requests.post(url, headers=headers, json=body)
        if response.status_code == 200:
            sentiment_data = response.json()
            document = sentiment_data["results"]["documents"][0]
            print(f"\nDocument Sentiment: {document['sentiment']}")
            scores = document["confidenceScores"]
            print(
                f"Overall scores: positive={scores['positive']:.2f}, "
                f"neutral={scores['neutral']:.2f}, "
                f"negative={scores['negative']:.2f}"
            )
            return document
        else:
            print(f"Error: {response.status_code}")
            print(response.text)
            return None
    except Exception as err:
        print(f"Encountered exception: {err}")
        return None

def main():
    endpoint = "https://ai102cogservices909.cognitiveservices.azure.com/"  # Endpoint URL (include trailing slash)
    key = "<YOUR_KEY>"
    sample_text = "The food and service were unacceptable."
    print("Performing sentiment analysis:")
    sentiment_analysis(endpoint, key, sample_text)

if __name__ == "__main__":
    main()
```

Notes on the REST example:

* The REST payload reveals the exact request structure (kind, parameters, analysisInput.documents).
* Set "opinionMining": true to enable opinion mining in results; omit or set false if not needed.
* The header shown uses Ocp-Apim-Subscription-Key; depending on your resource type, you may also see header variants (follow the current Azure REST docs).

## Comparing results and examples

Both SDK and REST return a sentiment label and confidence scores. Example inputs and typical outcomes:

* "Learning AI is good for career growth." — typically returns positive with a high positive confidence score.
* "The food and service were unacceptable." — typically returns negative.
* Mixed content — e.g., "Hotel is awesome. The food and service were unacceptable." — shows how per-sentence analysis can reveal mixed sentiments inside a single document.

Use per-sentence results when you need more granular insights about different parts of a document.

## Best practices & next steps

* For production, never hard-code credentials. Use:
  * Azure Key Vault
  * Managed identities (when running in Azure)
  * Environment variables with secure deployment pipelines
* Prefer SDKs for simpler, cleaner code and better integration with client libraries.
* Use REST for custom clients, language/platforms without an SDK, or to inspect raw payloads.

<Callout icon="warning" color="#FF6B6B">
  Always restrict and rotate keys regularly. Grant the minimum required permissions and monitor usage for unexpected calls.
</Callout>

You can apply the same patterns shown here to other Azure AI services (Vision, Speech, OpenAI, Content Safety). In later examples we'll use a mix of SDKs and other languages (for example, C#/.NET) where applicable.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/ai-102-microsoft-certified-azure-ai-engineer-associate/module/10ea4eb0-486e-4464-a864-dda671e1b308/lesson/ebf9325a-2e32-4fc7-9d93-187cb7347f2e" />
</CardGroup>
