Integrate v0 with the Shutterstock API easily—follow our step-by-step guide for best practices, troubleshooting tips, and a smooth backend integration.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
shutterstockConfig.ts
in your project's source directory (where your other TypeScript files are located).shutterstockConfig.ts
:export const SHUTTERSTOCK_CONFIG = {
CLIENTID: 'YOURCLIENTIDHERE',
CLIENTSECRET: 'YOURCLIENTSECRETHERE',
TOKENURL: 'https://api.shutterstock.com/v2/oauth/accesstoken',
APIBASEURL: 'https://api.shutterstock.com/v2'
};
shutterstockApi.ts
in the same source directory.shutterstockApi.ts
:import { SHUTTERSTOCK_CONFIG } from './shutterstockConfig';
interface AccessTokenResponse {
access_token: string;
token_type: string;
expires_in: number;
scope: string;
}
let cachedToken: string | null = null;
let tokenExpiry: number = 0;
/**
- Fetches a new access token from Shutterstock API using client credentials.
*/
export async function getAccessToken(): Promise<string> {
const now = Date.now();
if (cachedToken && now < tokenExpiry) {
return cachedToken;
}
const credentials = btoa(${SHUTTERSTOCK_CONFIG.CLIENT_ID}:${SHUTTERSTOCK_CONFIG.CLIENT_SECRET});
const params = new URLSearchParams();
params.append('granttype', 'clientcredentials');
try {
const response = await fetch(SHUTTERSTOCKCONFIG.TOKENURL, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': Basic ${credentials}
},
body: params.toString()
});
if (!response.ok) {
throw new Error(Token request failed: ${response.status} ${response.statusText});
}
const data: AccessTokenResponse = await response.json();
cachedToken = data.access_token;
tokenExpiry = now + (data.expires_in * 1000) - 60000; // Refresh 1 minute before expiry
return cachedToken;
} catch (error) {
console.error('Error fetching access token:', error);
throw error;
}
}
/**
- Searches Shutterstock images using a query string.
*/
export async function searchImages(query: string): Promise<any> {
const token = await getAccessToken();
const searchUrl = ${SHUTTERSTOCK_CONFIG.API_BASE_URL}/images/search?query=${encodeURIComponent(query)};
try {
const response = await fetch(searchUrl, {
headers: {
'Authorization': Bearer ${token}
}
});
if (!response.ok) {
throw new Error(Search request failed: ${response.status} ${response.statusText});
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error searching images:', error);
throw error;
}
}
index.ts
or another file where you handle API interactions), import the functions from shutterstockApi.ts
.searchImages
function and handle the result:import { searchImages } from './shutterstockApi';
async function performImageSearch() {
try {
const query = 'nature'; // Replace with desired search term
const searchResults = await searchImages(query);
console.log('Search Results:', searchResults);
// Implement further logic to display or process the searchResults as needed
} catch (error) {
console.error('Error during image search:', error);
}
}
// Invoke the search function (you can call this from an event handler or when your application starts)
performImageSearch();
fetch
API is used, which is supported in most modern browsers and environments without installing extra libraries.fetch
, add the following script tag in your HTML file within the <head>
section:<script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/3.6.2/fetch.min.js"></script>
shutterstockConfig.ts
are correct and that your project environment supports modern JavaScript features such as async/await.When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.