JavaScript Fetch API and API Practice Questions with Solutions

Introductions

The Fetch API is used to request data from a server or API using JavaScript. It is one of the most important skills for modern JavaScript because websites and web applications frequently communicate with APIs.

In this chapter, you will practice fetch(), handling JSON responses, .then(), async/await, error handling, POST requests, and working with API data through easy, step-by-step examples. JavaScript Fetch API and API practice questions help to understand the concepts.

Question 1: Make a Basic Fetch Request

Problem

Use the Fetch API to request data from a public API and display the response.

Solution

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        console.log(data);
    })
    .catch(function(error) {
        console.log("Error:", error);
    });

Output

The API returns an object similar to:

{
    userId: 1,
    id: 1,
    title: "...",
    body: "..."
}

Step-by-step Explanation

  1. fetch() sends a request to the API.
  2. The API sends a response.
  3. response.json() converts the JSON response into a JavaScript value.
  4. The second .then() receives the converted data.
  5. .catch() handles errors that occur while processing the Promise chain.

The basic pattern is:

fetch(url)
    .then(response => response.json())
    .then(data => {
        // Use data
    });

Question 2: Get a Specific Property from API Data

Problem

Fetch a post and display only its title.

Solution

fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {

        console.log(data.title);

    })
    .catch(function(error) {

        console.log("Error:", error);

    });

Output

The title of the requested post

Step-by-step Explanation

The API response contains several properties:

{
    userId: 1,
    id: 1,
    title: "...",
    body: "..."
}

After converting the response to a JavaScript object, you can access the title using:

data.title

Question 3: Fetch API Data Using async/await

Problem

Fetch a post using async/await instead of .then().

Solution

async function getPost() {

    const response = await fetch(
        "https://jsonplaceholder.typicode.com/posts/1"
    );

    const data = await response.json();

    console.log(data);

}

getPost();

Output

{
    userId: 1,
    id: 1,
    title: "...",
    body: "..."
}

Step-by-step Explanation

There are two important await statements:

const response = await fetch(url);

This waits for the server response.

Then:

const data = await response.json();

This waits for the response body to be converted from JSON.

The complete flow is:

fetch()
   ↓
Response
   ↓
response.json()
   ↓
JavaScript object

Question 4: Handle Fetch Errors with try…catch

Problem

Use async/await and try...catch to safely handle an API request.

Solution

async function getData() {

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/posts/1"
        );

        const data = await response.json();

        console.log(data);

    } catch (error) {

        console.log("Something went wrong:", error.message);

    }

}

getData();

Output

If the request succeeds, the API data is displayed.

If a network-related error occurs:

Something went wrong: ...

Step-by-step Explanation

  1. The API request is placed inside try.
  2. await fetch() waits for the response.
  3. response.json() converts the response.
  4. If an exception occurs, execution moves to catch.
  5. The error can then be handled without crashing the normal flow of the function.

Question 5: Check response.ok

Problem

Fetch a resource and check whether the HTTP response was successful before processing its JSON data.

Solution

async function getPost() {

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/posts/1"
        );

        if (!response.ok) {
            throw new Error("Request failed.");
        }

        const data = await response.json();

        console.log(data);

    } catch (error) {

        console.log("Error:", error.message);

    }

}

getPost();

Output

For a successful request:

{
    userId: 1,
    id: 1,
    title: "...",
    body: "..."
}

Step-by-step Explanation

A very important point about fetch() is that an HTTP error response does not automatically make the Fetch Promise reject.

For example, a server can return a response with a 404 status.

That’s why you should often check:

if (!response.ok) {
    throw new Error("Request failed.");
}

response.ok is true for successful HTTP responses in the 2xx range.


Question 6: Fetch Multiple Posts

Problem

Fetch several posts and display their titles.

Solution

async function getPosts() {

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/posts"
        );

        if (!response.ok) {
            throw new Error("Unable to fetch posts.");
        }

        const posts = await response.json();

        posts.slice(0, 5).forEach(function(post) {

            console.log(post.title);

        });

    } catch (error) {

        console.log(error.message);

    }

}

getPosts();

Output

Post title 1
Post title 2
Post title 3
Post title 4
Post title 5

Step-by-step Explanation

  1. fetch() requests the posts endpoint.
  2. response.ok checks whether the HTTP response was successful.
  3. response.json() converts the response into an array.
  4. slice(0, 5) selects the first five posts.
  5. forEach() loops through those posts.
  6. post.title gets each title.

Question 7: Display API Data on a Web Page

Problem

Fetch posts from an API and display their titles inside a webpage.

Solution

<div id="posts"></div>

<script>
async function loadPosts() {

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/posts"
        );

        if (!response.ok) {
            throw new Error("Unable to load posts.");
        }

        const posts = await response.json();

        const container = document.getElementById("posts");

        posts.slice(0, 5).forEach(function(post) {

            const heading = document.createElement("h3");

            heading.textContent = post.title;

            container.appendChild(heading);

        });

    } catch (error) {

        console.log(error.message);

    }
}

loadPosts();
</script>

Output

The webpage displays five post titles.

Step-by-step Explanation

  1. The API returns an array of posts.
  2. The JSON response is converted into a JavaScript array.
  3. The posts container is selected.
  4. forEach() loops through the posts.
  5. A new <h3> element is created.
  6. textContent adds the title.
  7. appendChild() adds the element to the webpage.

This is an important step toward building real API-powered websites.


Question 8: Send Data with a POST Request

Problem

Send a new post to an API using the POST method.

Solution

async function createPost() {

    try {

        const response = await fetch(
            "https://jsonplaceholder.typicode.com/posts",
            {
                method: "POST",

                headers: {
                    "Content-Type": "application/json"
                },

                body: JSON.stringify({
                    title: "Learning JavaScript",
                    body: "Practicing Fetch API",
                    userId: 1
                })
            }
        );

        if (!response.ok) {
            throw new Error("Unable to create post.");
        }

        const data = await response.json();

        console.log(data);

    } catch (error) {

        console.log("Error:", error.message);

    }
}

createPost();

Output

The test API returns an object representing the submitted post, typically including an assigned id.

{
    title: "Learning JavaScript",
    body: "Practicing Fetch API",
    userId: 1,
    id: ...
}

Step-by-step Explanation

A GET request normally retrieves data.

A POST request can send data to the server.

The important parts are:

method: "POST"

The content type tells the server that JSON is being sent:

headers: {
    "Content-Type": "application/json"
}

The JavaScript object is converted to JSON before sending:

body: JSON.stringify({
    title: "Learning JavaScript",
    body: "Practicing Fetch API",
    userId: 1
})

Question 9: Fetch Data Based on a Dynamic ID

Problem

Create a function that accepts a post ID and fetches that specific post.

Solution

async function getPostById(id) {

    try {

        const response = await fetch(
            `https://jsonplaceholder.typicode.com/posts/${id}`
        );

        if (!response.ok) {
            throw new Error("Post not found.");
        }

        const post = await response.json();

        console.log("Title:", post.title);
        console.log("Body:", post.body);

    } catch (error) {

        console.log("Error:", error.message);

    }
}

getPostById(5);

Output

Title: ...
Body: ...

Step-by-step Explanation

The function receives:

getPostById(5);

The ID is inserted into the URL:

`https://jsonplaceholder.typicode.com/posts/${id}`

For id = 5, the request is made for post 5.

This technique is useful when API URLs depend on user input or selected records.


Question 10: Build a Complete API Search Example

Problem

Create a small webpage where a user enters a post ID. When the button is clicked, fetch that post and display its title and body.

Solution

<input type="number" id="postId" placeholder="Enter post ID">

<button id="searchButton">
    Search
</button>

<div id="result"></div>

<script>
const button = document.getElementById("searchButton");
const result = document.getElementById("result");

button.addEventListener("click", async function() {

    const id = document.getElementById("postId").value;

    if (!id) {
        result.textContent = "Please enter a post ID.";
        return;
    }

    try {

        result.textContent = "Loading...";

        const response = await fetch(
            `https://jsonplaceholder.typicode.com/posts/${id}`
        );

        if (!response.ok) {
            throw new Error("Post not found.");
        }

        const post = await response.json();

        result.innerHTML = `
            <h2>${post.title}</h2>
            <p>${post.body}</p>
        `;

    } catch (error) {

        result.textContent = error.message;

    }

});
</script>

Output

The user can enter a post ID such as:

5

The webpage then displays the corresponding post title and body.

Step-by-step Explanation

  1. An input field accepts the post ID.
  2. The button receives a click event.
  3. JavaScript reads the entered ID.
  4. The program checks whether an ID was entered.
  5. fetch() requests the selected post.
  6. response.ok checks the HTTP response.
  7. response.json() converts the response into a JavaScript object.
  8. The title and body are displayed on the webpage.
  9. If something goes wrong, the catch block displays an error.

This combines several important JavaScript concepts:

DOM
 ↓
Event Listener
 ↓
Fetch API
 ↓
Promise
 ↓
async/await
 ↓
JSON
 ↓
Error Handling
 ↓
DOM Update

Key Takeaways

  • The Fetch API is used to make HTTP requests from JavaScript.
  • fetch() returns a Promise.
  • response.json() converts a JSON response into a JavaScript value.
  • async/await makes Fetch API code easier to read.
  • try...catch can handle exceptions around asynchronous code.
  • Always consider checking response.ok before processing a response.
  • fetch() does not automatically reject its Promise just because the server returns an HTTP error status.
  • GET requests are commonly used to retrieve data.
  • POST requests can send data to a server.
  • JSON.stringify() converts JavaScript data into JSON text for a request body.
  • HTTP headers can describe the data being sent.
  • API URLs can be created dynamically using template literals.
  • Fetch API is commonly used when building modern web applications.
  • CORS rules can affect whether a browser allows a webpage to read a response from another origin.
  • API requests can fail because of network problems, server responses, permissions, or invalid requests, so proper error handling is important.

FAQs

1. What is the Fetch API in JavaScript?

The Fetch API is a modern browser API used to make HTTP requests and work with responses asynchronously.

Example:

fetch("https://example.com/data")
    .then(function(response) {
        return response.json();
    })
    .then(function(data) {
        console.log(data);
    });

2. What does fetch() return?

fetch() returns a Promise.

That Promise fulfills with a Response object when the browser receives a response.

const response = await fetch(url);

You can then inspect the response or read its body.

3. Why do we use response.json()?

An API may return JSON data as the response body. response.json() reads that body and parses it as JSON.

const response = await fetch(url);
const data = await response.json();

The resulting data can then be used as a JavaScript object or array.

4. Does Fetch automatically throw an error for a 404 response?

No.

A response such as 404 Not Found does not normally cause the Fetch Promise itself to reject.

That is why this pattern is useful:

if (!response.ok) {
    throw new Error("Request failed.");
}

5. What is the difference between GET and POST?

GET is commonly used to retrieve data:

fetch(url);

POST is commonly used to send data to a server:

fetch(url, {
    method: "POST",
    body: JSON.stringify(data)
});

The exact behavior depends on the API’s design.

6. Why is JSON.stringify() used in a POST request?

JavaScript objects are not automatically sent as JSON text.

For a JSON request body, you can convert the object with:

JSON.stringify(data)

Example:

body: JSON.stringify({
    name: "Rahul",
    age: 20
})

7. Can Fetch API be used with async/await?

Yes. This is one of the most common ways to write Fetch API code.

async function getData() {

    const response = await fetch(url);

    const data = await response.json();

    console.log(data);
}

For production code, you should also consider checking response.ok and handling errors.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top