Reminder: If you haven’t already signed up for an API Key from Rebrandly, please read our Rebrandly URL Shortener API article. Keep in mind, while it’s ok to use your API key in these exercises, you should not share your key with anyone (not even if asking a question in the forums)!

In this exercise, you’ll be making a POST request to the Rebrandly API to shorten a URL.

Get ready! You’re now going to incorporate the previous lesson’s boilerplate code into making an actual POST request!

If you reset the exercise at any point, you will have to paste in your API key again at the top.



Copy your Rebrandly API Key, and assign it to the const apiKey at the top of your code.


Within the code block of shortenUrl(), create a const called urlToShorten, and save inputField.value to it. urlToShorten will now save the value of the input field

Note: for the remainder of this exercise’s instructions we will be working inside the code block of shortenUrl()!


Create a const called data, and save the following code to it:

JSON.stringify({destination: urlToShorten});

We’re including this information because the API expects to see an object with a key destination that has a value of a URL.


Create a new XMLHttpRequest object using the new operator, and save it to a const called xhr.


Set the responseType property of the xhr object to be 'json'.


Save an empty anonymous arrow function to the onreadystatechange event handler of the xhr object. This function will not take in any parameters.

Inside the anonymous function’s code block, include the following code inside of its code block:

if (xhr.readyState === XMLHttpRequest.DONE) { renderRawResponse(xhr.response); }

The renderRawResponse function can be viewed at public/helperFunctions.js.


Below the anonymous function you just created, call the .open() method on xhr, and pass it 'POST' and url as respective arguments.


To access the Rebrandly API, we need a header with two key-value pairs. In the header, you must include values for 'Content-type' and an 'apikey'.

To set the header, we have to include the following code below our .open() method.

xhr.setRequestHeader('Content-type', 'application/json'); xhr.setRequestHeader('apikey', apiKey);

On xhr, call the .send() method, and pass it data as an argument.


Enter this URL into the input field, and click the shorten button in the web page.


Notice the object that came back!

Now replace renderRawResponse(xhr.response) with renderResponse(xhr.response). Run the code.

Paste the URL again and click “Shorten”.

Isn’t it much cleaner?

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?