JavaScript Examples
Practical JavaScript examples for integrating with the Social Unlocks API.
Basic Key Validation
Simple Key Validation Function
async function validateKey(key) {
try {
const response = await fetch(
`/api/keys/validate?key=${key}`
);
const data = await response.json();
return data.valid;
} catch (error) {
console.error('Validation failed:', error);
return false;
}
}
try {
const response = await fetch(
`/api/keys/validate?key=${key}`
);
const data = await response.json();
return data.valid;
} catch (error) {
console.error('Validation failed:', error);
return false;
}
}
Fetch User Lockers
Get User's Active Lockers
async function getUserLockers(username) {
try {
const response = await fetch(
`/api/public-profile/${username}/lockers`
);
if (response.ok) {
const data = await response.json();
return data.lockers;
} else {
console.error('Failed to fetch lockers');
return [];
}
} catch (error) {
console.error('Error:', error);
return [];
}
}
try {
const response = await fetch(
`/api/public-profile/${username}/lockers`
);
if (response.ok) {
const data = await response.json();
return data.lockers;
} else {
console.error('Failed to fetch lockers');
return [];
}
} catch (error) {
console.error('Error:', error);
return [];
}
}
Advanced Error Handling
Comprehensive Error Handling
async function makeApiRequest(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
throw new Error(`Bad request: ${error.error}`);
case 404:
throw new Error(`Not found: ${error.error}`);
case 429:
throw new Error(`Rate limited: ${error.error}`);
default:
throw new Error(`API error: ${error.error}`);
}
}
return await response.json();
} catch (error) {
console.error('Request failed:', error.message);
throw error;
}
}
try {
const response = await fetch(url, options);
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
throw new Error(`Bad request: ${error.error}`);
case 404:
throw new Error(`Not found: ${error.error}`);
case 429:
throw new Error(`Rate limited: ${error.error}`);
default:
throw new Error(`API error: ${error.error}`);
}
}
return await response.json();
} catch (error) {
console.error('Request failed:', error.message);
throw error;
}
}