How To Fetch and Display Movie List Using TMDB API

Yoatam Mussie
4 min readFeb 24, 2024

--

What Is API?

APIs (Application Programming Interfaces) serve as the backbone of modern software development, acting as intermediaries that enable different applications, systems, or services to communicate and interact with each other seamlessly. It is simply a set of rules, protocols, and tools that allow one piece of software to interact with another. It defines the methods and data formats that applications can use to request and exchange information, abstracting away the underlying complexities and providing a standardized interface for developers to work with.

How A Simple API Works

How To Fetch Data Using API?

JavaScript provides powerful built-in features for making HTTP requests and fetching data from APIs. This capability allows developers to integrate external data sources into their web applications dynamically. Here’s a step-by-step guide on how to fetch data from an API using JavaScript:

STEP 1. Choose an API: Select the API you want to fetch data from.

const apiKey = 'YOUR_API_KEY';

STEP 2. Understand the API Documentation: Before fetching data, carefully read the documentation provided by the API provider. It typically includes information about the available endpoints, request methods, query parameters, authentication requirements, and response format.

Documentation: https://developers.themoviedb.org/3/getting-started/introduction

STEP 3. Use the Fetch API: JavaScript provides the Fetch API, which offers a modern way to make network requests. You can use fetch() to send HTTP requests and handle responses asynchronously.

async function fetchMovieData() {
try {
const response = await fetch(`https://api.themoviedb.org/3/movie/popular?api_key=${apiKey}`);

STEP 4. Handle the response: Once the response is received, you can handle it appropriately. This may involve parsing the JSON response, checking for errors, and using the data retrieved.

if (!response.ok) {
throw new Error('Failed to fetch movie data');
}

const data = await response.json();

STEP 5. Use the fetched data: After parsing the data, you can use it to update your website or perform any other operations as needed.

STEP 6. Error Handling: Handle potential errors gracefully by checking the response status and handling rejected promises. This ensures that your website remains strong even when API requests fail.

catch (error) {
console.error('Error fetching movie data:', error.message);

Here is an example of an API being used to fetch data from TMDB API:

<script>
// API key for accessing themoviedb API
const apiKey = '3d1cb94d909aab088231f5af899dffdc';

// DOM element for displaying movie cards
const movieContainer = document.getElementById('movie-container');

// DOM element for the modal body
const modalBody = document.getElementById('modalBody');

// Function to fetch popular movies using the API
function fetchMovies() {
fetch(`https://api.themoviedb.org/3/movie/popular?api_key=${apiKey}`)
.then(response => response.json())
.then(data => {
// Check if results exist
if (data.results) {
// Loop through results and create movie cards
data.results.forEach(movie => movieContainer.appendChild(createMovieCard(movie)));
}
})
.catch(error => console.error('Error fetching movies:', error));
}

// Function to create a movie card
function createMovieCard(movie) {
// Create column for the card
const cardCol = document.createElement('div');
cardCol.className = 'col-md-2 mb-4 mx-5';

// Create card element
const card = document.createElement('div');
card.className = 'movie-card card';

// Create image element for the card
const img = createImage(movie);
img.addEventListener('click', () => showMovieDetailsModal(movie));

// Create card body
const cardBody = document.createElement('div');
cardBody.className = 'card-body';

// Create title element
const title = createTextElement('h5', 'card-title', movie.title);

// Create release date element
const releaseDate = createTextElement('p', 'card-text', `Release Date: ${movie.release_date}`);

// Append title and release date to card body
cardBody.appendChild(title);
cardBody.appendChild(releaseDate);

// Append image and card body to card
card.appendChild(img);
card.appendChild(cardBody);

// Append card to column
cardCol.appendChild(card);

return cardCol;
}

// Function to create an image element
function createImage(movie) {
const img = document.createElement('img');
// Set image source
img.src = movie.poster_path ? `https://image.tmdb.org/t/p/w200/${movie.poster_path}` : 'https://via.placeholder.com/200';
// Set alternate text
img.alt = `${movie.title} Poster`;
img.className = 'card-img-top';
// Set modal attributes
img.setAttribute('data-toggle', 'modal');
img.setAttribute('data-placement', 'top');
img.setAttribute('data-content', movie.overview);
return img;
}

// Function to create a text element
function createTextElement(tag, className, text) {
const element = document.createElement(tag);
element.className = className;
element.textContent = text;
return element;
}

// Function to show movie details modal
function showMovieDetailsModal(movie) {
// Clear existing content in modal body
while (modalBody.firstChild) {
modalBody.removeChild(modalBody.firstChild);
}

// Create new content in modal body
modalBody.appendChild(createTextElement('h2', 'h4', movie.title));
modalBody.appendChild(createTextElement('p', 'p', `Overview: ${movie.overview}`));
modalBody.appendChild(createTextElement('p', 'p', `Release Date: ${movie.release_date}`));
modalBody.appendChild(createTextElement('p', 'p', `Vote Average: ${movie.vote_average}`));
modalBody.appendChild(createTextElement('p', 'p', `Popularity: ${movie.popularity}`));

// Show the modal
$('#detailsModal').modal('show');
}

// Call fetchMovies function to load movies on page load
fetchMovies();
</script>

Conclusion

Fetching data from APIs using JavaScript opens up a world of possibilities for creating dynamic and interactive websites. By following the steps outlined above and leveraging the Fetch API, you can seamlessly integrate external data sources into your projects and enhance the user experience.

--

--