JavaScript Fetch 問題集
fetchをいっぱい使おうというだけの記事です
webブラウザのJSエンジンではできなかったので、node環境で実行してください🙇
▼周辺記事
🔰 初級編(4問)
Q1. JSONPlaceholderの投稿データを取得しよう
問題:
JSONPlaceholder API の /posts
エンドポイントに GET
リクエストを送り、最初の投稿のタイトルを console.log
で表示してください。
エンドポイント:
https://jsonplaceholder.typicode.com/posts
答え(クリックで表示)
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => console.log(data[0].title));
Q2. ユーザー情報を取得しよう
問題:
Random User Generator を使ってランダムなユーザーの名前を取得し、
「こんにちは、〇〇さん!」と console.log
で表示してください。
エンドポイント:
https://randomuser.me/api/
答え(クリックで表示)
fetch("https://randomuser.me/api/")
.then(response => response.json())
.then(data => console.log(`こんにちは、${data.results[0].name.first}さん!`));
Q3. 犬の画像を取得しよう
問題:
Dog CEO’s Dog API を使って、ランダムな犬の画像URLを取得し、
console.log
で表示してください。
エンドポイント:
https://dog.ceo/api/breeds/image/random
答え(クリックで表示)
fetch("https://dog.ceo/api/breeds/image/random")
.then(response => response.json())
.then(data => console.log(data.message));
Q4. 簡単なエラーハンドリング
問題:
JSONPlaceholder API の /invalid-endpoint
に fetch
を実行し、
エラーが発生した場合は "エラーが発生しました"
と console.log
で表示するコードを書いてください。
エンドポイント:
https://jsonplaceholder.typicode.com/invalid-endpoint
答え(クリックで表示)
fetch("https://jsonplaceholder.typicode.com/invalid-endpoint")
.then(response => {
if (!response.ok) {
throw new Error("エラーが発生しました");
}
return response.json();
})
.catch(error => console.log(error.message));
⚡ 中級編(2問)
Q5. 2つのAPIを並列で取得しよう
問題:
-
JSONPlaceholder API の
/users/1
でユーザー情報を取得 - Dog CEO’s Dog API でランダムな犬の画像を取得
この2つを 同時に 取得し、console.log
で結果を表示してください。(Promise.all
を使うと良いかも?)
エンドポイント:
https://jsonplaceholder.typicode.com/users/1
https://dog.ceo/api/breeds/image/random
答え(クリックで表示)
Promise.all([
fetch("https://jsonplaceholder.typicode.com/users/1").then(res => res.json()),
fetch("https://dog.ceo/api/breeds/image/random").then(res => res.json())
]).then(([user, dog]) => {
console.log(`ユーザー名: ${user.name}, 犬の画像URL: ${dog.message}`);
});
Q6. POSTリクエストを送信しよう
問題:
JSONPlaceholder API の /posts
に対して、
以下のデータを送信し、成功したら console.log("投稿成功")
を表示してください。
送信するデータ(JSON形式):
{
"title": "Hello Fetch",
"body": "Fetchの練習をしています",
"userId": 1
}
エンドポイント:
https://jsonplaceholder.typicode.com/posts
(POST
リクエスト)
答え(クリックで表示)
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
title: "Hello Fetch",
body: "Fetchの練習をしています",
userId: 1
})
})
.then(response => response.json())
.then(data => console.log("投稿成功", data));
🔥 ちょいムズ (1問)
Q7. 3つのAPIを順番に実行しよう
問題:
次の手順で、3つのAPIを 順番に 実行してください。
(前のAPIの結果を次のAPIのリクエストに利用する)
-
JSONPlaceholder API の
/users/1
でuserId
を取得 - 取得した
userId
を使い、/posts?userId=1
で投稿リストを取得 - 取得した最初の投稿の
id
を使い、/comments?postId=最初の投稿のid
でコメントを取得しconsole.log
に表示
エンドポイント:
https://jsonplaceholder.typicode.com/users/1
https://jsonplaceholder.typicode.com/posts?userId=1
https://jsonplaceholder.typicode.com/comments?postId=最初の投稿のid
答え(クリックで表示)
fetch("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.json())
.then(user => fetch(`https://jsonplaceholder.typicode.com/posts?userId=${user.id}`))
.then(response => response.json())
.then(posts => fetch(`https://jsonplaceholder.typicode.com/comments?postId=${posts[0].id}`))
.then(response => response.json())
.then(comments => console.log(comments));
🎯 まとめ
Fetch API を使いこなせるようになったら、
次は async/await
や axios
でのリクエストにも挑戦してみましょう!!
▼ Comming soon...