แชร์ผ่าน


เริ่มต้นใช้งานด่วน: ตั้งค่าและใช้ข้อมูลแค็ตตาล็อก Microsoft Learn Platform API

ในการเริ่มต้นใช้งานด่วนนี้ คุณจะได้เรียนรู้วิธีตั้งค่าและเรียกใช้ Microsoft Learn Platform API ซึ่งรวมถึงตัวอย่างในการดึงข้อมูลหลักสูตร เส้นทางการเรียนรู้ โมดูล และการรับรอง

ข้อกําหนดเบื้องต้น

ก่อนที่คุณจะเริ่มต้น ตรวจสอบให้แน่ใจว่าคุณได้ติดตั้งสิ่งต่อไปนี้:

  • Node.js (เวอร์ชัน 18.0.0 หรือสูงกว่า)

    • Node.js เป็นรันไทม์ JavaScript ที่ให้คุณเรียกใช้โค้ด JavaScript/TypeScript ภายนอกเว็บเบราว์เซอร์ จําเป็นต้องเรียกใช้สคริปต์ตัวอย่างและจัดการแพ็คเกจผ่าน npm (Node Package Manager)
    • ดาวน์โหลดจาก: https://nodejs.org/
    • ตรวจสอบการติดตั้ง: node --version
  • Azure CLI ของ

    • Azure Command-Line Interface (CLI) เป็นเครื่องมือสําหรับจัดการทรัพยากร Azure จากบรรทัดคําสั่ง ในคู่มือนี้ จะใช้เพื่อตรวจสอบตัวตนของคุณเพื่อให้ตัวอย่างสามารถเข้าถึง Learn Platform API ในนามของคุณได้
    • ดาวน์โหลดจาก: https://learn.microsoft.com/cli/azure/install-azure-cli>
    • ตรวจสอบการติดตั้ง: az --version
  • บัญชี Azure

    • จําเป็นต้องมีบัญชี Azure ที่มีการสมัครใช้งานที่ใช้งานอยู่เพื่อรับรองความถูกต้องและเข้าถึง Microsoft Learn Platform API API ใช้ Microsoft Entra ID (เดิมคือ Azure Active Directory) สําหรับการรับรองความถูกต้อง ซึ่งต้องใช้ข้อมูลประจําตัว Azure ที่ถูกต้อง ไม่มีค่าใช้จ่ายในการดึงโทเค็นการรับรองความถูกต้องจากการสมัครใช้งาน Azure ของคุณ
    • คุณต้องมีการสมัครใช้งาน Azure ที่ใช้งานอยู่
    • ลงทะเบียนได้ที่: https://azure.microsoft.com/free/
  • Visual Studio Code (ไม่บังคับ)

    • Visual Studio Code (VS code) เป็นโปรแกรมแก้ไขโค้ดฟรีที่มีน้ําหนักเบาพร้อมเทอร์มินัลในตัว IntelliSense และรองรับ TypeScript แม้ว่าคุณจะสามารถใช้โปรแกรมแก้ไขข้อความและเทอร์มินัลใดก็ได้ แต่ Visual Studio Code จะมอบประสบการณ์ที่คล่องตัวสําหรับการเรียกใช้ตัวอย่างเหล่านี้
    • ดาวน์โหลดจาก: https://code.visualstudio.com/
    • ตรวจสอบการติดตั้ง: เปิด Visual Studio Code แล้วกด Ctrl+' เพื่อเปิดเทอร์มินัลในตัว

Note

คําสั่งทั้งหมดที่เขียนด้านล่างควรเรียกใช้ในเทอร์มินัล Git Bash คุณสามารถใช้เทอร์มินัลในตัวของ VS Code (กด Ctrl+'), Windows PowerShell หรือ Command Prompt

ตั้งค่าโครงการ

ทําตามขั้นตอนเหล่านี้เพื่อสร้างโครงการใหม่และติดตั้งการขึ้นต่อกันที่จําเป็น

  1. สร้างโฟลเดอร์ใหม่สําหรับโปรเจ็กต์ของคุณและไปที่โฟลเดอร์นั้น

    mkdir learn-api-examples
    cd learn-api-examples
    
  2. เริ่มต้นโปรเจ็กต์ Node.js ใหม่ด้วยการตั้งค่าเริ่มต้น -yแฟล็กจะยอมรับค่าดีฟอลต์ทั้งหมดโดยอัตโนมัติ

    npm init -y
    
  3. ติดตั้งแพ็คเกจ npm ที่จําเป็น (@azure/identity สําหรับการรับรอง tsx ความถูกต้อง เพื่อเรียกใช้ TypeScript โดยตรง typescript คอมไพเลอร์ และ @types/node สําหรับคําจํากัดความประเภท)

    npm install @azure/identity tsx typescript @types/node
    
  4. สร้างไฟล์ใหม่ที่เรียกว่า examples.ts และวางโค้ดด้านล่าง ซึ่งรวมถึงการรับรองความถูกต้องที่ใช้ประโยชน์จากข้อมูลประจําตัวเริ่มต้นของ Azure และตัวอย่างความสามารถของแค็ตตาล็อกหลายตัวอย่างที่พร้อมใช้งานผ่าน 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();
    
    

ตรวจสอบสิทธิ์และเรียกใช้ตัวอย่าง

ทําตามขั้นตอนเหล่านี้เพื่อรับรองความถูกต้องกับ Azure และเรียกใช้โค้ดตัวอย่าง

  1. ลงชื่อเข้าใช้ Azure CLI ขั้นตอนนี้จะเปิดหน้าต่างเบราว์เซอร์ที่คุณป้อนข้อมูลประจําตัว Azure ของคุณ

    az login
    
  2. หากคุณมีการสมัครใช้บริการหลายรายการ ให้ตั้งค่าการสมัครใช้งานที่ใช้งานอยู่ แทนที่ <your-subscription-name> ด้วยชื่อหรือรหัสการสมัครใช้งานของคุณ

    az account set --subscription "<your-subscription-name>"
    
  3. ยืนยันว่าข้อมูลเข้าสู่ระบบของคุณสามารถเข้าถึง Learn Platform API ได้

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

    หากสําเร็จ คุณจะเห็นการตอบกลับ JSON พร้อม accessToken ช่อง

  4. เรียกใช้ไฟล์ตัวอย่างโดยใช้ npx เพื่อเรียกใช้ tsx แพ็คเกจ

    npx tsx examples.ts
    
  5. (ไม่บังคับ) บันทึกผลลัพธ์ไปยังไฟล์โดยใช้การเปลี่ยนเส้นทางเอาต์พุต

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

ล้างแหล่งข้อมูล

ถ้าคุณไม่ต้องการทรัพยากรที่สร้างขึ้นในการเริ่มต้นใช้งานด่วนนี้อีกต่อไป

  1. ลบโฟลเดอร์โครงการและเนื้อหาทั้งหมดในโฟลเดอร์

    cd ..
    rm -rf learn-api-examples
    

    บน Windows PowerShell ให้ใช้:

    cd ..
    Remove-Item -Recurse -Force learn-api-examples
    
  2. (ไม่บังคับ) ลงชื่อออกจาก Azure CLI เพื่อลบข้อมูลประจําตัวที่แคชไว้

    az logout
    

Note

การเริ่มต้นใช้งานด่วนนี้ไม่ได้สร้างทรัพยากร Azure ใดๆ ที่มีค่าใช้จ่าย การเรียกใช้ API จะใช้ข้อมูลประจําตัว Azure ที่มีอยู่ของคุณสําหรับการรับรองความถูกต้องเท่านั้น