How to get Subtitles from Youtube Videos with Free YouTube Subtitles API?

An Overview of Subtitles in YouTube Videos

When you watch YouTube videos, would you enable subtitles? Obviously, the subtitles can help attract foreign audiences and also let deaf viewers understand the content. However, have you thought it can also be a valuable data source? Especially for certain video genres on YouTube, like educational videos and speech videos, their subtitles can be a transcript worth extracting.

When you may want to get the Subtitles?

  • Get a transcript of a speech video
  • Get a transcript for academic writing reference
  • Turn a tutorial video into a reading supporting your learning
  • Get lyrics from music videos
  • Screening the content of videos

What is an API?

We all know that there are somethings we just don’t want do it manually. That’s where APIs come in. An API, or application programming interface, is a set of rules and specifications that allow two software programs to communicate with each other. Developers can build applications that work seamlessly together and make it possible for end-users to complete complex tasks with just a few clicks. By using an API, you can save yourself time and effort of having to write your own code from scratch. Let’s take a closer look at what an API is and how you can use it in your own development projects. If you want to know more about what an API is, check this link out.

For example, imagine being able to book a flight, hotel, and rental car all in one place by using just a few taps on your smartphone. This would not be possible without APIs! As the world becomes increasingly interconnected, the importance of well-designed APIs will only continue to grow.

What YouTube Subtitles API can do?

YouTube Subtitles API offers various functionalities for different use cases. Here are the major features.

1. Output Subtitles in all available languages without downloading via API

YouTube Subtitles API allows users to get the subtitles from a YouTube video in all available languages as long as the video maker has provided them. Users don’t even need to download it to their disks but get a simple JSON response.

2. Locate the Timestamps of Subtitles in the Video

Want to know when did the speaker of the video say the words? No worry. YouTube Subtitles API tells you when and what the video says.

Create a sample YouTube Subtitles API

Why should you choose this YouTube Subtitles API?

The YouTube Subtitles API is supported by OpenAPIHub, an All-in-one API Platform that supports API Needs and it is certified as “AWS Qualified Software” since 2022. You can register for an API portal for free, share and monetise APIs easily on the trustable platform certified by ISO27001.

Features

Using this tool, you can extract subtitles from a YouTube video.

Prerequisites

You will need a suitable API provider. Using YouTube Subtitles API, you can proceed easily as follows :

1. OpenAPIHub Developer Account

You need to sign up for an OpenAPIHub developer account in order to subscribe and access this API. For more information, please refer to “Register as a Developer“.

2. Active API Subscription

You need to subscribe to this API before consuming it. Many APIs come with a free trial plan so that you can experience the API functions provided free of charge. For more information, please refer to “Subscribe to APIs“.

3. API Credential

An API Key is required to access the API. It can be obtained in the Developer Admin Portal once you have completed the signup to OpenAPIHub. For more information, please refer to “Create API Key“.

Parameters

There are two parameters available in this API.

youtube_video_id: The id of the video you would like to get the subtitles from.

lang_index: The index of language of the subtitles you want to get.

You may check out the full API documentation here in the OpenAPIHub.

Create an attractive User Interface

We are here to guide you with detailed steps. Let’s get into the first part – creating a user interface for users to enter the YouTube video id.

Try this HTML yourself!

<div id="app">
  <div class="demo-description">
    <h2>Youtube Subtitles</h2>
    <span>To protect your credentials.</span>
    <br>
    <span>DO NOT save this API Key in the code sandbox!!</span>
  </div>
  <div class="test-area">
    <div class="input-area">
      <label for="api-key">API Key</label>
      <input
        id="api-key"
        type="text"
        placeholder="Input your key here"
        v-model="apikey"
      >
      <br>
      <label for="video-id">Video Id</label>
      <input type="text" 
        id="video-id" 
        placeholder="Input the video id here" 
        v-model="videoId"
      >
      <br>
      <template v-if="returnedSubtitles == true">
        <label for="language">Language</label>
        <select id="language" v-model="langIndex" v-html="availableLangs"/>
        <br>
      </template>
      <button v-on:click="downloadSubtitles">Get Subtitles</button>
    </div>
 
    <div class="output-area">
      <template v-if="error">
        <div v-html="error" />
      </template>
      <template v-else-if="!result">
        <div>
          Enter an API Key, Video Id, then press "Get Subtitles".
        </div>
      </template>
      <template v-else>
        <div v-html="result"/>
      </template>
    </div>
  </div>
</div>

Apply CSS on the user interface

After creating the basic structure to get user input for the parameters, we need to add the following CSS to decorate our UI to make it more attractive!

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap');
body {
  background: #20262E;
  padding: 20px;
  font-family: 'Open Sans', sans-serif;
}
 
#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
  height: 800px;
}
 
.demo-description {
  text-align: center;
  margin-bottom: 20px;
}
 
.demo-description h2 {
  font-weight: semibold;
  margin-bottom: 5px;
}
 
.demo-description span {
  color: #999999;
}
 
.test-area {
  display: flex;
}
 
.input-area {
  text-align: right;
}
 
.input-area label {
  display: inline-block;
  line-height: 48px;
  margin-right: 8px;
  text-align: right;
  width: 150px;
}
 
.input-area input[type="text"] {
  border: 1px solid #999999;
  border-radius: 3px;
  height: 30px;
  width: 150px;
  padding: 0 7px;
}

.input-area select {
  border: 1px solid #999999;
  border-radius: 3px;
  height: 30px;
  width: 166px;
  padding: 0 7px;
}

 
.input-area input::placeholder {
  color: #d0d0d0;
}
 
.input-area button {
  background-color: #57abf0;
  border: 0;
  border-radius: 4px;
  color: #ffffff;
  font-weight: 600;
  margin-top: 15px;
  width: 166px;
  padding: 15px 10px;
}

.input-area button:hover{
  background-color: #4281b5;
}

 
.output-area {
  color: #505050;
  font-size: 14px;
  margin-left: 20px;
  margin-right: 0px;
  padding-top: 5px;
  width: calc(100% - 360px);
  border: 2px solid #57abf0;
  border-radius: 5px;
}

.output-area div{
  margin: 5px;
  max-height: 370px;
  overflow: auto;
}
 
@media screen and (max-width: 616px) {
  .input-area {
    text-align: center;
  }

  .input-area label {
    text-align: left;
  }
   
  .input-area button {
    width: 140px;
    padding: 10px 7px;
  }
  
  .output-area {
    width: calc(100% - 150px);
  }
}

Create a sample YouTube Subtitles API with Vue.js

Now, you can add the following Vue.js script.

const basepath;

new Vue({
  el: '#app',
  data() {
    return {
      apikey: '',
   		videoId: '',
      langIndex: null,
      returnedSubtitles: false,
      availableLangs: '',
      result: '',
      error: ''
    }
  },
  methods: {
    downloadSubtitles: function() {
    	this.returnedSubtitles = false
    	this.error = ''
    	this.result = 'Loading...'
      const axiosConfig = {
        headers: {
          'content-type': 'application/json',
          'x-openapihub-key': this.apikey
        }
      };
      axiosConfig.params = {
        lang_index: this.langIndex
      }
      axios.get(basepath + '/yt-subtitles/' + this.videoId, axiosConfig)
        .then(res => {
        	this.error = ''
          let result = ""
          for(let subtitle of res.data.subtitles){
            result = result + subtitle.text + '<br>';
          }
          this.result = result
          this.returnedSubtitles = true
          let availableLangs = ''
          res.data.available_languages.forEach(lang=>{
          	availableLangs += `<option value="${lang.index}">${lang.lang}</option>`
          })
          this.availableLangs = availableLangs
        }).catch(err => {
          this.error = `Error occurred -<br>${err?.response?.data?.message ? err?.response?.data?.message : err}`
          console.log('Error', err?.response?.data?.message ? err?.response?.data?.message : err)
      })
    }
  }
})

Now that we have all the materials prepared. Let’s take a look at getting our first subtitles with our API. 

Simply fill in the Video Id and an API Key, then press “Get Subtitles”. Swiftly, you can get your very first subtitles from the YouTube Subtitles API.  

Sample output with video [Bon Jovi – It’s My Life]:
Error Responses

You might get some error responses under certain circumstances.

Example response with status 401 – Unauthorized

{"message":"Invalid authentication credentials"}

Example response with status 500 – Internal Server Error

{"message": "Internal server error"}

Supported response codes

  • 200 – OK
  • 401 – Unauthorized
  • 500 – Internal Server Error

Conclusion

Subtitles in YouTube videos contain important information that can be leveraged for different needs. By understanding how to create a YouTube Subtitles API, you can get subtitles from YouTube videos with easy-to-use YouTube Subtitles API for your business or any needs. In fact, there are various ways to create a YouTube Subtitles API. Here, we provided you the easiest way to do it. 

Next Steps?

Enjoy the above tutorial and want to learn of more useful API? Explore more on OpenAPIHub!

OpenAPIHub is an API Platform that help you define API subscription and enable API Monetization with ease. Check the following 2-min What is OpenAPIHub video for more and try OpenAPIHub for Free!

Ready to Start Your API Journey?

Join OpenAPIHub and connect to the fast growing API Hub Community to grow your API Business today!

Start for Free