Skip to content
Learni
View all tutorials
Azure

How to Use Azure Cognitive Services in 2026

Lire en français

Introduction

Azure Cognitive Services is a suite of pre-trained AI services from Microsoft Azure, letting you add capabilities like image recognition, text analysis, or speech synthesis without machine learning expertise. In 2026, these services—now renamed Azure AI Services—are essential for developers looking to supercharge their apps with scalable, secure AI.

Why does it matter? Picture automatically analyzing a user-uploaded photo or detecting sentiment in a customer comment in real time. It accelerates development, cuts costs (pay-as-you-go), and meets GDPR standards through Azure. This beginner tutorial walks you step by step through creating a resource, getting your keys, and calling two flagship REST APIs in Node.js: Computer Vision to describe an image and Text Analytics for sentiment analysis. By the end, you'll have a working script ready to deploy. No complex SDKs—just pure HTTP to master the fundamentals.

Prerequisites

  • A free Azure account (includes $200 credit).
  • Node.js 20+ installed (download here).
  • A code editor like VS Code.
  • Basic JavaScript and HTTP knowledge (fetch).
  • 10 minutes to create your Azure resource.

Initialize the Node.js Project

terminal
mkdir azure-cognitive-demo
cd azure-cognitive-demo
npm init -y
npm install dotenv

This command creates a project folder, initializes package.json, and installs dotenv to handle secrets like API keys. Skip heavy SDKs for this pure REST tutorial. Run in your terminal for instant setup.

Create Your Azure Cognitive Services Resource

  1. Head to portal.azure.com and sign in.
  2. Click Create a resource > Search for Azure AI Services (like multi-service Cognitive Services).
  3. Pick your region (e.g., France Central), a unique name (e.g., myCogServ2026), and the free F0 tier.
  4. Once deployed (2 min), note the Endpoint (e.g., https://francecentral.api.cognitive.microsoft.com/) and Keys (Key 1/Key 2) under Keys and Endpoint.
Tip: Stick with Key 1 for testing. Rotate it regularly for security.

Configure Environment Variables

.env
ENDPOINT=https://votre-region.api.cognitive.microsoft.com/
KEY=votre-cle-api-ici

Create this .env file in your project root with your actual endpoint and key (no quotes). Dotenv loads it automatically. Pitfall: Never commit .env to Git—add it to .gitignore to prevent key leaks.

Image Analysis Script with Computer Vision

vision.js
require('dotenv').config();

const endpoint = process.env.ENDPOINT;
const key = process.env.KEY;
const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Seattle_-_Pike_Place_Market.jpg/320px-Seattle_-_Pike_Place_Market.jpg';

async function analyzeImage() {
  try {
    const response = await fetch(`${endpoint}/vision/v3.2/analyze?visualFeatures=Description,Objects&details=Landmarks&language=fr`, {
      method: 'POST',
      headers: {
        'Ocp-Apim-Subscription-Key': key,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        url: imageUrl
      })
    });

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

    const data = await response.json();
    console.log('Description de l\'image:');
    console.log(data.description.captions[0].text);
    console.log('\nObjets détectés:');
    data.description.objects?.forEach(obj => console.log(`- ${obj.object}`));
  } catch (error) {
    console.error('Erreur:', error.message);
  }
}

analyzeImage();

This script sends a public image URL to Computer Vision to generate a description in French and list detected objects. The Ocp-Apim-Subscription-Key header is required for authentication. Pitfall: Double-check the endpoint; a typo leads to 401 Unauthorized.

Test the Image Analysis

Run node vision.js. Expected output:

Description: A bustling outdoor market with fresh fruit and vegetable stalls, people, and the Pike Place Market in Seattle.
Objects: apple, banana, person...

If you get a 429 error: quota exceeded (F0 is limited). Upgrade to paid S0 if needed. API v3.2 is stable and beginner-friendly.

Sentiment Analysis Script with Text Analytics

sentiment.js
require('dotenv').config();

const endpoint = process.env.ENDPOINT;
const key = process.env.KEY;
const documents = [
  {
    id: '1',
    language: 'fr',
    text: 'Ce produit est génial ! Je l\'adore et le recommande.'
  },
  {
    id: '2',
    language: 'fr',
    text: 'Service nul, déçu et en colère.'
  }
];

async function analyzeSentiment() {
  try {
    const response = await fetch(`${endpoint}/text/analytics/v3.1/sentiment`, {
      method: 'POST',
      headers: {
        'Ocp-Apim-Subscription-Key': key,
        'Content-Type': 'application/json',
        'Apim-Request-Id': 'unique-id-' + Date.now()
      },
      body: JSON.stringify({
        documents
      })
    });

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

    const data = await response.json();
    data.documents.forEach(doc => {
      console.log(`Document ${doc.id}: ${doc.confidenceScores.positive.toFixed(2)} positif, ${doc.confidenceScores.negative.toFixed(2)} négatif`);
    });
  } catch (error) {
    console.error('Erreur:', error.message);
  }
}

analyzeSentiment();

This code analyzes sentiment on two French texts, outputting positive/negative confidence scores. The Apim-Request-Id header aids debugging. Pitfall: The 'language' field is mandatory; omit it and you get a 400 error.

Run and Interpret the Results

  • node sentiment.jsDocument 1: 0.99 positive, Document 2: 0.98 negative.
These services share the same multi-service key. Scale up by adding more documents or features like 'keyPhrases'.

Add to package.json for Easy Execution

package.json
{
  "name": "azure-cognitive-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "vision": "node vision.js",
    "sentiment": "node sentiment.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "dotenv": "^16.4.5"
  }
}

Update package.json with npm scripts for quick runs: npm run vision. Makes your project professional and reproducible. Pitfall: Verify versions; use dotenv >=16 with Node 20+.

Combined Script for Both Services

demo.js
require('dotenv').config();

const endpoint = process.env.ENDPOINT;
const key = process.env.KEY;

async function runDemo() {
  console.log('=== Azure Cognitive Services Demo ===');

  // Vision
  const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/14/Seattle_-_Pike_Place_Market.jpg/320px-Seattle_-_Pike_Place_Market.jpg';
  const visionRes = await fetch(`${endpoint}/vision/v3.2/analyze?visualFeatures=Description&language=fr`, {
    method: 'POST',
    headers: { 'Ocp-Apim-Subscription-Key': key, 'Content-Type': 'application/json' },
    body: JSON.stringify({ url: imageUrl })
  });
  const visionData = await visionRes.json();
  console.log('Vision:', visionData.description.captions[0].text);

  // Sentiment
  const docs = [{ id: '1', language: 'fr', text: 'Super tutoriel !' }];
  const sentRes = await fetch(`${endpoint}/text/analytics/v3.1/sentiment`, {
    method: 'POST',
    headers: { 'Ocp-Apim-Subscription-Key': key, 'Content-Type': 'application/json' },
    body: JSON.stringify({ documents: docs })
  });
  const sentData = await sentRes.json();
  console.log('Sentiment:', sentData.documents[0].sentiment);
}

runDemo().catch(console.error);

This script runs both APIs in one async flow. Perfect for demos. Use .catch for global error handling. Pitfall: Parallel async calls work fine, but serialize them for strict quotas.

Best Practices

  • Secure keys: Use Azure Key Vault in production—never hardcode them.
  • Rate limiting: Add retry logic with exponential backoff for 429 errors.
  • Input validation: Verify URLs and sizes before sending.
  • Monitoring: Enable Azure Application Insights for logging.
  • Language: Always specify 'language=en' for localized results.

Common Errors to Avoid

  • 401 Unauthorized: Wrong key or endpoint—copy fresh from the portal.
  • 400 Bad Request: Malformed JSON body or missing 'language'.
  • .env ignored: Ensure require('dotenv').config() runs first.
  • F0 quota exhausted: Switch to S0 ($0.001/1000 transactions).

Next Steps

How to Use Azure AI Services in 2026 | Node.js | Learni