I'm pretty new to APIs, and I'm starting my first API project. I'm using the Petfinder API v2 to create a website that searches for adoptable animals. But their API uses OAuth, and they give you a key and secret. Then you use those to get a token using something like CURL. But this token expires in 60 minutes. After that, you need to request a new token. Does anyone know how to increase the token's expiration? Or is there a way to have an unlimited amount of time? Or is there a code that will automatically get new tokens? I'm using vanilla JavaScript to program this.
This is their documentation: https://www.petfinder.com/developers/v2/docs/
There's nothing you can do to extend your access tokens expiration time. It's a security measure for Petfinders benefit so they don't have a bunch of old tokens lying around.
What you can do is update your code to fetch a new token if your token has expired. Original inspiration in vanilla javascript is here.
// Get OAuth token
const getOAuth = function() {
return fetch('https://api.petfinder.com/v2/oauth2/token', {
method: 'POST',
body: 'grant_type=client_credentials&client_id=' + key + '&client_secret=' + secret,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(resp) {
return resp.json();
}).then(function(data) {
// Store token data
token = data.access_token;
tokenType = data.token_type;
expires = new Date().getTime() + (data.expires_in * 1000);
});
};
// Make call if token expired
const makeCall = () => {
// If current token is invalid, get a new one
if (!expires || expires - new Date().getTime() < 1) {
getOAuth().then(function() {
// use access token
});
}
};