Retrieve data from a JSON file to assign to a variable, then access another API to retrieve a second

I am completely new to the world of javascript and json. My previous experience with javascript was quite minimal, about 12 years ago. So, please bear with me as I try to explain my current issue. The problem I am facing involves retrieving a second API URL from an initial API URL and using the JSON data from that file to generate an HTML page.

Let's illustrate this with an example. Imagine I have an API URL like

http://www.thiscarsite.com/API/thecars
. The structure of the JSON data retrieved from this URL might resemble something like the following:

{ "manufacturer": "Cheverolet",
  "model": "Camaro",
  "year": "1990",
  "styles": {
        "top": "convertible",
        "engine"; "v8",
        "address": "http://www.somesite.com/api/90ChevCamConvV8"
        }
}

While I can successfully fetch the initial JSON file using the fetch/await method or a simple code snippet like this:

const startUrl = 'http://www.thiscarsite.com/API/thecars';
fetch(startUrl)
  .then(response => {
    return response.json();
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

The dilemma arises when trying to extract the URL from the first JSON data and then fetching the secondary JSON file. In my case, the URL in the initial JSON file changes frequently, necessitating extracting it each time before accessing the data. I've come across examples where one retrieves the URL by using

const newURL = data.styles.address;
, but how do I navigate getting this address and subsequently requesting the second JSON file?

I acknowledge that this information may be readily available through online resources. However, my lack of expertise in this field limits my ability to use the appropriate search terms effectively.

I genuinely appreciate any guidance provided to steer me in the right direction.

MY ATTEMPTS, Unsuccessful

I attempted various approaches, but integrating the second URL into my edits led to failures. For instance:

fetch('https://example.com/endpoint1')
  .then(response => {
    return response.json();
  })
  .then(data1 => {
    return fetch(`https://example.com/endpoint2?data=${data1}`);
  })
  .then(response => {
    return response.json();
  })
  .then(data2 => {
    console.log(data2);
  })
  .catch(error => {
    console.error(error);
  });

I also experimented with utilizing two async functions, only to encounter errors such as "response already called" during execution.

Answer №1

After some reflection, I was able to identify the mistake in my approach. It dawned on me that the term "response" didn't have to be repeated and could take on any name. Consequently, I made the necessary correction and adjusted my code as shown below:

async function fetchData(){
const serverResponse = await fetch(startUrl, {headers: myheader});
const firstData = await serverResponse.json();
console.log(firstData);
const newEndpoint = firstData.styles.address;
const secondResponse = await fetch(newEndpoint);
const finalData = await secondResponse.json();
console.log(finalData);
}
fetchData();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty integrating a Hangout button using APIs on my webpage

I'm having some trouble adding a basic Hangout button component to initiate Google's Hangout. I've been following the steps outlined on the Google Developer page, but despite my efforts, I can't seem to resolve the following issue: Fai ...

Guide to prompting a browser to download a file using an XHR request

When it comes to downloading files from a server using an XHR request, how can I ensure that the browser initiates the download once the response is received? Additionally, which headers should be included by the server for this process to work seamlessl ...

Ways to store a component in cache once its route is triggered

There are 3 components in my project: 1 parent and 2 child components with router outlet. The child component becomes active whenever its route is called, sharing data using a service. Both of these child components have complex views. When switching bet ...

Unable to fetch Title from Strapi

I have a collection type named posts with the following values: https://i.sstatic.net/49OeV.png To access the API, I have a file in my lib folder that contains the following code: export async function getPosts() { var api_base_url = process.env.API_BASE ...

Strange behavior detected in TypeScript generic function when using a class as the generic parameter

class Class { } const f0 = <T extends typeof Class> (c:T): T => { return c } const call0 = f0 (Class) //ok const f1 = <T extends typeof Class> (c:T): T => { const a = new c() return a //TS2322: Type 'Class' is not assigna ...

During the rendering process, a referenced computed property is not defined on the instance

Description: In my child component, I am working with an array called expenseButton that is passed as props. The array contains objects with values which I need to calculate the sum of using the array.reduce() method. Issue: While I can successfully get ...

Tips on modifying classes within specific sections of HTML tables

I attempted to create calendar-like tables, In my script, I am trying to handle events being registered. My goal is to change the classes of cells from 2 to 5 when they are clicked on, and change the cell colors from first to hovered to aqua. For this p ...

.post method reveals parameter in URL upon submission

Currently, I am utilizing the $.post method to send a value to a PHP page for processing after replacing the serialize utility with a more specific element: $("button").click(function(event) { $.post( "php/index.php", { seq: $("seq").v ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

employing this for the second parameter

Utilizing this.value for $(".selector") is my goal with $("#style_background") serving as my save button. However, when I implement this code, the value coming through is 'save'. How can I achieve this using dania and seablue? $("#style_backgrou ...

Activate the toggle menu

Hi there! I'm currently working on a menu and I want the clicked item to become active, switching the active state to another item when clicked. However, my current implementation is not working as expected. Any assistance would be greatly appreciated ...

Using JSTL with jQuery or JavaScript

I am trying to send array elements from my Java code to a JSP page. The goal is for the array elements to be displayed on the page when a button is clicked. I have attempted to use the JSTL forEach tag within JavaScript or jQuery, but unfortunately, it do ...

Validating whether another element is checked when a radio button is unchecked

I'm completely stuck on this issue - I just can't figure out how to dynamically change the image when a user unchecks a radio button (i.e., checks a different radio button). Here is the code: handleCheckbox = e => { let target = e.targe ...

What could be causing my bounce animation to begin 50 pixels higher than its intended starting point?

Trying to create a bouncing effect on text Check out my attempt here. It seems like the bug is in this area. @keyframes bounce{ 0%, 40%{ transform:scale(2,.5) translate(0,100px); } 45%,55%{ transform:translate(0,-50px); } 55%, 100%{ ...

What is the process of utilizing jQuery to hover over a relevant cell?

I'm interested in learning how to implement jQuery to highlight related tables. Initially, I explored this JS fiddle and discovered a method for highlighting both vertically and horizontally. I conducted several searches to find a similar approach, ...

Can someone explain the method for displaying or concealing a menu based on scrolling direction?

https://i.stack.imgur.com/tpDx0.jpg I want to hide this menu when scrolling down and show it when scrolling up. The code for my menu bot is: <script> var previousScroll = 0; $(window).scroll(function(event){ v ...

Validating items within an array in a JSON field in Postgresql

Is there a way to ensure that a postgres json field is validated in such a manner that every item within an array inside the json must contain specific properties? For instance, if the json field contains an array of objects labeled as contacts, I require ...

Implementing a delay using setTimeOut function to execute an action upon user input

Take a look at this code snippet: $("#test").on("keyup", (e) => { if(e.target.value.length === 3) { setTimeout(() => { console.log("fired") }, 2000) } }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.m ...

An 'Syntax Error' message appears in Internet Explorer when JSONP does not receive a response

Our current application needs to retrieve information from another application, and this second application does not have to be active to respond to the JSONP request. In this case, the requester will receive an alert message informing them of this. funct ...

What is the best way to add a value to the value attribute of a div using JavaScript?

Is there a way to insert a value into the value attribute of a div using Internet Explorer 9? I have attempted various JavaScript functions, but so far I can only modify the content inside the div and not the value attribute itself. <div id="mydiv" val ...