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
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:
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.).
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.
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.
Do NOT embed long-lived keys directly in source code for production. Use Azure Key Vault, managed identities, or environment variables to secure secrets.
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
Install the SDK packages:pip install azure-core azure-ai-textanalyticsExample Python SDK usage. Replace endpoint and key with your values (do not hard-code in production).
Copy
# pythonimport osfrom azure.core.credentials import AzureKeyCredentialfrom azure.ai.textanalytics import TextAnalyticsClientdef 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 clientdef 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 Nonedef 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()
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:
Copy
# pythonimport requestsimport jsondef 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 Nonedef 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).
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.
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.
Always restrict and rotate keys regularly. Grant the minimum required permissions and monitor usage for unexpected calls.
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.