How to pass query params to a GET request with fetch
Doing a GET request with fetch
is easy:
const data = await fetch(`https://pokeapi.co/api/v2/pokemon`).then(reponse => response.json());
But what if you need to pass query string params? E.g. https://pokeapi.co/api/v2/pokemon?limit=100000&offset=0
. How do you make these configurable?
You can use the URL and URLSearchParams browser APIs:
const url = new URL('https://pokeapi.co/api/v2/pokemon');
const params = { limit: "100000", offset: "0" }
url.search = new URLSearchParams(params).toString();
fetch(url)
const data = await fetch(url).then(reponse => response.json());
And that's it!
Looking for a shorter version? You can just concatenate the params
and toString
will be called for you behind the scenes:
const params = new URLSearchParams({ limit: "100000", offset: "0" });
fetch(`https://pokeapi.co/api/v2/pokemon?${params}`);
Member discussion