What is an API
An API (Application Programming Interface) allows applications to comunnicate, share data.
For example, you can display Instagram posts on your website using the “Instagram API”.
What is TMDB
TMDB is a community built movie and TV database.
It provides an API that let you to fetch movie titles, posters, cast and crew data, ratings, and more. Creating an an account is required, but it’s free.
Creating an Account
You can create an account here: Sign up for an account .
Once you’ve signed up, open Profile and Settings > Settings
from the profile icon on the top-right corner.
On the Setting page, go to sidebar and click “API”. Scroll down to “Request an API Key” to apply.
Once approved, you will get an API Key and an API Read Access Token, which you can check anytime on the API setting page .
How to Fetch Data from TMDB API
You can use JavaScript Fetch API fetch()
to retrieve.
Here’s a basic fetch()
example:
fetch("http://sample.com/sample.json")
.then((response) => {
return response.json();
})
.then((data) => {
// handle fetched JSON data
console.log(data);
})
.catch((error) => {
console.log("error");
});
Displaying Data on a Page
As a sample, let’s display “Now Playing” movies.
Add a div
in your index.html with an id app
.
<div id="app"></div>
Next, update your fetch URL with the TMDB API endpoint and your API Key.
A single request returns 20 movies. To fetch data in a different language, change language=en-US
. To specify region, change region=JP
.
fetch(
"https://api.themoviedb.org/3/movie/now_playing?api_key=<YOUR_API_KEY>&language=en-US®ion=US&page=1"
)
...
If successful, you’ll see data in the console.
Now, let’s display titles and poster images using map()
. The data is storaged under data.results
.
data.results.map((movie) => {
createItem(movie.title, movie.poster_path);
});
Here’s an example function to render movies:
/** get div to display movies */
const container = document.getElementById("app");
/** function to create DOM elements */
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);
};
Check your browser - if titles and posters are displayed, it’s working 🎉
Conclusion
You can see more API on TMDB API Guides page.
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)](https://nanokamo.com/kinematos%5D(https://nanokamo.com/kinematos)%EF%BC%88%E5%8F%82%E7%85%A72017-09-30%EF%BC%89>)