Forem

Cover image for วิธีใช้ Azure APIs
Thanawat Wongchai
Thanawat Wongchai

Posted on • Originally published at apidog.com

วิธีใช้ Azure APIs

สรุปเนื้อหาสำคัญ (TL;DR)

Azure APIs ช่วยให้คุณเข้าถึงบริการคลาวด์ของ Microsoft ได้ผ่านโปรแกรม เช่น storage, compute, databases, AI ฯลฯ โดยใช้ Azure Active Directory (Entra ID) เพื่อยืนยันตัวตนและรับ access token จากนั้นเรียกใช้ REST endpoints สำหรับการทดสอบและจัดทำเอกสาร ควรใช้ Apidog เพื่อบันทึกการเรียกใช้ API ตรวจสอบ response ว่าตรงกับ schema หรือไม่ และแชร์ collection กับทีม

ทดลองใช้ Apidog วันนี้

บทนำ

Microsoft Azure มีบริการมากกว่า 200 รายการ โดยแต่ละบริการจะมี API เฉพาะ นักพัฒนาส่วนมากจะต้องใช้บริการอย่างน้อย 2-3 รายการ เช่น Azure Blob Storage สำหรับจัดเก็บไฟล์, Azure Functions สำหรับ serverless หรือ Azure OpenAI สำหรับ LLMs

แต่ปัญหาคือ เอกสาร Azure มีขนาดใหญ่และกระจัดกระจาย อาจเสียเวลานานในการค้นหา endpoint ที่ถูกต้อง ทำความเข้าใจ authentication และแก้ไขข้อผิดพลาด 401 Unauthorized

บทความนี้เน้นที่การใช้งาน API จริง ๆ ที่ใช้บ่อย (5-10 รายการ) โดยเน้นการยืนยันตัวตน ข้อผิดพลาดที่พบบ่อย และวิธีทดสอบการผสาน Azure ก่อน deploy

💡 หากคุณกำลังสร้างระบบโดยใช้ Azure APIs, Apidog จะช่วยออกแบบ ทดสอบ และจัดทำเอกสารการผสานเหล่านั้น เช่น บันทึก Azure API เป็น collection, กำหนด environment variable สำหรับ subscription ต่าง ๆ และตรวจสอบ response ตรงกับ schema ที่คาดไว้ ลดโอกาสเกิด config error ก่อน production

ทดสอบ Azure APIs ของคุณด้วย Apidog - ฟรี

เมื่อจบคู่มือนี้ คุณจะสามารถ:

  • ตั้งค่า Azure authentication ได้อย่างถูกต้อง (สาเหตุอันดับ 1 ของปัญหา)
  • เรียกใช้ Azure Storage, Compute และ AI APIs พร้อมตัวอย่างจริง
  • แก้ไขข้อผิดพลาด Azure API ที่พบได้บ่อย
  • ทดสอบและจัดทำเอกสารการผสาน Azure ของคุณด้วย Apidog

ปัญหาการยืนยันตัวตน (และวิธีแก้ไข)

ทุกครั้งที่เรียก Azure API ต้องมี authentication ถ้าทำผิด ทุกอย่างจะ fail จุดที่ dev ส่วนใหญ่ติดอยู่ที่นี่

ภาพแสดงขั้นตอนการยืนยันตัวตนของ Azure

Azure Active Directory / Microsoft Entra ID

Azure ใช้ OAuth 2.0 สำหรับ API authentication คุณจะต้องส่ง access token แทน user/pass

ขั้นตอน:

  1. ลงทะเบียนแอปใน Azure AD (Entra ID)
  2. รับ client ID และ client secret
  3. ขอ access token จาก Azure token endpoint
  4. นำ token ไปใช้ใน API request

ขั้นตอนที่ 1: ลงทะเบียนแอป

  • Azure Portal → Microsoft Entra ID → App registrations → New registration
  • ตั้งชื่อ เลือก “Accounts in this organizational directory only”
  • รับ Application (client) ID และ Directory (tenant) ID

ขั้นตอนที่ 2: สร้าง client secret

  • ไปที่ Certificates & secrets → New client secret
  • คัดลอก secret ทันที

ขั้นตอนที่ 3: กำหนดสิทธิ์

  • API permissions → Add a permission
    • Azure Storage: “Azure Storage” → “user_impersonation”
    • Azure Management APIs: “Azure Service Management” → “user_impersonation”

ขั้นตอนที่ 4: รับ access token

curl -X POST "https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "client_id={client-id}" \
  -d "client_secret={client-secret}" \
  -d "scope=https://storage.azure.com/.default" \
  -d "grant_type=client_credentials"
Enter fullscreen mode Exit fullscreen mode

Response:

{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs...",
  "expires_in": 3599,
  "token_type": "Bearer"
}
Enter fullscreen mode Exit fullscreen mode

ขั้นตอนที่ 5: ใช้ token

curl -X GET "https://youraccount.blob.core.windows.net/container?restype=container&comp=list" \
  -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIs..." \
  -H "x-ms-version: 2023-01-03"
Enter fullscreen mode Exit fullscreen mode

การใช้ Azure SDK แทน HTTP ดิบ

สำหรับ production code แนะนำให้ใช้ Azure SDK เพราะจัดการ token refresh, retry, serialization ให้

import { DefaultAzureCredential } from '@azure/identity'
import { BlobServiceClient } from '@azure/storage-blob'

const credential = new DefaultAzureCredential()
const blobServiceClient = new BlobServiceClient(
  'https://youraccount.blob.core.windows.net',
  credential
)

for await (const container of blobServiceClient.listContainers()) {
  console.log(container.name)
}
Enter fullscreen mode Exit fullscreen mode

แต่สำหรับ testing, debug, documentation ควรเข้าใจ HTTP request โดยตรง ซึ่ง Apidog ช่วยได้

Azure Storage APIs

Azure Storage คือบริการหลัก ใช้บ่อยที่สุด ประกอบด้วย:

  • Blob Storage: ไฟล์, รูปภาพ, สำรองข้อมูล
  • Queue Storage: คิวข้อความ
  • Table Storage: NoSQL key-value store
  • File Storage: SMB file share

Blob Storage API

แสดงรายการ container:

GET https://{account}.blob.core.windows.net/?comp=list
Authorization: Bearer {token}
x-ms-version: 2023-01-03
Enter fullscreen mode Exit fullscreen mode

สร้าง container:

PUT https://{account}.blob.core.windows.net/{container}?restype=container
Authorization: Bearer {token}
x-ms-version: 2023-01-03
Enter fullscreen mode Exit fullscreen mode

อัปโหลด blob:

PUT https://{account}.blob.core.windows.net/{container}/{blob}
Authorization: Bearer {token}
x-ms-version: 2023-01-03
Content-Type: text/plain

Hello, Azure Blob Storage!
Enter fullscreen mode Exit fullscreen mode

ดาวน์โหลด blob:

GET https://{account}.blob.core.windows.net/{container}/{blob}
Authorization: Bearer {token}
x-ms-version: 2023-01-03
Enter fullscreen mode Exit fullscreen mode

การทดสอบด้วย Apidog

Azure Storage APIs ต้องใช้ header เฉพาะ (เช่น x-ms-version) และรูปแบบ auth ถูกต้อง Apidog ช่วยในเรื่อง:

  1. บันทึก request เป็น reusable
  2. ใช้ environment variable แทน account name/token
  3. ตรวจสอบ response ให้ตรง schema

ออกแบบและทดสอบ Azure Storage APIs ด้วย Apidog

Azure Compute APIs

Azure Compute ใช้จัดการ VM, container, และ serverless functions

Azure Functions API

แสดงรายการ functions ใน function app:

GET https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{app-name}/functions?api-version=2023-01-01
Authorization: Bearer {management-token}
Enter fullscreen mode Exit fullscreen mode

เรียกใช้ function (HTTP trigger):

POST https://{app-name}.azurewebsites.net/api/{function-name}
Content-Type: application/json

{
  "name": "Azure",
  "message": "Hello from API"
}
Enter fullscreen mode Exit fullscreen mode

รับ function key:

POST https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{rg}/providers/Microsoft.Web/sites/{app-name}/functions/{function-name}/listKeys?api-version=2023-01-01
Authorization: Bearer {management-token}
Enter fullscreen mode Exit fullscreen mode

Virtual Machines API

แสดงรายการ VM:

GET https://management.azure.com/subscriptions/{subscription-id}/providers/Microsoft.Compute/virtualMachines?api-version=2023-07-01
Authorization: Bearer {management-token}
Enter fullscreen mode Exit fullscreen mode

เริ่ม VM:

POST https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachines/{vm-name}/start?api-version=2023-07-01
Authorization: Bearer {management-token}
Enter fullscreen mode Exit fullscreen mode

หยุด VM:

POST https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachines/{vm-name}/powerOff?api-version=2023-07-01
Authorization: Bearer {management-token}
Enter fullscreen mode Exit fullscreen mode

Azure AI Services APIs

Azure มีบริการ OpenAI และ cognitive services เช่น vision, speech, language

Azure OpenAI API

ขอ completion:

POST https://{resource-name}.openai.azure.com/openai/deployments/{deployment-id}/chat/completions?api-version=2024-02-15-preview
api-key: {your-api-key}
Content-Type: application/json

{
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is Azure?"}
  ],
  "max_tokens": 500
}
Enter fullscreen mode Exit fullscreen mode

แสดงรายการ deployment:

GET https://{resource-name}.openai.azure.com/openai/deployments?api-version=2024-02-15-preview
api-key: {your-api-key}
Enter fullscreen mode Exit fullscreen mode

Cognitive Services API

Text Analytics - ตรวจสอบความรู้สึก:

POST https://{resource-name}.cognitiveservices.azure.com/text/analytics/v3.1/sentiment
Ocp-Apim-Subscription-Key: {subscription-key}
Content-Type: application/json

{
  "documents": [
    {
      "id": "1",
      "language": "en",
      "text": "I love Azure APIs. They work great!"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Computer Vision - วิเคราะห์ภาพ:

POST https://{resource-name}.cognitiveservices.azure.com/vision/v3.2/analyze?visualFeatures=Description,Tags
Ocp-Apim-Subscription-Key: {subscription-key}
Content-Type: application/octet-stream

[binary image data]
Enter fullscreen mode Exit fullscreen mode

การทดสอบ Azure APIs ด้วย Apidog

Azure APIs มี authentication ซับซ้อนและต้องใช้ header ที่แม่นยำ การทดสอบด้วย curl ล้วนเสี่ยงผิดพลาด Apidog ช่วยดังนี้

1. การจัดการ Environment

Azure APIs มีหลาย endpoint:

  • management.azure.com (control plane)
  • {account}.blob.core.windows.net (storage)
  • {resource}.openai.azure.com (AI)

ตั้งค่าตัวแปร environment ใน Apidog:

# Development
MANAGEMENT_TOKEN: eyJ0eXAiOiJKV1Qi...
STORAGE_ACCOUNT: devstorage
OPENAI_RESOURCE: dev-openai

# Production
MANAGEMENT_TOKEN: eyJ0eXAiOiJKV1Qi...
STORAGE_ACCOUNT: prodstorage
OPENAI_RESOURCE: prod-openai
Enter fullscreen mode Exit fullscreen mode

2. สคริปต์ก่อน request สำหรับ refresh token

Token Azure หมดอายุภายใน 1 ชั่วโมง ใช้ pre-request script:

// ตรวจสอบ token หมดอายุหรือยัง
const tokenExpiry = pm.environment.get('token_expiry')
const now = Date.now() / 1000

if (!tokenExpiry || now >= tokenExpiry) {
  // ขอ token ใหม่
  const response = await pm.sendRequest({
    url: 'https://login.microsoftonline.com/' + pm.environment.get('tenant_id') + '/oauth2/v2.0/token',
    method: 'POST',
    header: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: {
      mode: 'urlencoded',
      urlencoded: [
        { key: 'client_id', value: pm.environment.get('client_id') },
        { key: 'client_secret', value: pm.environment.get('client_secret') },
        { key: 'scope', value: 'https://management.azure.com/.default' },
        { key: 'grant_type', value: 'client_credentials' }
      ]
    }
  })

  const data = response.json()
  pm.environment.set('management_token', data.access_token)
  pm.environment.set('token_expiry', now + data.expires_in)
}
Enter fullscreen mode Exit fullscreen mode

3. การตรวจสอบ response

ตรวจสอบว่า Azure response ตรง schema ที่ต้องการ:

// ตรวจสอบว่ามี containers ใน response
pm.test('Response has containers', () => {
  const xml = pm.response.text()
  pm.expect(xml).to.include('<Containers>')
  pm.expect(xml).to.include('<Container>')
})

// ตรวจสอบว่าเป็น XML
pm.test('Response is valid XML', () => {
  pm.response.to.be.ok
  pm.response.to.have.header('Content-Type', 'application/xml')
})
Enter fullscreen mode Exit fullscreen mode

เริ่มทดสอบ Azure APIs ด้วย Apidog - ฟรี

ข้อผิดพลาดทั่วไปและวิธีแก้ไข

401 Unauthorized

สาเหตุ: token ไม่ถูกต้องหรือหมดอายุ

วิธีแก้ไข:

  1. ตรวจสอบ token หมดอายุหรือไม่ (expires_in)
  2. ตรวจสอบ scope ตรงกับ API หรือไม่
  3. ตรวจสอบ app registration มี permission ถูกต้อง

403 Forbidden

สาเหตุ: token ถูกต้องแต่ไม่มีสิทธิ์

วิธีแก้ไข:

  1. ไปที่ resource ใน Azure Portal
  2. ตรวจสอบ Access control (IAM)
  3. เพิ่ม role assignment ให้ service principal ของแอป

404 Not Found

สาเหตุ: endpoint ผิด หรือ resource ไม่มี

วิธีแก้ไข:

  1. ตรวจสอบ resource name ใน URL
  2. ตรวจสอบ API version ใน query string
  3. ตรวจสอบ resource อยู่ใน resource group ที่ถูกต้อง

429 Too Many Requests

สาเหตุ: เกิน rate limit

วิธีแก้ไข:

  1. ใช้ exponential backoff
  2. ตรวจสอบ header x-ms-ratelimit-remaining
  3. รวม request เป็น batch ถ้าเป็นไปได้
async function callWithRetry(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn()
    } catch (error) {
      if (error.statusCode === 429) {
        const delay = Math.pow(2, i) * 1000
        await new Promise(resolve => setTimeout(resolve, delay))
      } else {
        throw error
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

ทางเลือกและการเปรียบเทียบ

คุณสมบัติ Azure APIs AWS APIs GCP APIs
การยืนยันตัวตน Azure AD (OAuth 2.0) IAM (Sig v4) OAuth 2.0
คุณภาพ SDK ยอดเยี่ยม ยอดเยี่ยม ยอดเยี่ยม
เอกสารประกอบ ครอบคลุมแต่กระจัดกระจาย เฉพาะบริการ เฉพาะบริการ
การจำกัดอัตรา ต่อการสมัครสมาชิก ต่อบริการ ต่อโปรเจกต์
ระดับฟรี 12 เดือน + ฟรีตลอดไป 12 เดือน ฟรีตลอดไป + เครดิต

การยืนยันตัวตนของ Azure ซับซ้อนกว่า AWS (Sig v4) แต่ผสานกับระบบองค์กรได้ดี

กรณีการใช้งานจริง

แพลตฟอร์มอีคอมเมิร์ซ: ใช้ Azure Blob Storage เก็บรูปสินค้า, Azure Functions สำหรับ webhooks, Azure OpenAI สำหรับคำอธิบายสินค้า ทดสอบ API ทุกตัวใน Apidog ก่อน deploy

Healthcare SaaS: ใช้ Cosmos DB สำหรับข้อมูลผู้ป่วย, Azure Functions สำหรับ HL7, Azure Key Vault สำหรับ secrets ทดสอบ API ตรวจสอบ schema response ทุกครั้ง (HIPAA compliance)

AI startup: ใช้ Azure OpenAI สำหรับ LLM, Azure Storage เก็บ training data, Azure Container Apps สำหรับ deploy ใช้ Apidog mock Azure APIs ตอน dev local

สรุป

สิ่งที่คุณควรเข้าใจ:

  • Azure authentication ใช้ OAuth 2.0 token จาก Azure AD (Entra ID)
  • Storage APIs ต้องใช้ header x-ms-version และ Bearer token ที่ถูกต้อง
  • Compute APIs ใช้ Azure Resource Manager endpoint
  • AI services ใช้ API key หรือ AAD token แล้วแต่บริการ
  • ทดสอบและจัดทำเอกสาร Azure API integration ของคุณด้วย Apidog

ขั้นตอนถัดไป:

  1. ลงทะเบียนแอปใน Azure AD และรับ credentials
  2. ขอ access token ด้วย client credentials flow
  3. เรียก Azure Storage API ครั้งแรกของคุณ
  4. บันทึก request ใน Apidog เป็น reusable
  5. สร้าง collection สำหรับ Azure APIs ของโปรเจกต์

ทดสอบ Azure APIs ด้วย Apidog - ฟรี

คำถามที่พบบ่อย (FAQ)

Azure AD ต่างกับ Microsoft Entra ID อย่างไร?

เป็นบริการเดียวกัน Microsoft เปลี่ยนชื่อ Azure Active Directory เป็น Microsoft Entra ID ในปี 2023 เอกสารจะเจอสองชื่อ ใช้ Entra ID สำหรับเอกสารใหม่

รับ API key สำหรับ Azure OpenAI ได้อย่างไร?

Azure Portal → Azure OpenAI → ทรัพยากร → Keys and Endpoint จะเห็น key 2 อัน ใช้อันไหนก็ได้ ควร rotate key เป็นระยะ ต้องมี subscription และ deployment ก่อน

ต่างกันอย่างไรระหว่าง management.azure.com กับ service-specific endpoints?

management.azure.com คือ Resource Manager ใช้ CRUD บน resource (เช่น สร้าง VM)

Service-specific endpoints เหมาะสำหรับใช้งาน resource (เช่น อัปโหลดไฟล์) ต้องใช้ token คนละแบบ

Azure access token มีอายุกี่นาน?

ประมาณ 1 ชั่วโมง (3600 วินาที) ดู field expires_in จาก token response ควร refresh ก่อนหมดอายุ ไม่ควรขอ token ใหม่ทุกครั้งที่เรียก API

ใช้ managed identities แทน client secret ได้หรือไม่?

ได้ แนะนำสำหรับ workload production ใน Azure (VM, Functions, AKS) สำหรับ local dev ใช้ Azure CLI (az login) หรือ env + client secret

API ทำงานใน Postman แต่ fail ในโค้ด?

เช็ค header ทั้งชื่อและรูปแบบ (case-sensitive) Postman อาจแอบเพิ่ม header บางตัว เปรียบเทียบ raw request ด้วย Fiddler หรือเช็คใน Apidog

สามารถทดสอบ Azure APIs ในเครื่องโดยไม่มี subscription ได้หรือไม่?

ไม่ 100% แต่ใช้ emulator ได้:

  • Azurite (Azure Storage)
  • Azure Functions Core Tools (Functions)
  • Apidog mock Azure API response

วิธีจัดการ error ของ Azure API ที่เหมาะสม?

Azure จะคืน JSON error ที่มีรายละเอียด ให้วิเคราะห์ error.code กับ error.message ตัวอย่างเช่น:

  • AuthenticationFailed - ตรวจสอบ token
  • ResourceNotFound - ตรวจสอบ resource name
  • OperationNotAllowed - ตรวจสอบ subscription limits

Top comments (0)