Home > database >  Fetching instagram feed as JSON
Fetching instagram feed as JSON

Time:12-04

im fetching photos from my instagram account from an api, and get the JSON in my console. However, i dont know how to get the photo displayed in my HTML

This is my JS, where i fetch the photos as JSON.

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
    method: "get",
    headers: myHeaders,
    redirect: "follow",
    
};

fetch("https://v1.nocodeapi.com/aps/instagram/pjCNBSyiUmzTFIzO", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result))
    .catch(error => console.log('error', error));

    document.getElementById("test").innerHTML = result;

Console message with link to the image

CodePudding user response:

To display the photos from your Instagram account in your HTML, you will need to parse the JSON response from the API and extract the URLs of the photos. You can then create img elements in your HTML and set the src attribute of each element to the URL of the corresponding photo.

Here is an example of how you might do this:

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
  method: "get",
  headers: myHeaders,
  redirect: "follow",
};

fetch("https://v1.nocodeapi.com/aps/instagram/pjCNBSyiUmzTFIzO", requestOptions)
  .then((response) => response.json())
  .then((result) => {
    // Parse the JSON response and extract the photo URLs
    const photoUrls = result.data.map((photo) => photo.media_url);

    // Create img elements for each photo
    const photoElements = photoUrls.map((url) => {
      const imgElement = document.createElement("img");
      imgElement.src = url;
      return imgElement;
    });

    // Append the img elements to the HTML element with the ID "test"
    const testElement = document.getElementById("test");
    photoElements.forEach((imgElement) => testElement.appendChild(imgElement));
  })
  .catch((error) => console.log("error", error));

In this example, the JSON response from the API is parsed and the URLs of the photos are extracted and stored in the photoUrls array. Then, an img element is created for each photo URL, and the src attribute of each element is set to the URL of the corresponding photo. Finally, the img elements are appended to the test element in the HTML.

This will display the photos from your Instagram account in the HTML element with the ID "test". You can customize the code to suit your specific needs, such as by setting the width and height of the photos, or by adding captions or other information. Consult the documentation for the API you are using for more information on the structure of the JSON response and the available data.

  • Related