If you are a movie buff, then you surely want to keep up with the upcoming movies, and their star cast. But if you are a movie trivia buff then you will need to get access to some online resources which has all the information about movies, their cast, crew, plots and other finer details.
Googling for movies conjures up images of the IMDB website. But it is always cluttered with movie details, reviews, and lots of other promos. IMDb has the world’s biggest repository of movies and TV shows from all countries. You can search the IMDb website and get details about movies, their casts, and more granular information about the crew, schedules, reviews, and other meta-information like plot summary and release dates.
But did you know that IMDB also offers an API?
What is the IMDb API?
An API is a web-based interface that can retrieve information from the Internet. Just like we type in the URL of a website to load its webpage on the browser, an API is called via its URL to fetch information, as per the APIs specification. The IMDb API can fetch all the information about movies and TV shows, that you can otherwise search from the IMDb website.
At RapidAPI, we are currently hosting quite a few APIs that are tailor-made for fetching information about movies, their casts, characters and more. So, instead of muddling through the IMDb website manually, why don’t we leverage the APIs.
Let’s write some code to combine an API with Python. In this blog post, we will show you how to quickly code a movie information search app in Python, with the help of one of the IMDb APIs hosted on the RapidAPI platform.
Before we proceed further, make sure that you subscribe to the RapidAPI account. It’s free and gives you a single API key to access thousands of APIs.
Which IMDB APIs to use at RapidAPI?
A quick search for “IMDb” on our website will list out quite a few APIs.
From the search results, the top two APIs (enclosed in a blue rectangle) are:
The Movie Database API is a simple API which can only search for movie name and retrieve their IMDb title ID. It does not provide detailed information about each movie.
The IMDb API offers the best choice in terms of the variety of information related to movies. It offers separate distinct API endpoints for fetching information about the crew, star cast, plot, characters, and a host of other information.
The IMDb API offers a Freemium subscription model with 500 free API calls per month. This is adequate for building a quick and easy movie search app.
Using IMDb API with Python
Now, that we have selected the right API, it’s time to fire up your python programming mojos.
Head over to the IMDb API console page on the RapidAPI website.
Click on the “Pricing” tab to take a look at the pricing plans. Subscribe to the BASIC plan, which gives you 500 API calls per month free.
On the right side of the console, you can see the API endpoints for querying specific information from IMDb.
Scroll down till you see the API endpoint title/find. Click on it and you can see the code snippet on the right to call this API. By default, the console may not show Python code snippet so you can choose from the dropdown next to the “Code Snippet” label and select “Python” > “unirest”.
Connect to this API using the movie search string “titanic” and you can see the listings with the IMDb title ID of the movie.
Great! So now your API subscription is working and you have tested one API endpoint. You also have the python code snippet to call the API.
With this, you are now ready to code the movie information search app.
How to Build your own Movie Search App in Python
To build this app, you will need:
- Your RapidAPI Subscription Key & Host Key
- You can get the keys from your API console page
- A computer with Python 2.7 environment
- Python unirest library
- To install unirest you can type the command “pip install unirest” under your python2 environment.
Follow along with the steps below to build the python program for movie search.
Step 1: Build the App Skeleton
To fetch data from the API, you have to import the unirest library and also define the RapidAPI related credentials as a constant.
import unirest unirest.timeout(15) # 5s timeout RAPIDAPI_KEY = "<YOUR_RAPIDAPI_SUBSCRIPTION_KEY>" RAPIDAPI_HOST = "<YOUR_RAPIDAPI_ENDPOINT>"
You must replace the placeholders <YOUR_RAPIDAPI_SUBSCRIPTION_KEY>
and <YOUR_RAPIDAPI_ENDPOINT>
with your subscription specific values.
Step 2: Look up the Movie Name
The next thing is to search for a movie. To search for a Movie name by string, you can call the “title/find” API endpoint as we tested it from the console.
However, before calling the API, you must prompt the user to enter a search string for the Movie name. Here is the python code for prompting the user.
while len(search_string) <= 2: search_string = raw_input("Enter the movie name to search: ")
You need to make sure that the user enters at least 2 characters, otherwise, the API will go for a spin and retrieve a lot of movie names.
Now, you can search for a Movie by invoking the “title/find” API endpoint.
def search_movie(search_keyword): response = unirest.get("https://imdb8.p.rapidapi.com/title/find?q="+search_keyword, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response
And then, you can retrieve the IMDb title id for the movie, its name, and release date.
main_response = search_movie(search_string) if(main_response.code == 200): if "results" in main_response.body: best_match = main_response.body["results"][0] movie_id = best_match["id"][7:-1] movie_title = best_match["title"] movie_year = str(best_match["year"])
For retrieving any movie information, you will need the movie_id
in future. This is a globally unique IMDb assigned title ID for each movie.
Step 3: Display the Movie Details
So what is the first thing that you ask when someone tells you about a new movie? The cast, plot, director? You can get all this information from the IMDb API as well.
Now in this last and concluding step, you will add additional API calls to the python program to display information about the main persons involved in a movie.
To get the details about the cast, you can call the endpoints
- title/get-top-cast
- title/get-charname-list
get-top-cast will return the name ids of the actors/actresses, from which you can deduce their names using the get-charname-list.
def search_cast(title_id): response = unirest.get("https://imdb8.p.rapidapi.com/title/get-top-cast?tconst=" + title_id, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response def search_character(movie_id,name_id): response = unirest.get("https://imdb8.p.rapidapi.com/title/get-charname-list?currentCountry=US&marketplace=ATVPDKIKX0DER&purchaseCountry=US&id=" + name_id + "&tconst=" + movie_id, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response
Here is how you will consume the data from these two endpoints to get the names of the cast.
cast_response = search_cast(movie_id) if(cast_response.code == 200): top_cast_id = cast_response.body[0:4] for cast_id in top_cast_id: char_response = search_character(movie_id,cast_id[6:-1]) if(char_response.code == 200): top_cast_name.append(char_response.body[cast_id[6:-1]]["name"]["name"]) else: print "Cannot fetch the star cast for " + movie_title
Finally, to get the names of the crew, including directors, writers, and others, you can call the
title/get-top-crew endpoint.
def search_crew(movie_id): response = unirest.get("https://imdb8.p.rapidapi.com/title/get-top-crew?tconst=" + movie_id, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response
The crew data is returned as a label along with its data. The label can represent a director or a writer of some other role. So, to retrieve this information, you have to create a dictionary and use the label as key and store all the names as values.
crew_response = search_crew(movie_id) if crew_response.code == 200: for crew,details in crew_response.body.items(): if len(details) > 0: for data in details: if(False == top_crew_name.has_key(crew)): top_crew_name[crew] = list() top_crew_name[crew].append(data["name"])
With this, you have a python based app that can search for movie names, and print out the essential information about a movie which best matches the search string.
Here is the complete program with variables to store the information retrieved from API and some error handling to take care of corner cases.
import unirest unirest.timeout(15) # 5s timeout RAPIDAPI_KEY ="<YOUR_RAPIDAPI_SUBSCRIPTION_KEY>" RAPIDAPI_HOST = "<YOUR_RAPIDAPI_ENDPOINT>" search_string = "" movie_id = "" movie_title = "" movie_year = "" top_cast_name = list() top_crew_name = dict() api_error = False def search_movie(search_keyword): response = unirest.get("https://imdb8.p.rapidapi.com/title/find?q="+search_keyword, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response def search_cast(title_id): response = unirest.get("https://imdb8.p.rapidapi.com/title/get-top-cast?tconst=" + title_id, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response def search_character(movie_id,name_id): response = unirest.get("https://imdb8.p.rapidapi.com/title/get-charname-list?currentCountry=US&marketplace=ATVPDKIKX0DER&purchaseCountry=US&id=" + name_id + "&tconst=" + movie_id, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response def search_crew(movie_id): response = unirest.get("https://imdb8.p.rapidapi.com/title/get-top-crew?tconst=" + movie_id, headers={ "X-RapidAPI-Host": RAPIDAPI_HOST, "X-RapidAPI-Key": RAPIDAPI_KEY, "Content-Type": "application/json" } ) return response def display_results(): if api_error == False: print "Movie Title: " + movie_title print "Release Year:" + movie_year print "n" print "Cast:" for name in top_cast_name: print name print "n" print "Crew:" for role,name in top_crew_name.items(): print role.capitalize() + " - " + ",".join(name ) else: print "API Error. Please try again later" if __name__ == "__main__": try: while len(search_string) <= 2: search_string = raw_input("Enter the movie name to search: ") print "Finding the best match for " + search_string + "... n" main_response = search_movie(search_string) if(main_response.code == 200): if "results" in main_response.body: best_match = main_response.body["results"][0] movie_id = best_match["id"][7:-1] movie_title = best_match["title"] movie_year = str(best_match["year"]) cast_response = search_cast(movie_id) if(cast_response.code == 200): top_cast_id = cast_response.body[0:4] for cast_id in top_cast_id: char_response = search_character(movie_id,cast_id[6:-1]) if(char_response.code == 200): top_cast_name.append(char_response.body[cast_id[6:-1]]["name"]["name"]) else: print "Cannot fetch the star cast for " + movie_title crew_response = search_crew(movie_id) if crew_response.code == 200: for crew,details in crew_response.body.items(): if len(details) > 0: for data in details: if(False == top_crew_name.has_key(crew)): top_crew_name[crew] = list() top_crew_name[crew].append(data["name"]) else: print "Unable to fetch crew data for " + movie_title api_error = True else: print "Unable to fetch the star cast for " + movie_title api_error = True display_results() else: print "Invalid request or error in response" api_error = True except Exception as e: print "Error" print e
Download the file here: imdb_search.py
Time to Search For Your Favourite Movies
Now that the program is ready, you can take it for a release.
So here’s our latest inhouse production from RapidAPI, starring IMDb API and Python.
Claps, please!!
You can go on and integrate other API endpoints to retrieve more information.
Conclusion
You have just scratched the surface of what’s possible with this App. As you can see in the list of endpoints, you can do more with the IMDb API.
So how about doing some data analysis on movies. Apart from fetching general information about movies, this API can also fetch you some datasets about awards, reviews and filming locations. You can get this data and do some cool analytics and visualization stuff which might give you some great insights. For example, you can get the most popular locations for shooting or histogram of user ratings.
The possibilities are endless and we hope this blog post has tickled your movie-obsessed brain cells to explore more. And we can’t wait to see what you build with this API.
Good luck and we are here to help, should you face any issues with accessing the APIs via RapidAPI.
Leave a Reply