Code Examples
Examples of how to use the Shortify API in different programming languages.
Creating and Retrieving Links
The following examples demonstrate how to create a new shortened link and then retrieve it using the API.
// Example using Node.js with fetch
const apiKey = 'your_api_key_here';
const baseUrl = 'https://shortify.com/api/mobile';
// Create a new link
async function createLink() {
try {
const response = await fetch(`${baseUrl}/link/create`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': apiKey
},
body: JSON.stringify({
url: 'https://example.com',
slug: 'my-custom-slug',
tags: ['example', 'documentation'],
comments: 'Created from API documentation example'
})
});
const data = await response.json();
if (!data.success) {
throw new Error(`Error: ${data.error.message}`);
}
console.log('Link created:', data.data);
return data.data;
} catch (error) {
console.error('Failed to create link:', error);
throw error;
}
}
// Retrieve a link
async function getLink(shortLink) {
try {
const response = await fetch(`${baseUrl}/link?shortLink=${shortLink}`, {
method: 'GET',
headers: {
'api-key': apiKey
}
});
const data = await response.json();
if (!data.success) {
throw new Error(`Error: ${data.error.message}`);
}
console.log('Link retrieved:', data.data);
return data.data;
} catch (error) {
console.error('Failed to retrieve link:', error);
throw error;
}
}
// Usage example
async function main() {
try {
const newLink = await createLink();
const retrievedLink = await getLink(newLink.key);
console.log('Link clicks:', retrievedLink.clicks);
} catch (error) {
console.error('Error in main function:', error);
}
}
main();