On many occasions, we want to get JSON data from a URL with JavaScript.
In this article, we’ll look at how to get JSON data from a URL with JavaScript.
Use the Fetch API
The Fetch API lets us make HTTP requests easily within the browser.
It’s promise-based and we can use it to get JSON data easily.
This means we can make multiple requests sequentially easily.
For instance, we can write:
fetch('https://yesno.wtf/api')
.then(res => res.json())
.then((out) => {
console.log(out);
})
.catch(err => {
throw err
});
to make a GET request to the URL we pass into fetch
.
Then we can res.json
in the then
callback to convert the response to a JSON object and return a promise with that.
Next, we get the result from the parameter from the 2nd promise callback.
And so we get something like:
{answer: "yes", forced: false, image: "https://yesno.wtf/assets/yes/11-a23cbde4ae018bbda812d2d8b2b8fc6c.gif"}
for out
.
We can also use the async
and await
syntax to make this shorter.
The catch
method lets us catch any request errors that arise.
For instance, we can write:
(async () => {
try {
const res = await fetch('https://yesno.wtf/api')
const out = await res.json()
console.log(out);
} catch (err) {
throw err
}
})()
We replaced the then
callbacks with await
.
And we replaced the catch
method with the catch
block.
Conclusion
We can use the Fetch API to get JSON data from a URL easily.
It’s a promised-based API which makes making multiple requests sequentially easy.