Skip to content

Instantly share code, notes, and snippets.

@mbforbes
Created September 16, 2023 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbforbes/22d4cbb36167246351f645f9c9025770 to your computer and use it in GitHub Desktop.
Save mbforbes/22d4cbb36167246351f645f9c9025770 to your computer and use it in GitHub Desktop.
First, click button at https://cors-anywhere.herokuapp.com/corsdemo. Then, run this
async function getWikiImageURL(searchQuery) {
const PROXY = "https://cors-anywhere.herokuapp.com/";
const WIKI_API_ENDPOINT = `${PROXY}https://en.wikipedia.org/w/api.php`;
// First fetch to get the page ID
let pageId;
try {
console.log("Trying request 1");
const response1 = await fetch(
`${WIKI_API_ENDPOINT}?action=query&list=search&srsearch=${encodeURIComponent(
searchQuery
)}&format=json`
);
const data1 = await response1.json();
if (data1.query.search.length === 0) {
// No search results
console.log("Request 1: No search results");
return null;
}
pageId = data1.query.search[0].pageid; // Get the first result's page ID
} catch (error) {
console.log("Request 1: Fetch or parsing failed");
return null; // Fetch or parsing failed
}
console.log("Got page id:", pageId);
// Second fetch to get the image URL using the page ID
try {
console.log("Trying request 2");
const response2 = await fetch(
`${WIKI_API_ENDPOINT}?action=query&prop=pageimages&piprop=original&pageids=${pageId}&format=json`
);
const data2 = await response2.json();
console.log("Response 2:");
console.log(data2);
return data2.query.pages[pageId].original.source; // Get the image URL
} catch (error) {
console.log("Request 2: Fetch or parsing failed");
console.log(error);
return null; // Fetch or parsing failed
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment