Vue 3 + FetchでREST APIを呼び出す方法
REST APIの仕組みがわかったら、次は実際に呼び出してデータを使ってみましょう!この記事では、Vue 3 と Fetch API を使って、外部のREST APIからデータを取得・表示する方法を解説します。
目次
前提環境
- 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での実装ステップ
-
ref
で状態(データ)を定義 -
onMounted()
で初回読み込み時にデータ取得 - テンプレートに表示
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
のオプションを使えば対応可能