認証済みAPIのContent-TypeとAuthorizationの組み合わせ

認証済みAPIリクエストでContent-TypeとAuthorizationヘッダーを組み合わせます。Bearerトークン、APIキー、一般的なヘッダーの組み合わせを解説します。

Best Practices

詳細な説明

認証付きContent-Type

ほとんどのAPIリクエストにはContent-Typeヘッダーと認証ヘッダーの両方が必要です。これらの連携を理解することがAPI統合に不可欠です。

一般的なヘッダーの組み合わせ

Content-Type: application/json; charset=utf-8
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

認証ヘッダーのパターン

パターン ヘッダー形式 一般的な用途
Bearerトークン Authorization: Bearer <token> OAuth 2.0、JWT
APIキー(ヘッダー) X-API-Key: <key> REST API
Basic認証 Authorization: Basic <base64> シンプルな認証
APIキー(クエリ) ?api_key=<key> レガシーAPI

Bearerトークン + JSON

curl -X POST \
  -H "Content-Type: application/json; charset=utf-8" \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
  -d '{"title":"New Post","content":"Hello world"}' \
  https://api.example.com/posts

fetch()の例

fetch("https://api.example.com/posts", {
  method: "POST",
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": "Bearer " + accessToken
  },
  body: JSON.stringify({ title: "New Post" })
});

axiosの例

axios.post("https://api.example.com/posts", {
  title: "New Post"
}, {
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    "Authorization": `Bearer ${accessToken}`
  }
});

OAuthトークンリクエスト

トークンエンドポイントはJSONではなくURLエンコードフォームデータを使用します:

curl -X POST \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials&client_id=xxx&client_secret=yyy" \
  https://auth.example.com/oauth/token

ユースケース

認証済みAPIとの統合時のリファレンスとして使用します。正しいContent-TypeとAuthorizationヘッダーの組み合わせを理解することで、一般的な統合エラーを防止できます。

試してみる — Content-Type Header Builder

フルツールを開く