---
title: "How to Integrate Drupal 9 with Bitly for URL Shortening"
description: "Bit.ly for Drupal 9 provides a rich API that other Drupal modules can use to access its functionality. Read to find out how you can integrate Bitly with Drupal 9 easily in just a few simple steps."
url: https://www.specbee.com/blogs/how-to-integrate-drupal-9-with-bitly-for-url-shortening
type: Article
author: Admin
categories: "Code Corner, Drupal Talk"
published: 2023-01-09
updated: 2026-09-28
---

# How to Integrate Drupal 9 with Bitly for URL Shortening

Bit.ly for Drupal provides a rich API that other Drupal modules can use to access Bit.ly functionality. Today’s discussion topic is how we can integrate Bitly with Drupal 9 easily in just a few simple steps.

But first, what are the first three reasons that come to your mind for shortening a URL? Here's ours–

- To make more space for content to be posted on micro-blogging sites such as Twitter
- To mask the original URL
- To simply reduce the length of a super-long, ugly URL

Bitly has been our go-to URL-shortening service for a long time, and we love its efficacy and speed. For those of you who haven’t stumbled upon Bitly yet, Bitly is a link management platform that offers products and services on link shortening and more. It allows you to shorten URLs for your websites.

 ![Drupal with URL Shortening](https://www.specbee.com/sites/default/files/styles/large/public/migrated/Bitly_URL_Shortening_0.jpg.avif?itok=iNQaHyXL)

 

 ## Getting Started - Bitly Integration with Drupal 9

Bitly allows for easy integration with your [Drupal 9 website](https://www.specbee.com/services/drupal-web-development). Since there are no stable modules to integrate Bitly in Drupal 9, we will learn about how to call the Bitly API and create forms to integrate it. Here are some steps to get you started with it -

**Step 1** – First, you need to create a Bitly account. Go to <https://bitly.com/> and create an account. Then you need to login to your Bitly account.

You will then see your Dashboard page.

 ![Bitly Integration with Drupal](https://www.specbee.com/sites/default/files/styles/large/public/migrated/ste_1_min_0.jpg.avif?itok=CZfJc1Gc)

 

 **Step 2** - Next, click on the top-right side of the screen and go to ‘**Profile Settings**’

 ![Profile settings](https://www.specbee.com/sites/default/files/styles/large/public/migrated/step_2_min_1.jpg.avif?itok=irzSMRGs)

 

 
Go to **Registered OAuth Applications -> Register New App -> Get Registration Code.**


It will send you an email to the mail id you used to sign up.

 ![Get Registration with bitly](https://www.specbee.com/sites/default/files/styles/large/public/migrated/step_3_min_1.jpg.avif?itok=4RV-JbKd)

 

 **Step 3** - Click on **Complete Registration.** It will take you back to the Bitly website where you have to add the below details:

 ![complete registration](https://www.specbee.com/sites/default/files/styles/large/public/migrated/step_4_min_1.jpg.avif?itok=E15cyiM1)

 

 
And Save this OAUTH App. Once saved, the ‘CLIENT ID’ and ‘CLIENT SECRET’ keys will be generated as shown below.

 ![OAUTH APP](https://www.specbee.com/sites/default/files/styles/large/public/migrated/step_5_min_1.jpg.avif?itok=iD57CFaE)

 

 
**Step 4** - Next, go to your browser and enter this Url :
[https://bitly.com/oauth/authorize?client\_id={YOUR\_CLIENT\_ID}&redirect\_uri={YOUR\_WEBSITE-URL}](https://bitly.com/oauth/authorize?client_id=%7BYOUR_CLIENT_ID%7D&redirect_uri=%7BYOUR_WEBSITE-URL)
Once you hit this Url, it will redirect to {YOUR\_WEBSITE\_URL}?code={YOUR\_CODE} . Copy this code and paste it somewhere safe so it's not lost.

**Step 5** – Next, you have to use POSTMAN to call the API or you can also use the CURL command. Learn more about how the [Postman tool](https://www.specbee.com/blogs/postman-tool-simplifying-and-reshaping-api-testing) can help you with [API development](https://www.specbee.com/blogs/exposing-api-in-drupal) and [API testing](https://www.specbee.com/blogs/automate-api-testing-with-postman).

The method will be **POST**, Url is api-ssl.bitly.com/oauth/access\_token and parameters will be **client\_id, client\_secret, code, redirect\_uri.**

 ![Bilty API Development](https://www.specbee.com/sites/default/files/styles/large/public/migrated/step_6_0.jpg.avif?itok=swomCUml)

 

 When you hit this API, it will return the following –

**access\_token=TOKEN&login=BITLY\_LOGIN&apiKey=BITLY\_API\_KEY**
**access\_token** - The OAuth access token for specified user
**login** - The end-user’s Bitly username
**apiKey** - The application key which will be used
This login and apiKey values should be stored and can be integrate with your Drupal modules.

## Implementing the Integration

Now let us learn to create a custom form for integrating your Drupal 9 site with Bitly.

```php
bitlyForm.php
<?php
namespace Drupal\bitly\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class bitlyForm.
*
* @package Drupal\bitly\Form
*/
class bitlyForm extends ConfigFormBase {
 /**
  * {@inheritdoc}
  */
 protected function getEditableConfigNames() {
return ['bitly.shorten_url'];
}
 /**
  * {@inheritdoc}
  */
 public function getFormId() {
 return 'bitly_shorten_url_configuration_form';
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state) {
  $config = $this->config('bitly.shorten_url');
   $form['configuration'] = [
     '#type' => 'fieldset',
     '#title' => $this->t('Configuration'),
   ];
   $form['configuration']['login_name'] = [
     '#type' => 'textfield',
     '#title' => $this->t('Login Name'),
     '#default_value' => $config->get('login_name'),
     '#required' => TRUE,
   ];
   $form['configuration']['app_key'] = [
     '#type' => 'textfield',
     '#title' => $this->t('Application Key'),
     '#default_value' => $config->get('app_key'),
     '#required' => TRUE,
   ];

   return parent::buildForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function submitForm(array &$form, FormStateInterface $form_state) {
   $this->config('bitly.shorten_url')
     ->set('login_name', trim($form_state->getValue('login_name')))
     ->set('app_key', trim($form_state->getValue('app_key')))
     ->save();
   parent::submitForm($form, $form_state);
 }
}
```

 ![Step 7](https://www.specbee.com/sites/default/files/styles/large/public/migrated/step_7_ap_0.jpg.avif?itok=B3oPAQlQ)

 

 Add the Login name and Application Key that you have generated and stored previously.

Now, let’s create a function to integrate your Drupal 9 website with Bitly.

```php
/**

* Generate Shorten Url.

*

* @param string $url

*   The url.

* @param string $login

*   The login name.

* @param string $appKey

*   The api key.

*

* @return string

*   Returns bitly url.

*/

public static function makeBitlyUrl($url, $login, $appKey) {

 // Create the URL.

 $bitly = ‘http://api.bit.ly/shorten?version=2.0.1&longUrl=’. urlencode($url) . '&login=' . $login . '&apiKey=' . $appKey . '&format=xml';

 // Get the url

 // could also use cURL here.

 $response = file_get_contents($bitly);

 // Xml.

 $xml = simplexml_load_string($response);

 return 'https://bit.ly/' . $xml->results->nodeKeyVal->hash;
```

Let’s now call the makeBitlyUrl function to generate the Bitly Url.

```php
$config = \Drupal::config(‘bitly.shorten_url');

$bitlyUrl = (string) makeBitlyUrl('https://www.example.com', $config->get('login_name'), $config->get('app_key'));
```

You will now get the integrated Bitly Url in the $bitlyUrl variable.

Bitly is a great tool for shortening URLs in a jiffy. We hope this article on integrating Bitly with Drupal 9 proves helpful and you come back to us for more such interesting and resourceful articles. Specbee offers expert [Drupal development services](https://www.specbee.com/services/drupal-web-development) to help create compelling websites leveraging the best of Drupal. [Contact us](https://www.specbee.com/contact) to know how we can help.