tips / javascript
How to Use the TMDb API
Last Update : February 09, 2023
What is API
API(Application Programming Interface) is a set of defined rules that enable different applications to communicate with each other.
For example, you can display Instagram posts with Instagram API.
What is TMDb
TMDb is Web API that provides data base for movies and TV series. You can use the data like movie poster, cast and staff informations, reviews. It requires an account but it’s free.
Create an account
Create an account on Sign up page .
After registered, open the Settings page from profile icon on the right of window.
Click the API menu on side menu, and then you can send request for Request an API Key.
After approved, you will get API Key, API Read Access Token. And you can check keys on API page.
How to get data from API
Use fetch()
method to get data from API. (Check the Browser compatibility )
Here’s the basic fetch()
usage.
fetch('http://sample.com/sample.json')
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log('error');
});
Create a display page with JavaScript
Let’s see how to display a list of movies in theatres.
Source & Demo(CodeSandbox)
Create div
to display data.
<div id="app"></div>
Put data to console with TMDb API Key. You can change the language and regions with language=xx
and region=xx
.
fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=<ここにAPI Key入れる>&language=en-US®ion=US&page=1')
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log('error');
});
If it succeed, you can see data on console.
Get more details with map()
method. In this demo, it displays title and poster. Use map()
method to data.results
.
Pass the title and poster path to createItem()
(you can create on the next step).
data.results.map(movie => {
createItem(movie.title, movie.poster_path);
});
Here’s the code for display data.
const container = document.getElementById('app');
const createItem = (titleName, imgPath) => {
const row = document.createElement('div');
row.setAttribute('class', 'item');
const title = document.createElement('p');
title.setAttribute('class', 'title');
title.textContent = titleName;
const poster = document.createElement('img');
poster.src = `https://image.tmdb.org/t/p/w300_and_h450_bestv2/${imgPath}`;
container.appendChild(row);
row.appendChild(poster);
row.appendChild(title);
};
It shows titles and posters 🚀
References
- Tania Rascia「How to Use the JavaScript Fetch API to Get JSON Data」(参照2019-08-23
- Tania Rascia「How to Connect to an API with JavaScript」(参照2019-08-23)
- クロジ「映画ブログ作りました」, <https://nanokamo.com/kinematos>(参照2017-09-30)