Get first image URL from Google

Viewed 685

Given a query, I'm looking for the URL of the first image that Google Images would return for such a query.

E.g. if the query is "tomatoes" I want "https://upload.wikimedia.org/wikipedia/commons/8/89/Tomato_je.jpg"

There is a number of similar questions here on Stack Overflow but everything is deprecated by now. It looks like the only working method is to register for an API key and use the Custom Search API.

This is what I've been able to achieve so far:

https://www.googleapis.com/customsearch/v1?key=AIzaSyCRNQbDeEcMTlakA8aJeFoFj9Ci9ZQTvsw&cx=017576662512468239146:omuauf_lfve&q=tomatoes&searchType=image

but there is no image URL in the response. Any help?

1 Answers

You should try using the googleapis npm library and call the cse.list method.

That way you can retrieve the list of the image results you want.

const { result } = await gapi.client.search.cse.list({
  cx: '[YOUR_CUSTOM_SEARCH_ENGINE_ID]',
  q: 'tomato',
  searchType: 'image',
});

enter image description here

Related