0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue 3 + FetchでREST APIを呼び出す方法

Posted at

Vue 3 + FetchでREST APIを呼び出す方法

REST APIの仕組みがわかったら、次は実際に呼び出してデータを使ってみましょう!この記事では、Vue 3 と Fetch API を使って、外部のREST APIからデータを取得・表示する方法を解説します。


目次

  1. 前提環境
  2. Fetch APIの基本
  3. Vueでの実装ステップ
  4. GETリクエストの例
  5. POSTリクエストの例
  6. エラーハンドリング
  7. まとめ

前提環境

  • Vue 3 プロジェクトが作成済み(ViteやVue CLIでOK)
  • Composition API(<script setup>)を使用

Fetch APIの基本

JavaScript標準の fetch() 関数を使うことで、外部APIと通信できます。

fetch('https://api.example.com/users')
  .then(response => response.json())
  .then(data => console.log(data));
  • .json() でレスポンスをJSON形式として取得します
  • 非同期なので async/await を使うのが主流です

Vueでの実装ステップ

  1. ref で状態(データ)を定義
  2. onMounted() で初回読み込み時にデータ取得
  3. テンプレートに表示

GETリクエストの例

<script setup>
import { ref, onMounted } from 'vue';

const users = ref([]);

onMounted(async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  users.value = await res.json();
});
</script>

<template>
  <h2>ユーザー一覧</h2>
  <ul>
    <li v-for="user in users" :key="user.id">
      {{ user.name }} - {{ user.email }}
    </li>
  </ul>
</template>

無料のモックAPIサービス JSONPlaceholder を使用しています。


POSTリクエストの例

const createUser = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      name: 'New User',
      email: 'new@example.com'
    })
  });

  const data = await res.json();
  console.log('作成されたユーザー:', data);
};
  • Content-Type: application/json を忘れずに
  • body は JSON 文字列で送信

エラーハンドリング

try {
  const res = await fetch(url);
  if (!res.ok) throw new Error('APIエラー');
  const data = await res.json();
} catch (error) {
  console.error('通信エラー:', error);
}
  • res.ok で HTTP ステータスチェック
  • ネットワークエラーも try-catch で対応

まとめ

  • fetch() を使って簡単にAPIと通信できる
  • onMounted()ref を使えばVueで非同期表示も簡単
  • POST/PUT/DELETEも fetch のオプションを使えば対応可能
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?