Last active
April 19, 2021 19:32
-
-
Save willy-r/3a0b30735f3b6d70cb0b4ac5d34dfdfd to your computer and use it in GitHub Desktop.
How to get some details of a movie using TMDB API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://www.themoviedb.org/ | |
from pprint import pprint | |
import requests | |
def get_json(path, **params): | |
url = f'https://api.themoviedb.org/3/{path}' | |
all_params = {'api_key': 'your_api_key'} | params | |
try: | |
r = requests.get(url, params=all_params) | |
except requests.exceptions.RequestException: | |
print('Houve algum problema com a requisição.') | |
return | |
else: | |
return r.json() | |
def get_movies_per_page(movie_name, page=1, quantity_per_page=20): | |
data = get_json('search/movie', language='pt-BR', include_adult='false', page=page, query=movie_name) | |
if not data: | |
return | |
if data['total_results']: | |
movies = [ | |
[movie['title'], movie['original_title'], movie['id']] | |
for movie in data['results'][:quantity_per_page] | |
] | |
return movies | |
else: | |
print('Este filme não foi encontrado.') | |
return | |
def get_movie_details(movie_id): | |
data = get_json(f'/movie/{movie_id}', language='pt-BR', append_to_response='credits') | |
if not data: | |
return | |
credits = data['credits'] | |
return { | |
'title': data['title'], | |
'original_title': data['original_title'], | |
'release_year': data['release_date'].split('-')[0], | |
'director': [member['name'] for member in credits['crew'] | |
if member['job'] == 'Director'][0], | |
'cast': [member['name'] for member in credits['cast']][:10], | |
'poster': f'https://image.tmdb.org/t/p/w154{data["poster_path"]}' | |
} | |
def main(): | |
movie_name = input('Nome do filme: ') | |
movies = get_movies_per_page(movie_name) | |
if movies: | |
print('\nEscolha o ID de um dos filmes abaixo:') | |
pprint(movies) | |
movie_id = input('Digite o ID do filme: ') | |
if movie_id not in [str(movie[2]) for movie in movies]: | |
print('Digite um ID de filme válido.') | |
else: | |
movie_details = get_movie_details(movie_id) | |
if movie_details: | |
pprint(movie_details, width=100, sort_dicts=False) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment