Hi @ankitag3
Adobe API token will expiry after 24 hours
You can use this code fetch bearer token dynamically.
let accessToken = null;
let tokenExpirationTime = null;
// Function to fetch a new Bearer token
async function fetchBearerToken() {
const response = await fetch('https://example.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Include any required credentials or additional headers
},
body: JSON.stringify({
// Include required parameters for token retrieval
username: 'yourUsername',
password: 'yourPassword'
})
});
if (!response.ok) {
throw new Error('Failed to fetch token');
}
const data = await response.json();
accessToken = data.token; // Assuming the token is in `data.token`
const expiresIn = data.expiresIn; // Assuming expiration is provided in seconds
tokenExpirationTime = Date.now() + expiresIn * 1000; // Convert to milliseconds
}
// Function to get the Bearer token, refreshing if necessary
async function getBearerToken() {
const isTokenExpired = !accessToken || Date.now() >= tokenExpirationTime;
if (isTokenExpired) {
await fetchBearerToken();
}
return accessToken;
}
// Example usage in an API request
async function makeApiRequest() {
const token = await getBearerToken();
const response = await fetch('https://example.com/api/protected-resource', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('API request failed');
}
const data = await response.json();
return data; // Process your data as needed
}
// Call the API
makeApiRequest()
.then(data => console.log(data))
.catch(error => console.error(error));