5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】 fetchでAPIに慣れるための問題集 #1

Posted at

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-endpointfetch を実行し、
エラーが発生した場合は "エラーが発生しました"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を並列で取得しよう

問題:

この2つを 同時に 取得し、console.log で結果を表示してください。(Promise.all を使うと良いかも?)

エンドポイント:

  1. https://jsonplaceholder.typicode.com/users/1
  2. 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/postsPOST リクエスト)

答え(クリックで表示)
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のリクエストに利用する)

  1. JSONPlaceholder API/users/1userId を取得
  2. 取得した userId を使い、 /posts?userId=1 で投稿リストを取得
  3. 取得した最初の投稿の id を使い、 /comments?postId=最初の投稿のid でコメントを取得し console.log に表示

エンドポイント:

  1. https://jsonplaceholder.typicode.com/users/1
  2. https://jsonplaceholder.typicode.com/posts?userId=1
  3. 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/awaitaxios でのリクエストにも挑戦してみましょう!!

▼ Comming soon...

5
8
1

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
5
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?