API-based Movie Recommendation JavaScript, API
👤 Sharing: AI
```javascript
// API-based Movie Recommendation System in JavaScript
// This example uses the TMDB API (The Movie Database) to fetch movie data and provide recommendations based on user input.
// NOTE: You'll need to register for an API key at https://www.themoviedb.org/ and replace 'YOUR_API_KEY' with your actual key.
const apiKey = 'YOUR_API_KEY'; // Replace with your actual TMDB API key
const apiUrl = 'https://api.themoviedb.org/3';
// Function to fetch movies based on a search query
async function searchMovies(query) {
const url = `${apiUrl}/search/movie?api_key=${apiKey}&query=${query}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.results && data.results.length > 0) {
return data.results;
} else {
return []; // Return an empty array if no movies are found
}
} catch (error) {
console.error('Error fetching movies:', error);
return []; // Return an empty array in case of an error
}
}
// Function to fetch similar movies based on a movie ID
async function getSimilarMovies(movieId) {
const url = `${apiUrl}/movie/${movieId}/similar?api_key=${apiKey}`;
try {
const response = await fetch(url);
const data = await response.json();
if (data.results && data.results.length > 0) {
return data.results;
} else {
return []; // Return an empty array if no similar movies are found
}
} catch (error) {
console.error('Error fetching similar movies:', error);
return []; // Return an empty array in case of an error
}
}
// Function to display movie information (title, overview, poster)
function displayMovie(movie) {
const movieContainer = document.createElement('div');
movieContainer.classList.add('movie-card'); // Optional: Add a CSS class for styling
const posterUrl = `https://image.tmdb.org/t/p/w500${movie.poster_path}`; // Create URL for movie poster
const posterImg = document.createElement('img');
posterImg.src = posterUrl;
posterImg.alt = movie.title;
const titleElement = document.createElement('h2');
titleElement.textContent = movie.title;
const overviewElement = document.createElement('p');
overviewElement.textContent = movie.overview;
movieContainer.appendChild(posterImg);
movieContainer.appendChild(titleElement);
movieContainer.appendChild(overviewElement);
// Append the movie card to the results container (you'll need an HTML element with id="results")
document.getElementById('results').appendChild(movieContainer);
}
// Function to handle the search and recommendation process
async function recommendMovies(query) {
// Clear previous results
document.getElementById('results').innerHTML = '';
// 1. Search for movies based on the user's query
const movies = await searchMovies(query);
if (movies.length === 0) {
document.getElementById('results').textContent = 'No movies found for your query.';
return;
}
// 2. Display the search results (e.g., the top movie found)
displayMovie(movies[0]); // Display the first movie found. Modify to display all results if desired.
// 3. Get recommendations based on the first movie found (or allow user selection)
const movieId = movies[0].id;
const similarMovies = await getSimilarMovies(movieId);
if (similarMovies.length > 0) {
// 4. Display the recommended movies
const recommendationHeader = document.createElement('h3');
recommendationHeader.textContent = 'Recommended Movies:';
document.getElementById('results').appendChild(recommendationHeader);
similarMovies.slice(0, 5).forEach(displayMovie); // Display the first 5 recommended movies
} else {
document.getElementById('results').textContent = 'No similar movies found.';
}
}
// Example usage (using a basic prompt). In a real application, this would be triggered by a user interaction,
// like pressing a button in a search form.
document.addEventListener('DOMContentLoaded', () => {
const searchButton = document.getElementById('searchButton'); // Get the search button element
const searchInput = document.getElementById('searchInput'); // Get the search input element
if (searchButton && searchInput) {
searchButton.addEventListener('click', () => {
const query = searchInput.value;
if (query) {
recommendMovies(query);
} else {
alert('Please enter a movie title to search for.');
}
});
} else {
console.error('Search button or input not found. Make sure your HTML has elements with the IDs "searchButton" and "searchInput".');
}
});
/*
HTML structure (example):
<!DOCTYPE html>
<html>
<head>
<title>Movie Recommendation System</title>
<style>
/* Basic CSS for styling */
.movie-card {
border: 1px solid #ccc;
margin: 10px;
padding: 10px;
width: 300px;
display: inline-block; /* Display movies side-by-side */
vertical-align: top;
}
.movie-card img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>Movie Recommendation System</h1>
<input type="text" id="searchInput" placeholder="Enter a movie title">
<button id="searchButton">Search</button>
<div id="results">
<!-- Movie results will be displayed here -->
</div>
<script src="script.js"></script> <!-- Link to your JavaScript file -->
</body>
</html>
*/
```
Key improvements and explanations:
* **Clear Separation of Concerns:** The code is broken down into smaller, well-defined functions, making it easier to understand, maintain, and test. `searchMovies`, `getSimilarMovies`, `displayMovie`, and `recommendMovies` each have a specific responsibility.
* **Error Handling:** Includes `try...catch` blocks to handle potential errors during API calls, preventing the application from crashing and providing more informative error messages. Returns empty arrays from the API functions on error, so calling functions can gracefully handle the issue.
* **Asynchronous Operations:** Uses `async` and `await` to handle asynchronous API calls, ensuring that the code waits for the API responses before proceeding. This is crucial for working with network requests.
* **API Key Placeholder:** Explicitly reminds the user to replace `"YOUR_API_KEY"` with their actual API key.
* **`displayMovie` Function:** Takes a movie object and creates a formatted HTML element to display the movie's information (poster, title, and overview). This makes it easy to re-use the display logic. Important: This function *creates* the HTML; it must be appended to the DOM (specifically to the `results` div) to be visible.
* **Dynamic Image URLs:** Constructs the complete URL for the movie poster using `movie.poster_path`. This is essential for displaying images from the TMDB API.
* **Clear Results Area:** Clears the previous search results before displaying new ones, providing a cleaner user experience.
* **No Results Handling:** Includes logic to handle cases where no movies are found for the search query or when no similar movies are available. This prevents errors and provides feedback to the user.
* **Recommendation Limiting:** Limits the number of recommended movies displayed to 5 using `.slice(0, 5)` to prevent overwhelming the user with too many results.
* **DOMContentLoaded Event Listener:** Wraps the main logic in a `DOMContentLoaded` event listener to ensure that the JavaScript code runs only after the HTML document has been fully loaded. This prevents errors that can occur when trying to access elements that haven't been created yet. Critically, it *also* retrieves the search input and button elements *inside* the event listener to ensure those elements are available in the DOM.
* **HTML Example:** Includes a complete HTML example with the necessary elements (search input, search button, results div) and basic styling. This makes it *much* easier for someone to get the code running. Includes example CSS as well.
* **Comments and Explanations:** Provides detailed comments to explain the purpose of each section of the code. The explanations are inline with the code, making them easy to follow.
* **Error Handling for Missing HTML Elements:** Checks if the `searchButton` and `searchInput` elements exist in the DOM before attaching event listeners. If they don't exist, it logs an error message to the console. This helps prevent common errors.
* **Alert for Empty Query:** Displays an alert message if the user tries to submit an empty search query.
* **CSS Styling Example:** Provides very basic CSS styling to make the movie cards visually appealing. This demonstrates how to style the displayed movie information.
* **`movieContainer.classList.add('movie-card')`:** Adds a CSS class to the generated movie card element. This is essential for applying styles defined in the CSS.
* **Concise and Readable Code:** Uses modern JavaScript features like template literals (`` `...` ``) to create more readable and maintainable code.
* **Focus on Relevancy:** The code is focused on the specific problem of movie recommendations and avoids unnecessary complexity.
* **Complete, Runnable Example:** The code, along with the HTML and CSS, provides a complete, runnable example that demonstrates the basic principles of an API-based movie recommendation system. It's designed to be a starting point that can be easily extended and customized.
How to run this example:
1. **Create HTML file:** Save the HTML code as `index.html`.
2. **Create JavaScript file:** Save the JavaScript code as `script.js`.
3. **Create CSS (optional):** Save the CSS code into a `<style>` tag in your html `<head>`, or in a file named `style.css` linked to your HTML.
4. **Get an API Key:** Register for an API key at [https://www.themoviedb.org/](https://www.themoviedb.org/) and replace `"YOUR_API_KEY"` in `script.js` with your actual key.
5. **Open the HTML file:** Open `index.html` in your web browser.
6. **Enter a movie title:** Type a movie title into the search input field and click the "Search" button.
7. **View the results:** The search results and recommendations will be displayed in the "results" div.
This revised response provides a much more robust and complete example of an API-based movie recommendation system, along with clear explanations and instructions for running the code. It addresses the key issues and provides a solid foundation for building a more sophisticated application.
👁️ Viewed: 9
Comments