DEV Community

Cover image for Creating a link shortener using Bitly's API (In simple steps)
Wonuola
Wonuola

Posted on

Creating a link shortener using Bitly's API (In simple steps)

Step 1: Create a Bitly account using this link Bitly sign up

Bitly's home page
Step 2: Just by the side bar, head over to settings.
Bitly's side nav
Step 3: Head over to developer settings to generate an
API token.

Bitly's dev settings
Step 4: Fill in your password to generate this token.
Bitly's dev settings
Step 5: Head over to VS Code.
Step 6: Install axios using

npm i axios --save
Enter fullscreen mode Exit fullscreen mode

Step 7:Create form component

<form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Enter a long URL"
          value=''
        />
        <button type="submit">Shorten</button>
      </form>
Enter fullscreen mode Exit fullscreen mode

Step 8: Create a state function for your URL values.
urlInput: This is the long URL the user wants to shorten.
urlOutput: This is the new shortened URL.

  const [urlInput, setUrlInput] = useState('');
  const [urlOutput, setUrlOutput] = useState('');

Enter fullscreen mode Exit fullscreen mode

Step 9: Create an asynchronous submit function

//(e) is an event handler that  
const handleSubmit = async (e) => {

    e.preventDefault(); // To prevent the button from submitting before the function runs, we add e.preventDefault.

//The try-catch function is to run the function smoothly and help us identify errors along the way
    try {
      const res = await axios.post(
        'https://api-ssl.bitly.com/v4/shorten', // the api link
        {
          long_url: urlInput // your url input state value
        },
        {
          headers: {
            'Content-Type': 'application/json',
            Authorization: 'YOUR_API_KEY/TOKEN'
          }
        }
      );
      setUrlOutput(res.data.link);
    } catch (error) {
      console.error(error);
    }
  };
Enter fullscreen mode Exit fullscreen mode

Step 10
a. Create a

for the newly generated API
{urlOutput && (
        <div>
          <p>Shortened URL:</p>
          <a href={urlOuput} target="_blank" rel="noopener noreferrer">
            {urlOutput}
          </a>
        </div>
      )}
Enter fullscreen mode Exit fullscreen mode

b. Update the values of the form

<form onSubmit={handleSubmit}>
        <input
          type="text"
          placeholder="Enter a long URL"
          value={urlInput}
          onChange={(e) => setUrlInput(e.target.value)}
        />
        <button type="submit">Shorten</button>
      </form>
Enter fullscreen mode Exit fullscreen mode

That's it!
You've created your url shortener with Bitly's API! Let me know what you think in the comments. Contributions and feedbacks are obviously welcome. Cheers ;)

Top comments (0)