Paulo Vivanco
Paulo Vivanco

Reputation: 1

How do I use the ombd API to iterate over a list of movie titles?

from omdbapi.movie_search import GetMovie

def get_movie_data(api_key, titles): movie_data = {} movie_api = GetMovie(api_key=api_key)

for title in titles:
    # Attempt to fetch the movie information
    try:
        result = movie_api.get_movie(title=title)
        
        # Check if movie details were found and the title matches the queried title
        if result and result.get('Response', 'False') == 'True' and result.get('Title') == title:
            movie_data[result.get('Title')] = result
    except GetMovieException as e:
        # Handle "Movie not found" exception
        print(f"Movie not found: {title}")
        continue
    except Exception as e:
        # Handle other exceptions
        print(f"Error querying title {title}: {e}")
        continue
        
return movie_data

api_key = 'api-key'

titles = [x for x in movie_data['title'].head(10)] # Adjust based on your actual data

movies_info = get_movie_data(api_key, titles)

print(movies_info)

Having issues iterating over a list of movies to obtain the information using the omdb API. Has anyone used this API before that can point me in the right direction?

I was expecting to get a dictionary of titles and movie information. However, when I iterate over the list of movies, I get the same information for all movies.

Upvotes: 0

Views: 258

Answers (1)

Bench Vue
Bench Vue

Reputation: 9320

I tested omdbapi library but It did not work when I ran it.

How about just call directly by requests library.

Get Movie

GET http://www.omdbapi.com/?t={movie title}&apikey={your API key}

Detail information in here

Demo

I will get three movies and save to JSON file with it's title name.

Save as demo.py

import requests
import json

def get_movie(title, api_key):
    base_url = 'http://www.omdbapi.com/'
    # Replace spaces in the title with '+'
    formatted_title = title.replace(' ', '+')
    params = {
        't': formatted_title,
        'apikey': api_key
    }
    
    response = requests.get(base_url, params=params)
    if response.status_code == 200:
        return response.json()
    else:
        return {'error': 'Failed to fetch data', 'status_code': response.status_code}

def save_movie_data(title, data):
    with open(f"{title}.json", "w") as f:
        json.dump(data, f, indent=4)

api_key = 'your API key'  # Replace with your actual API key
movie_titles = ['The Godfather', 'Interstellar', 'Toy Story']

for title in movie_titles:
    movie_data = get_movie(title, api_key)
    save_movie_data(title, movie_data)
    print(f"Data for '{title}' saved to '{title}.json'")

Run it

python demo.py

enter image description here

Result

enter image description here

Saved the Interstellar.json

{
    "Title": "Interstellar",
    "Year": "2014",
    "Rated": "PG-13",
    "Released": "07 Nov 2014",
    "Runtime": "169 min",
    "Genre": "Adventure, Drama, Sci-Fi",
    "Director": "Christopher Nolan",
    "Writer": "Jonathan Nolan, Christopher Nolan",
    "Actors": "Matthew McConaughey, Anne Hathaway, Jessica Chastain",
    "Plot": "When Earth becomes uninhabitable in the future, a farmer and ex-NASA pilot, Joseph Cooper, is tasked to pilot a spacecraft, along with a team of researchers, to find a new planet for humans.",
    "Language": "English",
    "Country": "United States, United Kingdom, Canada",
    "Awards": "Won 1 Oscar. 44 wins & 148 nominations total",
    "Poster": "https://m.media-amazon.com/images/M/MV5BZjdkOTU3MDktN2IxOS00OGEyLWFmMjktY2FiMmZkNWIyODZiXkEyXkFqcGdeQXVyMTMxODk2OTU@._V1_SX300.jpg",
    "Ratings": [
        {
            "Source": "Internet Movie Database",
            "Value": "8.7/10"
        },
        {
            "Source": "Rotten Tomatoes",
            "Value": "73%"
        },
        {
            "Source": "Metacritic",
            "Value": "74/100"
        }
    ],
    "Metascore": "74",
    "imdbRating": "8.7",
    "imdbVotes": "2,071,776",
    "imdbID": "tt0816692",
    "Type": "movie",
    "DVD": "24 May 2016",
    "BoxOffice": "$188,020,017",
    "Production": "N/A",
    "Website": "N/A",
    "Response": "True"
}

And other two json files too.

Upvotes: 0

Related Questions