Update tags using Hubspot API
Tags: javascript, hubl, hubspot, api
Published: 2021-08-19 10:13:35

Hello Dev.to community!

My name is Albert Soriano, I'm a Web Developer at Avast Software and this is my first Dev.to post. I hope some of you find it useful! 

Today I'm going to talk about **Hubspot tags** and how to **automatically tag articles** by using Hubspot's API.

For those who don't know what Hubspot tags are, here's what the documentation says:

> Tags allow you to manage your blog posts by subject. Once you've added tags to your posts, you can customize your templates to link to a feed of all posts by tag. You can also add a post filter module so visitors can filter posts by tag.

Adding tags is usually a **manual process** where content authors manually tag articles with a tag or with multiple tags. It's a very simple process in Hubspot, but what if you need to tag several articles at once? 

Tagging hundreds of articles manually is extremely time consuming, but luckily we can use **Hubspot's API to help us tagging articles automatically**.

The first thing you need to do is find the **ID of your new tag**. This is a bit tricky since Hubspot doesn't provide a clear way to get the tag ID, but you can find it using the API to list all your tags and their information (name, ID, etc.). 

To get the tag ID we will use Hubspot's **API test calls** to retrieve data from our tags.

### Go to the API documentation and run a test call

Test calls will require your API key. To get the API key, go to Hubspot, Settings, API key.

Now that you have the API key, go to Hubspot's API documentation ([here](https://developers.hubspot.com/docs/api/cms/blog-tags#endpoint?spec=GET-/cms/v3/blogs/tags)), find the "Get all Blog Tags" function and run it. 

The response should look like this:

![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z074p36c84hzx9s69qx2.png)

All you have to do is find your tag and **copy the ID**.

### Retrieve all blog posts from your Blog

There are many ways to approach this, but our second step in this process will be to **retrieve all blog posts from our Blog** and store them in an array. We will then update the tags of each blog and will call the API to update the information in Hubspot. 

To retrieve all blog posts and store them in our code, we will use the following code (all code can be found in [this repository](https://github.com/albertsg/hubspot-api-scripts/blob/master/scripts/tag-update.js)):


```javascript
function callApi(){


  var options = {
  method: 'GET',
    url: 'https://api.hubapi.com/cms/v3/blogs/posts',
    qs: {hapikey: accountKey, limit: limit, offset: offset},
    headers: {accept: 'application/json'}
  };


  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    const res = JSON.parse(response.body)
    const posts = res.results

    isEnd = posts.length === 300 ? false : true

    posts.forEach(element => {
      offset++
      //Add here any filtering options you want. For example, now I select the blogs to update based on the URL as I have different domains in my account. Feel free to change this logic to something that suits better your needs
      if(element.url.includes(domainURL)){
        blogs.push(element)
      }
    });
      
    checkIfFurtherNeeded();

  });
}
```

The previous code will store our all blog posts into the *blogs* array. Then it will run the function *checkIfFurtherNeeded()* that will check if there are still blogs to process or if it can start updating tags.

It's important to mention that in this example I'm filtering the blogs by URL as I have different domains in my account. The API will return **all** blog posts in my account, but it doesn't mean that I have to update them all, I can **filter** the blogs according to some logic and update only the ones I need.

### Update tags in blog posts

Once we have all our blog posts, it's time to add the **new tag to the tag list**. To do that, we can use the following code:

```javascript
/**
 * updateHubTags Evaluates is a blog post includes the tag to be added and calls the function to do it
 */
function updateHubTags() {
  blogs.forEach(post =>{
    if(!post.tagIds.includes(newTagId)){
      UpdateTag(post)
    } 
  }) 
}


/**
 * UpdateTag Executes a call to Hubspot's API en processes the data
 * @param  {Object} blog This object includes the information of the blog post where we will add the tag
 */
function UpdateTag(blog){

  //Update a blog post
  var request = require("request");
  
  blog.tagIds.push(newTagId) //Add new tag to the array of tag

  var options = {
    method: 'PATCH',
    url: `https://api.hubapi.com/cms/v3/blogs/posts/${blog.id}`,
    qs: {hapikey: accountKey},
    headers: {accept: 'application/json', 'content-type': 'application/json'},
    body: {
      tagIds: blog.tagIds
    },
    json: true
  };

  request(options, function (error, response, body) {
    if (error) throw new Error(error);

    console.log(`Article ${blog.htmlTitle} updated`);
  });
}
```

And that's all! With the code above you will be able to automatically tag your blog posts with a specific tag, saving a lot of time to content authors.

Here are some things to keep in mind:

* The variable _accountKey_ should include your API key.
* Keep in mind that Hubspot's requests return only 300 elements (but code above solves it by doing a request several times until all blog posts are obtained).
* You can filter the blogs as you want. In the example above I filter the blogs by URL because I have different domains in the same account.

All the code can be found in my Github account:

{% github albertsg/hubspot-api-scripts %}

Feel free to contribute to the code, I'm sure it can be optimized in many different ways!