Fetching data from an API
API's are opening up and there's tons of examples on pages like https://github.com/toddmotto/public-apis
When working with API's, fetch
is a common way to get the data it exposes. Other libraries serve a similar purpose, like Axios
. There are have been many ways to do this throughout the ages, and although callbacks were common, Promise
s and more recently async/await
is taking over.
I recorded two short gifs to explain how a Promise
can be used, as well as how much easier and smaller the code is by using await
.
To get the data from this API, you could wrap it in a Promise
:
const apiUrl = 'https://jobs.search.gov/jobs/search.json\?query\=nursing+jobs+in+ny'
// Making a promise
const apiPromise = new Promise((resolve, reject) => {
// Using a promise
fetch(apiUrl).then((result) => {
console.log('Fetched!', new Date().getTime())
resolve(result.json())
}).catch((error) => {
console.log('Failed fetch', new Date().getTime())
reject(error)
})
})
https://gifsplanation.com/gifs/javascript-fetch-from-an-api-with-promises
Here's the same 2 promises resolved (fetch
and result.json()
) using await
:
const apiUrl = 'https://jobs.search.gov/jobs/search.json\?query\=nursing+jobs+in+ny'
// await only works in an async function
async function getJobs() {
try {
const result = await fetch(apiUrl)
const json = await result.json()
console.log(json)
} catch(error) {
console.log(error)
}
}
https://gifsplanation.com/gifs/javascript-fetch-from-an-api-with-await
Congratulations @codeluggage! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @codeluggage! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Do not miss the last post from @steemitboard:
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit