Exploring the shrtcode API with JavaScript

Shrtcode is a URL shortener service that provides an API which you can use to integrate the functionality of their service into your own web app or website. In this blog, we will explore their API and learn how to use it with JavaScript.

Signing Up and Getting an API Key

Before we proceed, we will need to sign up and obtain an API key from shrtcode. To do this, follow these simple steps:

  1. Go to https://shrtco.de/docs
  2. Scroll down the page until you find the API Key section and click the Create a new API key button.
  3. Enter your email address and click the Submit button.
  4. Check your email inbox for a new message from shrtcode. The email should contain your new API key.

With your API key in hand, let's dive into some JavaScript code and start using the shrtcode API.

Shortening a URL

The most basic functionality of the shrtcode API is to shorten a URL. Here is an example code snippet on how to achieve that using the fetch method in JavaScript:

const apiKey = 'YOUR_API_KEY_HERE';
const url = 'https://example.com/';

fetch(`https://api.shrtco.de/v2/shorten?url=${url}`, {
    headers: {
        'Content-Type': 'application/json',
        'apikey': apiKey
    }
}).then(response => response.json())
  .then(data => {
      console.log(data.result.full_short_link2);
  });

In the code above, we make a fetch call to the shrtcode API's shorten endpoint and pass in the URL we want to shorten. We also pass in our apiKey in the header to authenticate the API request. Finally, we parse the JSON response and log the shortened URL.

Retrieving Shortened Links

Once you have shortened a URL with the shrtcode API, you can retrieve its details by using the info endpoint. Here is an example code on how to retrieve the details of a shortened link:

const apiKey = 'YOUR_API_KEY_HERE';
const shortCode = 'shortCodeHere';

fetch(`https://api.shrtco.de/v2/info?code=${shortCode}`, {
    headers: {
        'Content-Type': 'application/json',
        'apikey': apiKey
    }
}).then(response => response.json())
  .then(data => {
      console.log(data.result.original_link);
  });

In the code above, we pass in the shortCode of the shortened link that we want to retrieve the details of. We also use our apiKey again to authenticate the API request.

Conclusion

In this blog post, we explored how to use the shrtcode API with JavaScript to shorten URLs and retrieve details of shortened links. With these examples, you can integrate shrtcode into your own web app or website and provide a URL shortener service to your users.

Related APIs in URL Shorteners