Forem

Cover image for Hướng Dẫn Sử Dụng Azure APIs Hiệu Quả
Sebastian Petrus
Sebastian Petrus

Posted on • Originally published at apidog.com

Hướng Dẫn Sử Dụng Azure APIs Hiệu Quả

TL;DR (Tóm tắt nhanh)

Các API của Azure cung cấp quyền truy cập theo lập trình tới các dịch vụ đám mây của Microsoft như lưu trữ, điện toán, cơ sở dữ liệu, AI, và nhiều hơn nữa. Để sử dụng, bạn xác thực qua Azure Active Directory (Entra ID), lấy access token và gọi các endpoint REST. Để kiểm thử và tài liệu hóa, hãy dùng Apidog để lưu các request, xác thực response theo schema và chia sẻ collection với nhóm của bạn.

Thử Apidog ngay hôm nay

Giới thiệu

Microsoft Azure có hơn 200 dịch vụ, mỗi dịch vụ đều có API riêng. Phần lớn developer sẽ dùng một số dịch vụ phổ biến như Azure Blob Storage (lưu trữ tệp), Azure Functions (serverless), hoặc Azure OpenAI (LLM).

Vấn đề là tài liệu Azure rất nhiều và phân tán, khiến việc tìm đúng endpoint, xác thực, và debug lỗi 401 Unauthorized tốn nhiều thời gian.

Bài viết này tập trung vào các API bạn thực sự cần: khoảng 5-10 dịch vụ chiếm phần lớn các ứng dụng thực tế. Bạn sẽ học các mẫu xác thực, lỗi thường gặp và cách kiểm thử tích hợp Azure trước khi triển khai.

💡 Nếu bạn đang xây dựng ứng dụng dựa trên API Azure, Apidog sẽ giúp bạn thiết kế, kiểm thử và tài liệu hóa các tích hợp. Bạn có thể lưu các cuộc gọi API Azure dưới dạng collection, thêm biến môi trường cho nhiều subscription và xác thực response theo schema mong đợi. Điều này giúp phát hiện lỗi cấu hình trước khi lên production.

Kiểm thử API Azure của bạn với Apidog - miễn phí

Sau khi hoàn thành bài này, bạn sẽ biết cách:

  • Thiết lập xác thực Azure đúng cách (lỗi thường gặp số 1)
  • Gọi API Azure Storage, Compute, AI với ví dụ thực tế
  • Debug lỗi API Azure phổ biến
  • Kiểm thử và tài liệu hóa tích hợp Azure với Apidog

Vấn đề xác thực (và cách giải quyết)

Mọi API Azure đều yêu cầu xác thực. Nếu bước này sai, các bước tiếp theo đều thất bại. Đây là điểm mà nhiều developer gặp khó.

Hình ảnh minh họa sơ đồ luồng xác thực của Azure.

Azure Active Directory / Microsoft Entra ID

Azure dùng OAuth 2.0 cho xác thực API. Bạn không gửi username/password mà dùng access token để chứng minh danh tính và quyền hạn.

Quy trình tổng quát:

  1. Đăng ký một ứng dụng trong Azure AD (Entra ID)
  2. Lấy client ID và client secret
  3. Lấy access token từ endpoint token của Azure
  4. Đưa token này vào các API call

Bước 1: Đăng ký ứng dụng

Vào Azure Portal → Microsoft Entra ID → App registrations → New registration. Đặt tên, chọn "Accounts in this organizational directory only" nếu là app nội bộ, rồi đăng ký. Bạn sẽ có:

  • Application (client) ID: 12345678-1234-1234-1234-123456789abc
  • Directory (tenant) ID: 87654321-4321-4321-4321-cba987654321

Bước 2: Tạo client secret

Vào Certificates & secrets → New client secret. Sao chép giá trị bí mật ngay lập tức.

  • Client secret: abc123~DEF456-ghi789

Bước 3: Gán quyền

Vào API permissions → Add a permission.

  • Với Storage: chọn “Azure Storage” → “user_impersonation”
  • Với Management APIs: chọn “Azure Service Management” → “user_impersonation”

Bước 4: Lấy 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

Phản hồi:

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

Bước 5: Sử dụng access 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

Sử dụng Azure SDK thay vì HTTP thô

Trong production code, nên dùng Azure SDK để tự động làm mới token, retry và serialize:

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
)

// Liệt kê các containers
for await (const container of blobServiceClient.listContainers()) {
  console.log(container.name)
}
Enter fullscreen mode Exit fullscreen mode

Nhưng để kiểm thử, debug và tài liệu hóa, bạn cần hiểu HTTP thô. Đó là lúc Apidog phát huy tác dụng.

API của Azure Storage

Azure Storage là dịch vụ phổ biến nhất, gồm:

  • Blob Storage: Tệp, ảnh, backup
  • Queue Storage: Hàng đợi tin nhắn
  • Table Storage: NoSQL key-value
  • File Storage: Chia sẻ file SMB

API của Blob Storage

Liệt kê containers:

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

Tạo 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

Tải lên 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

Tải xuống 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

Kiểm thử với Apidog

API Azure Storage yêu cầu các header đặc biệt (x-ms-version, Authorization). Apidog hỗ trợ:

  1. Lưu request tái sử dụng
  2. Dùng biến môi trường cho account/token
  3. Xác thực response với schema mong đợi

Thiết kế và kiểm thử API Azure Storage với Apidog.

API của Azure Compute

Azure Compute giúp quản lý VM, container, serverless.

API của Azure Functions

REST API cho quản lý function app.

Liệt kê functions:

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

Kích hoạt 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

Lấy function keys:

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

API của Virtual Machines

Liệt kê 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

Khởi động 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

Dừng 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

API của Dịch vụ AI của Azure

Azure cung cấp các mô hình OpenAI và dịch vụ nhận diện thị giác, giọng nói, ngôn ngữ.

API của Azure OpenAI

Lấy completions:

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

Liệt kê deployments:

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

API của Cognitive Services

Text Analytics - Phân tích cảm xúc:

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 - Phân tích hình ảnh:

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

Kiểm thử API Azure với Apidog

Các API Azure có xác thực phức tạp và cần header chuẩn xác. Kiểm thử thủ công với curl dễ sai sót. Apidog giúp:

1. Quản lý môi trường

API Azure phân tán nhiều endpoint:

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

Tạo môi trường trong Apidog cho từng loại:

# 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. Kịch bản pre-request để làm mới token

Token Azure hết hạn sau 1 giờ. Thêm script pre-request:

// Kiểm tra token hết hạn
const tokenExpiry = pm.environment.get('token_expiry')
const now = Date.now() / 1000

if (!tokenExpiry || now >= tokenExpiry) {
  // Yêu cầu token mới
  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. Xác thực phản hồi

Kiểm tra response của Azure có đúng định dạng mong đợi:

// Check danh sách blob trả về đúng cấu trúc
pm.test('Response has containers', () => {
  const xml = pm.response.text()
  pm.expect(xml).to.include('<Containers>')
  pm.expect(xml).to.include('<Container>')
})

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

Bắt đầu kiểm thử API Azure với Apidog - miễn phí

Các lỗi thường gặp và cách khắc phục

401 Unauthorized

Nguyên nhân: Token không hợp lệ hoặc đã hết hạn.

Khắc phục:

  1. Kiểm tra token chưa hết hạn (expires_in ~ 3600 giây)
  2. Scope phải đúng với API gọi
  3. Ứng dụng phải có quyền phù hợp

403 Forbidden

Nguyên nhân: Token hợp lệ nhưng thiếu quyền.

Khắc phục:

  1. Truy cập resource trong Azure Portal
  2. Kiểm tra Access control (IAM)
  3. Thêm role assignment cho service principal

404 Not Found

Nguyên nhân: Sai endpoint hoặc tài nguyên không tồn tại.

Khắc phục:

  1. Kiểm tra tên resource trong URL
  2. Đúng API version trong query string
  3. Tài nguyên có trong đúng resource group

429 Too Many Requests

Nguyên nhân: Vượt quá rate limit của Azure.

Khắc phục:

  1. Dùng exponential backoff
  2. Kiểm tra header x-ms-ratelimit-remaining
  3. Batching request nếu có thể
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

Các lựa chọn thay thế và so sánh

Tính năng API của Azure API của AWS API của GCP
Xác thực Azure AD (OAuth 2.0) IAM (Sig v4) OAuth 2.0
Chất lượng SDK Xuất sắc Xuất sắc Xuất sắc
Tài liệu Toàn diện, rải rác Theo dịch vụ Theo dịch vụ
Giới hạn tỉ lệ Theo subscription Theo dịch vụ Theo dự án
Bậc miễn phí 12 tháng + luôn free 12 tháng Luôn free + credit

Xác thực của Azure phức tạp hơn phương pháp dựa trên chữ ký của AWS nhưng tích hợp tốt với hệ thống danh tính doanh nghiệp.

Các trường hợp sử dụng thực tế

Nền tảng thương mại điện tử: Sử dụng Azure Blob Storage cho ảnh sản phẩm, Azure Functions cho webhook xử lý đơn hàng, Azure OpenAI cho mô tả sản phẩm. Kiểm thử toàn bộ API call bằng Apidog trước khi triển khai.

SaaS chăm sóc sức khỏe: Hệ thống hồ sơ bệnh nhân dùng Azure Cosmos DB, Azure Functions (xử lý HL7), Azure Key Vault cho secrets. Kiểm thử API để đảm bảo tuân thủ HIPAA bằng cách validate mọi schema response.

Startup AI: Sử dụng Azure OpenAI cho LLM, Azure Storage cho dữ liệu train, Azure Container Apps để deploy. Apidog dùng để mock API Azure trong phát triển local.

Tổng kết

Những gì bạn đã học:

  • Xác thực Azure dùng OAuth 2.0 token từ Azure AD (Entra ID)
  • API Storage cần header x-ms-version và Bearer token đúng chuẩn
  • API Compute dùng endpoint Azure Resource Manager
  • Dịch vụ AI dùng API key hoặc token AAD tùy dịch vụ
  • Kiểm thử, tài liệu hóa tích hợp Azure với Apidog

Các bước tiếp theo:

  1. Đăng ký app trong Azure AD, lấy credential
  2. Lấy access token qua client credentials flow
  3. Gọi API Azure Storage đầu tiên
  4. Lưu request đó thành reusable request trong Apidog
  5. Xây dựng collection cho API Azure dự án của bạn

Kiểm thử API Azure với Apidog - miễn phí

FAQ (Các câu hỏi thường gặp)

Sự khác biệt giữa Azure AD và Microsoft Entra ID là gì?

Chúng là một. Azure Active Directory đã đổi tên thành Microsoft Entra ID từ 2023. Dùng Entra ID cho tài liệu mới, nhưng Azure AD vẫn còn phổ biến.

Cách lấy API key cho Azure OpenAI?

Vào Azure Portal → Azure OpenAI → resource → Keys and Endpoint. Có 2 key, dùng key nào cũng được. Thường xuyên rotate key để đảm bảo security. Khác với OpenAI public API, Azure OpenAI cần đăng ký Azure và resource deployment.

Khác biệt giữa management.azure.com và các endpoint dịch vụ?

management.azure.com: endpoint của Azure Resource Manager, thao tác CRUD resource (tạo VM, xóa storage account).

Endpoint dịch vụ ({account}.blob.core.windows.net, {resource}.openai.azure.com): dùng để truy cập tài nguyên (tải tệp, tạo văn bản). Cần token khác nhau cho mỗi loại.

Access token Azure tồn tại bao lâu?

Thường là 1 giờ (3600s). Nên refresh token trước khi hết hạn, dùng trường expires_in trong response. Không nên request token mới cho mỗi API call.

Có dùng managed identities thay client secret được không?

Có, nên dùng cho production workload chạy trên Azure. Managed identities không cần lưu trữ client secret, hỗ trợ VM, Functions, Container Apps, AKS. Dev local có thể dùng Azure CLI (az login) hoặc env vars với client secret.

Tại sao API call chạy được trên Postman nhưng fail trong code?

Kiểm tra headers. Azure API phân biệt hoa thường header name. Postman có thể tự thêm header. So sánh raw request giữa Postman và code bằng Fiddler hoặc request inspector của Apidog.

Cách kiểm thử API Azure local không cần subscription?

Không thể test hoàn toàn nếu không có subscription, nhưng có thể dùng local emulator:

  • Azurite cho Azure Storage
  • Azure Functions Core Tools cho Functions
  • Apidog để mock API Azure

Xử lý lỗi API Azure thế nào?

Azure trả JSON lỗi chi tiết. Xử lý trường error.code, error.message. Một số mã phổ biến:

  • AuthenticationFailed – kiểm tra access token
  • ResourceNotFound – kiểm tra resource name
  • OperationNotAllowed – kiểm tra subscription limit

Tài nguyên bổ sung:

Top comments (0)