How to display json Image collected from Flickr API in HTML

368 Views Asked by At

I've been tasked to build an API that will get data from Flickrs public photo.search API and then feed these pictures to my website. I've used a lot of YouTube videos to try and create my API because I'm totally new to this, I've only written HTML, CSS and basic Java.

But now when I've started my http-server with npm no picture is showing and I'm getting an error in the console in Chrome. Could someone help me get this going? Thanks

let pagenr=1;
let query ="";

async function Photos(pagenr) {
    const data = await fetch(
        `https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=f594577bccc78a7056049a0aaa2d1cc2&per_page=10&format=json&nojsoncallback=1&text=MarvelUniverse`, 
        {
            method:"GET",
            headers : {
            Accept: "application/json",
           
            },
        }
    );
    const result=await data.json();
    console.log(result);
    const pic=document.createElement("div");
        document.querySelector(".gallery").appendChild(pic);
    };
Photos(pagenr);

EDIT: I've tried to change the .json to .text and the error is gone but I'm now getting the raw json string from the Flickr API. I want that json to be converted to an object to display as an image in the HTML with http-server. Any help is appreciated!

EDIT 2: Changed the API URL and back to .json and all seems good but can't get anything to be displayed in my HTML.

1

There are 1 best solutions below

0
Conor Reid On

The issue is because inside the URL you have jsoncallback=FlickrPhotoSearch which is designed to help invoke a function after an API call. This actually means the response type is no longer valid JSON which is causing the error you are seeing. You want to get the raw JSON, for the Flickr API you need to add nojsoncallback=1 and remove jsoncallback=FlickrPhotoSearch from the API URL.

You seemed to have posted the URL with your API key included inside too, this meant I was able to access the link using your API credentials and anyone else can do the same. You should change this key as soon as possible.