JAVASCRIPT

Chaining Dependent API Requests Sequentially

Learn to chain multiple API requests where subsequent requests depend on data returned from previous ones, ensuring proper sequence in JavaScript with async/await.

async function fetchUserPosts(userId) {
  try {
    // First request: Get user details
    const userResponse = await fetch(`https://api.example.com/users/${userId}`);
    if (!userResponse.ok) {
      throw new Error(`HTTP error! Status: ${userResponse.status}`);
    }
    const userData = await userResponse.json();

    // Second request: Use user data (e.g., username) to fetch their posts
    // Assuming userData contains a property like 'username' or 'postsUrl'
    const postsResponse = await fetch(`https://api.example.com/users/${userData.id}/posts`);
    if (!postsResponse.ok) {
      throw new Error(`HTTP error! Status: ${postsResponse.status}`);
    }
    const postsData = await postsResponse.json();

    console.log('User Data:', userData);
    console.log('User Posts:', postsData);
    return { user: userData, posts: postsData };
  } catch (error) {
    console.error('Error fetching user and posts:', error);
    throw error; // Re-throw to allow callers to handle
  }
}

// Example usage:
// fetchUserPosts(123).then(data => console.log('Successfully fetched:', data)).catch(err => console.error('Failed:', err));
How it works: This snippet demonstrates how to perform dependent API requests using `async/await`. The first `fetch` call retrieves user details. Once that data is available, a property (e.g., `id`) from the first response is used to construct and make the second `fetch` call to get the user's posts. This sequential execution is crucial when an API endpoint's parameters rely on the output of a preceding API call, ensuring data integrity and correct request flow.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs