Fetch TMDB movie data using Python

Hey! Everyone I’m glad to see you here, hope you all are doing well. This post is going to be an interesting one for you and I hope it’ll fulfill your expectation after reading it. For fetching TMDB movie data we have two ways to do it first using RESTful APIs or second using tmdbv3api.

In this post, I’ll explain to you how you can

  • Fetch TMDB(The Movie Database) movie data from using RESTful APIs in Python. (Using only requests module)
  • Fetch TMDB(The Movie Database) movie data using tmdbv3api library.

So let’s start.

TMDB(The Movie Database):

So before going into the coding part let me first explain TMDB. TMDB(The Movie Database) is a community movie and TV database where you can find all the data regarding any movie or TV show. It came in 2008 and since then TMDB has become a greater source of metadata. You can find information about people, movies, and TV shows here, and a thousand fine-grained movie posters. So now maybe you’re thinking about what is the purpose of this TMDB here so let me explain to you using TMDB you can extract all the information about movies and TV shows using an API(Application Programming Interface) key which is provided to you by TMDB free of cost and I hope you know already about API. If you don’t know browse it and you can find more about it. So I hope you get a good idea about TMDB.

Now let’s suppose as a developer you want to access details about some popular movies using coding or you want to develop an application related to movies for your organization and how you will do that, so let’s get started. It’s an easy one.

Fetching TMDB movie data using RESTful API in Python:

Let us understand what is a RESTful API. It is an interface that two autonomous computer systems use to exchange information amongst themselves. I visited the TMDB website to get an API key for myself. You also need to Sign up yourself to get your own curated API key.

Follow these links:-

Register an account: https://www.themoviedb.org/account/signup

Check how you can get your unique API: https://developers.themoviedb.org/3/getting-started/introduction

So I hope now you have set up your system for the coding part and have access to your unique API key. 

Code:

import requests
from pprint import pprint

url = "https://api.themoviedb.org/3/discover/movie/" 

api_key = "YOUR_TMDB_API_KEY"

response = requests.get(url, params = {'api_key' : api_key})

json_data = response.json()

pprint(json_data)

I have used the request module to enable myself to request data from the TMDB server. Check out our blog on Send GET and POST requests in Python to know more about the requests module. As I want to retrieve data on all popular movies I’ve used the URL to that page, https://api.themoviedb.org/3/discover/movie/. I have stored my API key in a temporary variable, api_key. I have used the get method to get the movie data. The arguments for the method are my URL and the params field which takes my unique API key.

Output:-

Fetch TMDB movie data using Python

The response variable returns a dictionary of the JSON data.  I’ve pretty printed the dictionary which contains details on the popular movies using pprint module.

Fetch the release date from

Now, let’s retrieve the release date of every movie. You can refer to our How to parse JSON in python to learn more on this topic.

Code:-

Release_data = json_data['results']

for i in range(0, len(Release_data)):
    print(Release_data[i]['release_date'])

Now that I know that my JSON object contains two values: pages and results. As I’m interested in getting the release dates of the movies, I made a list of the results of the JSON object with the name, Release_data. I’ve used a for loop with a starting value of 0 and an end value as the length of the list variable Release_data, to iterate over each movie which is stored in the form of a dictionary. To get the release date I’ve subscripted the list as Release_data[i]['release_date'] this value returns me the release date value of the ith movie in the list Release_data.

Output:-

release date from tmdb api python

Thus you can now fetch any information from the TMDB movie data.

Search for a particular movie:-

Now that you know how to fetch all and particular information from the TMDB API. Let us look at how you can search for a particular movie using the REST API.

Code:-

import requests
from pprint import pprint

base_url = "https://api.themoviedb.org/3" 

api_key = "YOUR_TMDB_API_KEY"

input_Str = input("Movie's name : ")

url = f"{base_url}/search/movie?api_key={api_key}&query={input_Str}"
response = requests.get(url)

json_data = response.json()

pprint(json_data)

In the above code, I have taken the name of the movie you want to search for as an input and stored it in a temporary variable, input_Str. I have also curated the URL here by formatting a string, where I’ve given my api_key’s value in the api_key parameter and the query parameter’s value as input_Str, the name of the movie you want to search for.  I have used the get method to get the JSON object from the URL. Now I’ve used the json function to convert the JSON object to a dictionary and print the same.

Output:-

Search for a particular movie

I have given the input_Str value as Avengers and got the details on all movies that have the word ‘Avengers’ in them.

Fetching TMDB movie data using tmdb3api

Here I’ll explain to you using the tmdbv3api Python library. Since maybe you don’t have some experience with REST before it it’ll become typical for you.

tmdbv3api:-

tmdbv3api is a Python library using which you can work with TMDB and access any information from TMDB while creating your application in Python. 

You can install the tmdbv3api library using pip install tmdbv3api and in order to work with it, you need to install it, so before going ahead install it using this above command on your development environment.

And before going with the coding part you also need to Register your account to get your API key from TMDB.

Follow these links:-

Register an account: https://www.themoviedb.org/account/signup

Check how you can get your unique API: https://developers.themoviedb.org/3/getting-started/introduction

So I hope now you have set up your system for the coding part and have access to your unique API key

from TMDB copy it somewhere you’ll need it.

So, now let’s start with the coding part. I used Jupyter Lab as my id:- 

#Python program for fetching TMDB movie data
#after installing our library we'll import or initialize TMDB and Movie object
from tmdbv3api import TMDb
from tmdbv3api import Movie
tmdb=TMDb()
#set you unique API key that you get from TMDB after registartion in my case this is my API key
TMDb.api_key='6f15568d9aa3d15d0261a5454578c28b'
#you can also export your api key as environment variable using this below export command
# export TMDb_API_KEY='6f15568d9aa3d15d0261a5454578c28b'
#it's optional it's for setting language of Data that we'll fetch from TMDB
tmdb.language = 'en'
#for debugging we have set it true 
tmdb.debug = True
movie=Movie()
#here I have fetched movie data using movie_id 
similar = movie.similar(343611)
#iterate through the data since it have multiple information
for s in similar:
    #print required data like in my case title of movie and it's overview, poster path
    print("Title of the movie: ", s.title)
    print("Overview of the movie:", s.overview)
    print("Poster of the Movie:", s.poster_path)
    #it will give us all movie data which have similar id=343611
#you can also fetch movies using other methods also like popular(), recommendation() etc.

Output:-

Below is the output of the above code:

Title of the movie:  Detachment
Overview of the movie: A chronicle of three weeks in the lives of several high school teachers, administrators and students through the eyes of substitute teacher, Henry Barthes. Henry roams from school to school, imparting modes of knowledge, but never staying long enough to form any semblance of sentient attachment.
Poster of the Movie: /2uvZbXzhd3bMakRXiZpO1Kd6Ho3.jpg
Title of the movie:  Paranormal Activity 3
Overview of the movie: In 1988, young sisters Katie and Kristi befriend an invisible entity who resides in their home.
Poster of the Movie: /9nYranPiWdNmbD5PRPPSL7VUFTS.jpg
Title of the movie:  American Reunion
Overview of the movie: The characters we met a little more than a decade ago return to East Great Falls for their high-school reunion. In one long-overdue weekend, they will discover what has changed, who hasn’t, and that time and distance can’t break the bonds of friendship.
Poster of the Movie: /de5QBIdVR4dnkBZ4a0zjkS4lTg.jpg
Title of the movie:  World War Z
Overview of the movie: Life for former United Nations investigator Gerry Lane and his family seems content. Suddenly, the world is plagued by a mysterious infection turning whole human populations into rampaging mindless zombies. After barely escaping the chaos, Lane is persuaded to go on a mission to investigate this disease. What follows is a perilous trek around the world where Lane must brave horrific dangers and long odds to find answers before human civilization falls.
Poster of the Movie: /1SWBSYJsnyhdNRfLI1T6RsCxAQ4.jpg
Title of the movie:  The Hunger Games
Overview of the movie: Every year in the ruins of what was once North America, the nation of Panem forces each of its twelve districts to send a teenage boy and girl to compete in the Hunger Games.  Part twisted entertainment, part government intimidation tactic, the Hunger Games are a nationally televised event in which “Tributes” must fight with one another until one survivor remains.  Pitted against highly-trained Tributes who have prepared for these Games their entire lives, Katniss is forced to rely upon her sharp instincts as well as the mentorship of drunken former victor Haymitch Abernathy.  If she’s ever to return home to District 12, Katniss must make impossible choices in the arena that weigh survival against humanity and life against love. The world will be watching.
Poster of the Movie: /iQK0pkTQC60XR3Zlu2pp8kujoqW.jpg
Title of the movie:  The Human Centipede 2 (Full Sequence)
Overview of the movie: Inspired by the fictional Dr. Heiter, disturbed loner Martin dreams of creating a 12-person centipede and sets out to realize his sick fantasy.
Poster of the Movie: /2cMTX2BQVJDZfFlnPL5dDstmLfz.jpg
Title of the movie:  Jack Reacher
Overview of the movie: When a gunman takes five lives with six shots, all evidence points to the suspect in custody. On interrogation, the suspect offers up a single note: "Get Jack Reacher!" So begins an extraordinary chase for the truth, pitting Jack Reacher against an unexpected enemy, with a skill for violence and a secret to keep.
Poster of the Movie: /zlyhKMi2aLk25nOHnNm43MpZMtQ.jpg
Title of the movie:  What's Your Number?
Overview of the movie: Ally Darling is realizing she's a little lost in life. Her latest romance has just fizzled out, and she's just been fired from her marketing job. Then she reads an eye-opening magazine article that warns that 96 percent of women who've been with 20 or more lovers are unlikely to find a husband. Determined to turn her life around and prove the article wrong, Ally embarks on a mission to find the perfect mate from among her numerous ex-boyfriends.
Poster of the Movie: /e2PcyjS9oBaMR7rV2DUJ1yY1gKX.jpg
Title of the movie:  The Great Gatsby
Overview of the movie: An adaptation of F. Scott Fitzgerald's Long Island-set novel, where Midwesterner Nick Carraway is lured into the lavish world of his neighbor, Jay Gatsby. Soon enough, however, Carraway will see through the cracks of Gatsby's nouveau riche existence, where obsession, madness, and tragedy await.
Poster of the Movie: /nimh1rrDDLhgpG8XAYoUZXHYwb6.jpg
Title of the movie:  Colorful
Overview of the movie: Upon reaching the train station to death, a dejected soul is informed that he is lucky and will have another chance at life. He is placed in the body of a 14-year-old boy named Kobayashi Makoto, who has just committed suicide. Watched over by a neutral spirit named Purapura, the soul must figure out what his greatest sin and mistake in his former life was, before his time limit in Makoto's body runs out. He also has a number of other lesser duties he must complete, such as understanding what led Makoto to commit suicide in the first place and learning how to enjoy his second chance at life.
Poster of the Movie: /aSM1ki4WSEgvPYMZ9K28aylImFF.jpg
Title of the movie:  Paranormal Activity: Tokyo Night
Overview of the movie: This Japan production spins-off the story of the first Paranormal Activity film by having the ghost from the first film follow a student back to her homeland after a visit to San Diego where she is tragically injured during a car accident. Back home in Japan, she is cared for by her brother, Koichi, who begins to suspect that something is amiss when his sister's wheelchair begins to move on its own. From there, the picture takes on the usual candid cam shocks of the series. Tokyo Night is notable for being an official part of the franchise (it was released in Japan two days before Paranormal Activity 2's release in the States), even though the U.S. has yet to see an official release.
Poster of the Movie: /mh7j7XlYWo82UnQGhsxcuyolzp.jpg
Title of the movie:  Midnight in Paris
Overview of the movie: A romantic comedy about a family traveling to the French capital for business. The party includes a young engaged couple forced to confront the illusion that a life different from their own is better.
Poster of the Movie: /4wBG5kbfagTQclETblPRRGihk0I.jpg
Title of the movie:  Jackass 3.5
Overview of the movie: Johnny Knoxville of 'Jackass' releases unused material of stunts, tricks, antics and shenanigans shot during the production of 'Jackass 3D' that didn't make it into the film, as well as the hilarious outtakes.
Poster of the Movie: /1dXigjDk1XTmwVBtKEB422LxgS.jpg
Title of the movie:  Exploits of a Young Don Juan
Overview of the movie: Roger is a 16-year-old who seeks to lose his virginity in this softcore erotic drama. His initial efforts are unsuccessful, but World War I breaks out and men are seen marching off to battle. Roger goes overboard when he is presented with several amorous opportunities.
Poster of the Movie: /kjj3cpffTly4LzmLS84OrFfCcYh.jpg
Title of the movie:  Piranha 3DD
Overview of the movie: After the events at Lake Victoria, the prehistoric school of blood-thirsty piranhas make their way into swimming pools, plumbing, and a newly opened water park.
Poster of the Movie: /mv2Ej9WPVWivNvtMTTxgb07c7N9.jpg
Title of the movie:  Hostel: Part III
Overview of the movie: Set in Las Vegas, the film centers on a man who attends his best friend's bachelor party, unaware of an insidious agenda that plays into hunting humans.
Poster of the Movie: /v7B0Ap0fyaSpEkacqHlIIis90jG.jpg
Title of the movie:  We Need to Talk About Kevin
Overview of the movie: After her son Kevin commits a horrific act, troubled mother Eva reflects on her complicated relationship with her disturbed son as he grew from a toddler into a teenager.
Poster of the Movie: /auAmiRmbBQ5QIYGpWgcGBoBQY3b.jpg
Title of the movie:  Terminator Genisys
Overview of the movie: The year is 2029. John Connor, leader of the resistance continues the war against the machines. At the Los Angeles offensive, John's fears of the unknown future begin to emerge when TECOM spies reveal a new plot by SkyNet that will attack him from both fronts; past and future, and will ultimately change warfare forever.
Poster of the Movie: /oZRVDpNtmHk8M1VYy1aeOWUXgbC.jpg
Title of the movie:  How to Train Your Dragon 2
Overview of the movie: Five years have passed since Hiccup and Toothless united the dragons and Vikings of Berk. Now, they spend their time charting unmapped territories. During one of their adventures, the pair discover a secret cave that houses hundreds of wild dragons -- and a mysterious dragon rider who turns out to be Hiccup's mother, Valka. Hiccup and Toothless then find themselves at the center of a battle to protect Berk from a power-hungry warrior named Drago.
Poster of the Movie: /d13Uj86LdbDLrfDoHR5aDOFYyJC.jpg
Title of the movie:  The Host
Overview of the movie: A parasitic alien soul is injected into the body of Melanie Stryder. Instead of carrying out her race's mission of taking over the Earth, "Wanda" (as she comes to be called) forms a bond with her host and sets out to aid other free humans.
Poster of the Movie: /ok2sl6rGITZ0W94DeRU4VkB2ssW.jpg

Thank You. I hope you have enjoyed this post and learned a lot from it. 

You can also check:  Python JSON Encoder and Decoder

If you like this post comment on it.

Leave a Reply

Your email address will not be published. Required fields are marked *