Published
Edited
Sep 24, 2019
1 fork
1 star
Insert cell
md`# OAuth with fetch in vanilla JS
Exercise from https://gomakethings.com/using-oauth-with-fetch-in-vanilla-js/?mc_cid=f1faa82f28&mc_eid=8e9dd7f5e3`
Insert cell
org = 'RI77'
Insert cell
status = 'adoptable'
Insert cell
cache = ({
token: null,
tokenType: null,
expires: null
})
Insert cell
fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + Secret('Petfinder API Key') + '&client_secret=' + Secret('Petfinder API Secret'),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(resp => {
return resp.json()
}).then(data => {
console.log('token', data)
// Store token data
cache.token = data.access_token;
cache.tokenType = data.token_type;
cache.expires = new Date().getTime() + (data.expires_in * 1000)
return data
}).then(data => {
return fetch ('https://api.petfinder.com/v2/animals?organization=' + org + '&status=' + status, {
headers: {
'Authorization': `${data.token_type} ${data.access_token}`,
'Content-Type': 'application/x-www/form-urlencoded'
}
})
}).then(resp => {
return resp.json()
}).then(data => {
console.log('pets', data)
return data
}).catch(err => {
console.log('something went wrong', err)
})
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more