How to get Flickr API working correctly in my app using webpack and React?

Hi all. I have been following the excellent article on Sitepoint about using the Flickr API by James Hibbard @James_Hibbard . However, I am using Axios instead of jQuery .ajax as well as Webpack and React.

I keep on getting XMLHttpRequest cannot load errors. This is when using

https://api.flickr.com/services/feeds/photos_public.gne?format=json

even though my understanding is that this should work as in the article. I can only assume this is due to jsonp, CORS issues?? I know that Axios doesn’t support JSONP so wonder if this makes a difference? Or webpack dev server?

However, when playing around with flickr.photos.search in the format

https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[APIKEYHERE]&format=json&nojsoncallback=1

I am able to access the data, but it is in a form that gives limited data after which I would have to make several other calls in order to determine author names, descriptions etc.

Any way I can make a simple call using the first API endpoint without having to resort to flickr.photos.search?

Any hints or tips would be welcomed.

Thanks

Update:

According to this https://github.com/github/fetch/issues/280, it seems that fetch and XMLHttpRequest will not work as Flickr does not supports CORS headers. Also, elsehwere I found that that Axios doesn’t support JSONP (if that affects me in using Flickr API?).

I am relatively novice to CORS etc but have been able to deal with it in the past with better API documentation and endpoints. Should I cut my losses and just go with jQuery? I find it odd that Flickr is this hard to use and I am wondering if it is because of Webpack dev server? I’ve tried adding headers to webpack dev server but to no avail.

I have also used the allow control allow origin extension on chrome just now and it sort of worked - but all the json data came out as one large string!?

Not sure what else to do now except use jQuery…

Hey, so essentially you’re just trying to implement the demo in the article minus the jQuery, right?

Hey Pullo. Yeah basically. So I am using Webpack if that makes a difference. I have just written an update on the original post about all the things I tried…

Well, jQuery is just JavaScript, so there’s (hopefully) no magic going on there. I’m sure we should be able to translate the article’s demo to vanilla JS and then work out how to integrate that with whatever build process you are using.

Do you have some code that isn’t working for you (just the minimum)?

photoSearch(term) {
		axios.get(`https://api.flickr.com/services/feeds/photos_public.gne?format=json`)
		.then((response) => {
		console.log(response);
			this.setState({
				photos: response.items
			})
	.catch((error) => {
			console.log(error);
		});
		});
	}

So this will work by passing a search term that I will add in using template literal. That is not really relevant right now but I just can’t figure out why it wont work on Webpack. I may just use jQuery - I have no problems using jQuery, just wanted to try without…

Ok, so that’s using axios. I don’t have any experience of this (sorry). My advice would be to use jQuery (or even just the part you need if size is an issue).

I’m on the hop right now, but I’ll have a look at translating the example to vanilla JS later on and we can see if that helps.

Thanks for the help. Appreciate it regardless. Axios is relatively simple to use and I don’t think lots in involved. But I will try jQuery for now.

Btw, this is the error I keep getting. I got rid of it with that Chrome extension but all the JSON data came out a long string:

FWIW, the Axios maintainer recommends using the jsonp module for making JSONP requests. That’s probably going to be more lightweight than introducing jQuery in this case (if you’re not already using it for something else).

Thanks for this. I haven’t introduced jQuery yet at all and was hoping not to. So jsonp module works with Axios? Or separate and therefore I wont need axios? Forgive my novice questions…

It’s standalone, but you’d still need Axios for other kinds of Ajax request. The code for the jsonp lib is actually quite straightforward and worth a read if you’re interested to learn how JSONP requests work.

Appreciate it. I will look through. I will only need this one Ajax request so if jsonp module does the job, I’m happy…

Here’s the demo minus the jQuery. That help?

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Flickr API demo</title>
  </head>
  <body>
    <button>Click here for cats!</button>
    <div id="images"></div>

    <script>
      const catButton = document.querySelector("button");
      const imageContainer = document.querySelector("#images");
      catButton.addEventListener("click", handleButtonClick);

      function jsonFlickrFeed(json) {
        Object.keys(json.items).forEach(function (key) {
          let obj = json.items[key];
          const img = document.createElement('img');
          img.src = obj.media.m
          imageContainer.appendChild(img);
        });
      };

      function handleButtonClick() {
        catButton.parentNode.removeChild(catButton);
        const script = document.createElement('script');
        script.src = 'https://api.flickr.com/services/feeds/photos_public.gne?tags=kitten&format=json';
        document.getElementsByTagName('head')[0].appendChild(script);
      }
    </script>
  </body>
</html>

Thanks again. Let me just go through this and have a read. :smile:

No worries. All it’s doing is just creating a script tag and inserting it into the page, then calling the JSONP callback.

Ok. I understand the script creation and inserting into the head (would this conflict with Webpack in anyway as I have this handling script injections?).

So then the json callback, I understand how this works on your demo page, but how would I define the success and error callbacks. Since I am using React, I will be using the success function to setState using the data returned…

It shouldn’t. Try it out :slight_smile:

Where are you seeing those?

I’m trying it out as we speak.

So I understand the general concept here but have never written it before in pure JS. I guess the jsonFlickrFeed function will get invoked as soon as the object of that name is returned via the API?

But within that function, I want to for now do nothing more than console log the response. I guess there would be no error response as it wouldnt be invoked without a return prior?

is that correct?

Kinda. The jsonFlickrFeed function will get invoked as soon as the browser injects the script into the head of the document and the script loads.

There is no error handling for cross domain JSONP requests. If you wanted that, you’d be back into plugin territory: https://github.com/jaubourg/jquery-jsonp

Makes a lot more sense now. So does that mean that .json and .ajax calls inject into script as well? So when you change the search tag, it would append a new script each time? I need to take some time going through implementing you code in terms of my requirement.

Let me play around with it. You have helped me loads! I will get back to you with results and feel free to respond whenever you have the time.

Nope. They get a response from a remote server and don’t inject anything.

Yeah, you’ll query Flickr’s API again. I’d probably replace the script tag instead of append it in this case.