Compartir a través de


Inicio rápido: Configuración y uso de los datos del catálogo de API de plataforma de Microsoft Learn

En este inicio rápido, aprenderá a configurar y ejecutar la API de plataforma de Microsoft Learn, que incluye ejemplos para recuperar cursos, rutas de aprendizaje, módulos y certificaciones.

Prerrequisitos

Antes de comenzar, asegúrese de que tiene instalado lo siguiente:

  • Node.js (versión 18.0.0 o posterior)

    • Node.js es un entorno de ejecución de JavaScript que permite ejecutar código JavaScript o TypeScript fuera de un explorador web. Es necesario ejecutar los scripts de ejemplo y administrar paquetes a través de npm (Administrador de paquetes de Node).
    • Descargar desde: https://nodejs.org/
    • Comprobación de la instalación: node --version
  • Azure CLI

    • Azure Command-Line Interface (CLI) es una herramienta para administrar recursos de Azure desde la línea de comandos. En esta guía, se utiliza para autenticar tu identidad, de manera que los ejemplos puedan acceder a la API de la plataforma Learn en tu nombre.
    • Descargar desde: https://learn.microsoft.com/cli/azure/install-azure-cli>
    • Comprobación de la instalación: az --version
  • Una cuenta de Azure

    • Se requiere una cuenta de Azure con una suscripción activa para autenticarse y acceder a la API de la plataforma de Microsoft Learn. La API usa microsoft Entra ID (anteriormente Azure Active Directory) para la autenticación, lo que requiere credenciales de Azure válidas. No hay ningún costo para recuperar el token de autenticación de la suscripción de Azure.
    • Necesita una suscripción de Azure activa.
    • Regístrese en: https://azure.microsoft.com/free/
  • Visual Studio Code (opcional)

    • Visual Studio Code (VS Code) es un editor de código ligero y gratuito con un terminal integrado, IntelliSense y compatibilidad con TypeScript. Aunque puede usar cualquier editor de texto y terminal, Visual Studio Code proporciona una experiencia simplificada para ejecutar estos ejemplos.
    • Descargar desde: https://code.visualstudio.com/
    • Comprobar la instalación: abra Visual Studio Code y presione Ctrl+' para abrir el terminal integrado.

Nota:

Todos los comandos escritos a continuación deben ejecutarse en un terminal de Git Bash. Puede usar el terminal integrado de VS Code (pulse Ctrl+`), Windows PowerShell o símbolo del sistema.

Configuración del proyecto

Siga estos pasos para crear un nuevo proyecto e instalar las dependencias necesarias.

  1. Cree una nueva carpeta para el proyecto y vaya a ella.

    mkdir learn-api-examples
    cd learn-api-examples
    
  2. Inicialice un nuevo proyecto de Node.js con la configuración predeterminada. La -y marca acepta automáticamente todos los valores predeterminados.

    npm init -y
    
  3. Instale los paquetes npm necesarios (@azure/identity para la autenticación, tsx para ejecutar TypeScript directamente, typescript el compilador y @types/node para las definiciones de tipo).

    npm install @azure/identity tsx typescript @types/node
    
  4. Cree un archivo llamado examples.ts y pegue el código siguiente. Esto incluye la autenticación que aprovecha las credenciales predeterminadas de Azure y varios ejemplos de las funcionalidades de catálogo disponibles a través de learn Platform API.

    /**
     * Microsoft Learn Platform API Examples
     * API Version: 2023-11-01-preview
     * Base URL: https://learn.microsoft.com/api/v1
     *
     * Authentication: OAuth2 with scope https://learn.microsoft.com/.default
     */
    
    import { DefaultAzureCredential } from "@azure/identity";
    
    const API_BASE_URL = "https://learn.microsoft.com/api/v1";
    const API_VERSION = "2023-11-01-preview";
    
    // ============================================================================
    // AUTHENTICATION HELPER
    // ============================================================================
    
    async function getAccessToken(): Promise<string> {
      const credential = new DefaultAzureCredential();
      const token = await credential.getToken("https://learn.microsoft.com/.default");
      return token.token;
    }
    
    /**
     * Helper to handle API response with error checking
     */
    async function handleResponse(response: Response, label: string): Promise<void> {
      if (!response.ok) {
        const text = await response.text();
        console.log(`${label} Error: ${response.status} ${response.statusText}`);
        console.log("Response:", text || "(empty)");
        return;
      }
    
      const text = await response.text();
      if (!text) {
        console.log(`${label}: (empty response)`);
        return;
      }
    
      try {
        const data = JSON.parse(text);
        console.log(`${label}:`, JSON.stringify(data, null, 2));
      } catch (e) {
        console.log(`${label} Parse Error: Invalid JSON`);
        console.log("Raw response:", text.substring(0, 500));
      }
    }
    
    // ============================================================================
    // TRAINING ENDPOINTS
    // ============================================================================
    
    /**
     * List all courses with optional filters
     * GET /courses
     */
    async function listCourses(options?: {
      levels?: string[];
      roles?: string[];
      products?: string[];
      locale?: string;
      maxpagesize?: number;
    }): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (options?.levels) params.append("levels", options.levels.join(","));
      if (options?.roles) params.append("roles", options.roles.join(","));
      if (options?.products) params.append("products", options.products.join(","));
      if (options?.locale) params.append("locale", options.locale);
      if (options?.maxpagesize) params.append("maxpagesize", options.maxpagesize.toString());
    
      const response = await fetch(`${API_BASE_URL}/courses?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Courses");
    }
    
    /**
     * Get a specific course by ID
     * GET /courses/{id}
     */
    async function getCourse(courseId: string, locale?: string): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (locale) params.append("locale", locale);
    
      const response = await fetch(`${API_BASE_URL}/courses/${courseId}?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Course");
    }
    
    /**
     * List all learning paths
     * GET /learning-paths
     */
    async function listLearningPaths(options?: {
      levels?: string[];
      roles?: string[];
      products?: string[];
      subjects?: string[];
      locale?: string;
      maxpagesize?: number;
    }): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (options?.levels) params.append("levels", options.levels.join(","));
      if (options?.roles) params.append("roles", options.roles.join(","));
      if (options?.products) params.append("products", options.products.join(","));
      if (options?.subjects) params.append("subjects", options.subjects.join(","));
      if (options?.locale) params.append("locale", options.locale);
      if (options?.maxpagesize) params.append("maxpagesize", options.maxpagesize.toString());
    
      const response = await fetch(`${API_BASE_URL}/learning-paths?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Learning Paths");
    }
    
    /**
     * Get a specific learning path by ID
     * GET /learning-paths/{id}
     */
    async function getLearningPath(learningPathId: string, locale?: string): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (locale) params.append("locale", locale);
    
      const response = await fetch(`${API_BASE_URL}/learning-paths/${learningPathId}?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Learning Path");
    }
    
    /**
     * List all modules
     * GET /modules
     */
    async function listModules(options?: {
      levels?: string[];
      roles?: string[];
      products?: string[];
      subjects?: string[];
      locale?: string;
      maxpagesize?: number;
    }): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (options?.levels) params.append("levels", options.levels.join(","));
      if (options?.roles) params.append("roles", options.roles.join(","));
      if (options?.products) params.append("products", options.products.join(","));
      if (options?.subjects) params.append("subjects", options.subjects.join(","));
      if (options?.locale) params.append("locale", options.locale);
      if (options?.maxpagesize) params.append("maxpagesize", options.maxpagesize.toString());
    
      const response = await fetch(`${API_BASE_URL}/modules?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Modules");
    }
    
    /**
     * Get a specific module by ID
     * GET /modules/{id}
     */
    async function getModule(moduleId: string, locale?: string): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (locale) params.append("locale", locale);
    
      const response = await fetch(`${API_BASE_URL}/modules/${moduleId}?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Module");
    }
    
    /**
     * Get a specific unit by ID
     * GET /units/{id}
     */
    async function getUnit(unitId: string, locale?: string): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (locale) params.append("locale", locale);
    
      const response = await fetch(`${API_BASE_URL}/units/${unitId}?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Unit");
    }
    
    // ============================================================================
    // CREDENTIALS ENDPOINTS
    // ============================================================================
    
    /**
     * List all certifications
     * GET /certifications
     */
    async function listCertifications(options?: {
      levels?: string[];
      roles?: string[];
      products?: string[];
      subjects?: string[];
      locale?: string;
      maxpagesize?: number;
    }): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (options?.levels) params.append("levels", options.levels.join(","));
      if (options?.roles) params.append("roles", options.roles.join(","));
      if (options?.products) params.append("products", options.products.join(","));
      if (options?.subjects) params.append("subjects", options.subjects.join(","));
      if (options?.locale) params.append("locale", options.locale);
      if (options?.maxpagesize) params.append("maxpagesize", options.maxpagesize.toString());
    
      const response = await fetch(`${API_BASE_URL}/certifications?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Certifications");
    }
    
    /**
     * Get a specific certification by ID
     * GET /certifications/{id}
     */
    async function getCertification(certificationId: string, locale?: string): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (locale) params.append("locale", locale);
    
      const response = await fetch(`${API_BASE_URL}/certifications/${certificationId}?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Certification");
    }
    
    /**
     * List all exams
     * GET /exams
     */
    async function listExams(options?: {
      levels?: string[];
      roles?: string[];
      products?: string[];
      locale?: string;
      maxpagesize?: number;
    }): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (options?.levels) params.append("levels", options.levels.join(","));
      if (options?.roles) params.append("roles", options.roles.join(","));
      if (options?.products) params.append("products", options.products.join(","));
      if (options?.locale) params.append("locale", options.locale);
      if (options?.maxpagesize) params.append("maxpagesize", options.maxpagesize.toString());
    
      const response = await fetch(`${API_BASE_URL}/exams?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Exams");
    }
    
    /**
     * Get a specific exam by ID
     * GET /exams/{id}
     */
    async function getExam(examId: string, locale?: string): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (locale) params.append("locale", locale);
    
      const response = await fetch(`${API_BASE_URL}/exams/${examId}?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Exam");
    }
    
    /**
     * List all applied skills
     * GET /applied-skills
     */
    async function listAppliedSkills(options?: {
      levels?: string[];
      roles?: string[];
      products?: string[];
      subjects?: string[];
      locale?: string;
      maxpagesize?: number;
    }): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (options?.levels) params.append("levels", options.levels.join(","));
      if (options?.roles) params.append("roles", options.roles.join(","));
      if (options?.products) params.append("products", options.products.join(","));
      if (options?.subjects) params.append("subjects", options.subjects.join(","));
      if (options?.locale) params.append("locale", options.locale);
      if (options?.maxpagesize) params.append("maxpagesize", options.maxpagesize.toString());
    
      const response = await fetch(`${API_BASE_URL}/applied-skills?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Applied Skills");
    }
    
    /**
     * Get a specific applied skill by ID
     * GET /applied-skills/{id}
     */
    async function getAppliedSkill(appliedSkillId: string, locale?: string): Promise<void> {
      const token = await getAccessToken();
    
      const params = new URLSearchParams({ "api-version": API_VERSION });
      if (locale) params.append("locale", locale);
    
      const response = await fetch(`${API_BASE_URL}/applied-skills/${appliedSkillId}?${params}`, {
        method: "GET",
        headers: {
          "Accept": "application/json",
          "Authorization": `Bearer ${token}`
        }
      });
    
      await handleResponse(response, "Applied Skill");
    }
    
    // ============================================================================
    // PAGINATION HELPER
    // ============================================================================
    
    /**
     * Helper to handle paginated responses
     */
    async function fetchAllPages<T>(initialUrl: string, token: string): Promise<T[]> {
      const allItems: T[] = [];
      let nextLink: string | undefined = initialUrl;
    
      while (nextLink) {
        const response = await fetch(nextLink, {
          method: "GET",
          headers: {
            "Accept": "application/json",
            "Authorization": `Bearer ${token}`
          }
        });
    
        const data = await response.json();
        allItems.push(...data.value);
        nextLink = data.nextLink;
      }
    
      return allItems;
    }
    
    // ============================================================================
    // EXAMPLE USAGE
    // ============================================================================
    
    async function main() {
      try {
        // List beginner-level certifications for Azure
        console.log("=== Listing Azure certifications (beginner level) ===");
        await listCertifications({
          levels: ["beginner"],
          products: ["azure"],
          maxpagesize: 5
        });
    
        // List certifications
        console.log("\n=== Listing certifications ===");
        await listCertifications({ maxpagesize: 5 });
    
        // List all Spanish learning paths
        console.log("\n=== Listing Spanish learning paths ===");
        await listLearningPaths({ locale: "es-es", maxpagesize: 5 });
    
        // Get a specific learning path by ID
        console.log("\n=== Getting learning path: learn.introduction-ai-azure ===");
        await getLearningPath("learn.introduction-ai-azure");
    
        // Get a specific module by ID
        console.log("\n=== Getting module: learn.wwl.fundamentals-generative-ai ===");
        await getModule("learn.wwl.fundamentals-generative-ai");
    
        // Get a specific unit by ID
        console.log("\n=== Getting unit: learn.wwl.fundamentals-generative-ai.agents ===");
        await getUnit("learn.wwl.fundamentals-generative-ai.agents");
    
        // Get a specific applied skill by ID
        console.log("\n=== Getting applied skill: applied-skill.deploy-and-configure-azure-monitor ===");
        await getAppliedSkill("applied-skill.deploy-and-configure-azure-monitor");
    
        // Get a specific certification by ID
        console.log("\n=== Getting certification: certification.d365-functional-consultant-customer-service ===");
        await getCertification("certification.d365-functional-consultant-customer-service");
    
        // Get a specific exam by ID
        console.log("\n=== Getting exam: exam.77-881 ===");
        await getExam("exam.77-881");
    
        // Get a specific instructor-led course by ID
        console.log("\n=== Getting instructor-led course: course.ai-900t00 ===");
        await getCourse("course.ai-900t00");
    
      } catch (error) {
        console.error("Error:", error);
      }
    }
    
    main();
    
    

Autenticación y ejecución de los ejemplos

Siga estos pasos para autenticarse con Azure y ejecutar el código de ejemplo.

  1. Inicie sesión en la CLI de Azure. En este paso se abre una ventana del explorador en la que se escriben las credenciales de Azure.

    az login
    
  2. Si tiene varias suscripciones, establezca la activa. Reemplace por <your-subscription-name> el nombre o el identificador de la suscripción.

    az account set --subscription "<your-subscription-name>"
    
  3. Compruebe que sus credenciales pueden acceder a Learn Platform API.

    az account get-access-token --resource https://learn.microsoft.com
    

    Si se ejecuta correctamente, verá una respuesta JSON con un accessToken campo.

  4. Ejecute el archivo de ejemplos mediante npx para ejecutar el tsx paquete.

    npx tsx examples.ts
    
  5. (Opcional) Guarde la salida en un archivo mediante el redireccionamiento de salida.

    npx tsx examples.ts > output.txt 2>&1
    

Limpieza de recursos

Si ya no necesita los recursos creados en este inicio rápido, puede quitarlos.

  1. Quite la carpeta del proyecto y todo su contenido.

    cd ..
    rm -rf learn-api-examples
    

    En Windows PowerShell, utilice:

    cd ..
    Remove-Item -Recurse -Force learn-api-examples
    
  2. (Opcional) Cierre la sesión de la CLI de Azure para quitar las credenciales almacenadas en caché.

    az logout
    

Nota:

En este inicio rápido no se crean recursos de Azure que incurren en costos. Las llamadas API usan la identidad de Azure existente solo para la autenticación.