Let's imagine we want to make a GET request to the Google Translate REST endpoint https://translation.googleapis.com/language/translate/v2
.
We need to pass the source & target languages, the text to translate, the format and our API key.
const params = {
key: 'XXX',
q: 'I like coding',
target: 'fr',
source: 'en',
format: 'text'
}
Our GET request URL should look like that:
https://translation.googleapis.com/language/translate/v2?key=XXX&q=I+like+coding&target=fr&source=en&format=text
To obtain that URL, we need to serialize the params object. Using jQuery, we can simply write jQuery.param(params)
.
In plain JavaScript, we can use the URLSearchParams constructor, which returns a URLSearchParams object.
The problem is that URLSearchParams is quite restrictive about what formats it accepts. For instance, we can't just pass it our params object. It needs to be in this format:
[ ["key","XXX"], ["q","I like coding"], ["target","fr"], ["source","en"],["format","text"] ]
Worry not, EcmaScript 2017 gave us the Object.entries method, which turns our object in the exact format we need:
Object.entries(params) // [ ["key","XXX"], ["q","I like coding"], ["target","fr"], ["source","en"], ["format","text"] ]
We can then initialize our URLSearchParams object in this way:
const URLparams = new URLSearchParams(Object.entries(params))
urlParams.toString() // "key=XXX&q=I+like+coding&target=fr&source=en&format=text"
Finally we can make our request. Note that you can directly append the URLparams object to the URL string without calling the toString() method. But don't forget to add the ?
character before it.
fetch('https://translation.googleapis.com/language/translate/v2?' + URLparams)
That's it! Thank you for reading my post and let me know in the comment section below if you know of better/other ways to achieve this.
Note on browser support
Object.entries and URLSearchParams are supported in all modern browsers and can be polyfilled in IE11: Object.entries polyfill, URLSearchParams polyfill