使用 Drupal REST API 新增文章範例
2025-05-09
標籤: Drupal API
廣告
                
                
                
            以下是使用 Drupal REST API 搭配 HTTP Basic Authentication 新增文章的詳細範例。假設你已啟用必要的模組並配置好權限。
環境準備
- 啟用模組:
- 確保已啟用 rest、serialization和basic_auth模組:bash drush en rest serialization basic_auth -y
- 配置 REST 資源:
- 編輯 sites/default/services.yml,確保 REST API 支援節點操作,或者創建一個配置文件(如rest.resource.node.yml)啟用節點資源。
- 範例配置:
     yaml langcode: en status: true dependencies: module: - basic_auth - node - serialization id: node plugin_id: entity:node granularity: resource configuration: methods: - GET - POST - PATCH - DELETE formats: - json authentication: - basic_auth
- 權限設置:
- 授予用戶「創建 article 內容類型」和「訪問 RESTful 資源」權限。
- 在 Drupal 管理介面:管理 > 人員 > 權限。
API 請求範例
以下是使用 cURL 透過 REST API 新增一篇「文章」(article)類型節點的範例,使用 HTTP Basic Authentication 進行認證。
cURL 命令
curl --request POST \
  --url 'http://example.com/entity/node?_format=json' \
  --header 'Content-Type: application/json' \
  --header 'Authorization: Basic YWRtaW46cGFzc3dvcmQ=' \
  --data '{
    "type": [{"target_id": "article"}],
    "title": [{"value": "My New Article"}],
    "body": [{"value": "This is the content of my article.", "format": "basic_html"}]
  }'
說明
- URL:http://example.com/entity/node?_format=json
- 指向節點實體端點,指定 JSON 格式。
- Authorization Header:
- YWRtaW46cGFzc3dvcmQ=是- admin:password的 Base64 編碼。
- 你需要將 admin:password替換為你的用戶名和密碼,並使用工具(如echo -n 'admin:password' | base64)生成 Base64 編碼。
- Payload:
- type:指定內容類型為- article。
- title:文章標題。
- body:文章內容,指定格式為- basic_html(可根據站點配置調整)。
- Content-Type:必須設為 application/json。
成功回應
如果請求成功,Drupal 會返回新創建節點的詳細資訊,HTTP 狀態碼為 201 Created:
{
  "nid": [{"value": 1}],
  "uuid": [{"value": "123e4567-e89b-12d3-a456-426614174000"}],
  "type": [{"target_id": "article"}],
  "title": [{"value": "My New Article"}],
  "body": [{"value": "This is the content of my article.", "format": "basic_html"}],
  ...
}
錯誤處理
- 401 Unauthorized:認證失敗,檢查用戶名/密碼或 Base64 編碼。
- 403 Forbidden:用戶缺少創建文章的權限,檢查權限設置。
- 422 Unprocessable Entity:請求格式錯誤,檢查 JSON 結構或欄位值。
使用 Postman 測試
- 打開 Postman,創建新請求:
- 方法:POST
- URL:http://example.com/entity/node?_format=json
- 設置 Headers:
- Content-Type: application/json
- Authorization: Basic <Base64 編碼的用戶名:密碼>
- 設置 Body(選擇 raw和JSON):json { "type": [{"target_id": "article"}], "title": [{"value": "My New Article"}], "body": [{"value": "This is the content of my article.", "format": "basic_html"}] }
- 發送請求並檢查回應。
注意事項
- 安全性:使用 HTTPS 保護 API 請求,避免密碼洩露。
- 認證:HTTP Basic Authentication 不適合公開 API,考慮使用 OAuth 或 JWT 進行生產環境部署。
- 欄位驗證:確保 article內容類型支援指定的欄位(如body),否則需調整 JSON 結構。
- 緩存:新增節點後,可能需清除緩存以查看更新:
  bash drush cr
進一步學習
- 參考 Drupal REST API 文檔。
- 測試其他操作(如更新 PATCH或刪除DELETE)。
- 探索 Drupal 的 HAL+JSON 格式以支援更複雜的關係數據。