[IMAD] TMDB API 사용법 정리

NCOOKIE·2023년 6월 8일
3

IMAD 프로젝트

목록 보기
3/11

TMDB API 문서 링크

TMDB API란

Welcome to version 3 of The Movie Database (TMDB) API. This is where you will find the definitive list of currently available methods for our movie, tv, actor and image API.

The Movie Database (TMDB) API v3는 영화, TV 프로그램, 배우, 그리고 이미지 API 등에 대한 메소드들을 제공하고 있다. 사이트를 조금 살펴봤는데, 영화, 드라마, 다큐, 애니메이션 등 특정 장르에 국한되지 않고 대부분의 영상물 정보를 찾아볼 수 있는 것으로 보인다. 그리고 해외 서비스인 것 치고 한글화(로컬라이징) 부분에서 적극적이어서 이 API를 선택하게 되었다. 최종적으로 이 API를 사용하게 된 이유는 이전 포스팅 참고바란다.


API 키 발급받기

API 키를 등록하기 위해서는 TMDB에 회원가입 후 계정 설정 페이지에서 API 키를 발급받자. API를 적용할 어플리케이션의 정보와 주소, 연락처 등을 써야하지만 따로 검수 없이 바로 발급되니, 간단하게 적어두어도 괜찮을 것 같다. 다만 추후 API를 영리 목적으로 사용할 예정이라면 TMDB 측에 검수를 받아야하므로 그 때 가서 자세하게 작성해야 하지 않나 싶다.

기본적으로 오픈 API이지만, 상업적으로 사용하게 될 경우 사이트 측과 상의하여 비용을 지불해야 한다. API 이용약관에서 살펴볼 수 있듯이, 광고를 포함하여 상업용 목적의 서비스 개발은 별도로 TMDB 사에 문의하여 API 이용에 대해 문의해야 한다.

Your site is a "destination" site that uses TMDB content to drive traffic and generate revenue.

해당 API를 사용하여 사이트에 트래픽을 “유도”한다는 점에서 서비스에 광고를 붙여서 수익을 얻는 것도 상업적 목적으로 분류되는 것 같다.

A. RULES AND RESTRICTIONS
If the primary purpose of your application is to derive revenue, it is considered a commercial application. TMDB reserves the right to make these evaluations at the time that you apply for the license. TMDB may also monitor your site or application over time to ensure continued compliance with the appropriate type of API key.

If you're in doubt about whether your application is commercial, here are a few common examples of commercial use that may provide you some guidance:

Users are charged a fee for your product or a 3rd party's product or service or a 3rd party's service that includes some sort of integration using the TMDB APIs.
You sell services using TMDb's APIs to bring users' TMDB content into your service.
Your site is a "destination" site that uses TMDB content to drive traffic and generate revenue.
Your site generates revenue by charging users for access to content related to TMDB content such as movies, television shows and music.


API 속도 제한

과거에는 10초 당 요청 수 40으로 제한하는 등의 조건이 있었지만, 비활성화 되었다가 최근에는 초당 50개 근처에서 제한을 두고 있는 것 같다. 다만 이는 사이트 측의 사정에 따라 언제든지 변경될 수 있다. 만약 응답 코드로 429를 받았다면 허용 제한 넘은 것이므로, API 요청 수를 줄이는 방법을 고려하거나 사이트 측에 문의하여 유료로 이용하는 방법도 있다.


API 사용법

Append To Response

append to response는 최상위 네임스페이스에 추가 요청을 추가하는 쉽고 효율적인 방법이다. 영화, TV 쇼, TV 시즌, TV 에피소드 및 인물 상세 메소드 모두 append_to_response라는 쿼리 메소드 파라미터를 지원한다.

예를 들어, 어떤 영화의 상세 정보와 영상을 원한다고 해보자. 보통 아래와 같이 두 개의 요청을 날릴 것이다.

https://api.themoviedb.org/3/movie/157336?api_key=88365cf6bdc6c46015bf85c731dfab8f
https://api.themoviedb.org/3/movie/157336/videos?api_key=88365cf6bdc6c46015bf85c731dfab8f

그러나 append_to_response를 사용하면 단일 요청으로 처리할 수 있다.

https://api.themoviedb.org/3/movie/157336?api_key=88365cf6bdc6c46015bf85c731dfab8f&append_to_response=videos,images

여러 개의 요청의 값들을 콤마로 구분하여 사용할 수도 있다.

https://api.themoviedb.org/3/movie/157336?api_key=88365cf6bdc6c46015bf85c731dfab8f&append_to_response=videos,images

Finding Data

TMDB에서 영화, 티비쇼, 그리고 인물들에 대해 검색하기 위해서는 3가지 방법이 있다.

텍스트 기반의 검색으로, 가장 일반적인 방법이다. 요청 시 query string와 함께 보내면 TMDB 측에서 가장 근접한 검색 결과를 제공해준다. 텍스트 검색은 원본, 번역, 대체 이름과 제목 모두 가능하다.

/discover

등급, 인증 또는 출시 날짜와 같은 정의 가능한 값이나 필터를 기반으로 영화 및 TV 프로그램을 검색할 때 사용한다.

/find

TMDB 내부에 저장되어 있는 작품 또는 인물 등의 ID 값을 알고 있을 때 사용한다.

Languages

TMDB는 가능한 한 현지화(로컬라이징)를 하려고 노력하지만, 배우와 배역(캐릭터) 이름은 여기에서 제외된다. 추후 지원 예정이라고는 하지만 당장은 기대하기 어렵기 때문에 애플리케이션에서 별도의 조치를 취해야 할 것으로 보인다. 이를 위해 DB에 is_translated 칼럼을 추가할 예정이다.

Images

작품과 인물 관련 이미지의 URL을 만들기 위해서는 base_url, file_size, file_path 이렇게 3가지의 데이터가 필요하다. base_url과 file_size는 /configuration AIP를 통해서 정보를 받아올 수 있고, file_path는 API에 request를 날렸을 때 응답 데이터에 담겨 있는 정보를 사용하면 된다.

TMDB API Configuration

configuration API에서 받아올 수 있는 데이터는 다음과 같다. 여기서 우리가 쓸 것은 iamges에 있는 size 데이터들이다. 이렇게 3가지에 데이터를 적절히 조합해서 사용하면 우리가 원하는 이미지 파일을 불러올 수 있다.

{
  "images": {
    "base_url": "http://image.tmdb.org/t/p/",
    "secure_base_url": "https://image.tmdb.org/t/p/",
    "backdrop_sizes": [
      "w300",
      "w780",
      "w1280",
      "original"
    ],
    "logo_sizes": [
      "w45",
      "w92",
      "w154",
      "w185",
      "w300",
      "w500",
      "original"
    ],
    "poster_sizes": [
      "w92",
      "w154",
      "w185",
      "w342",
      "w500",
      "w780",
      "original"
    ],
    "profile_sizes": [
      "w45",
      "w185",
      "h632",
      "original"
    ],
    "still_sizes": [
      "w92",
      "w185",
      "w300",
      "original"
    ]
  },
  "change_keys": [
    "adult",
    "air_date",
    "also_known_as",
    "alternative_titles",
    "biography",
    "birthday",
    "budget",
    "cast",
    "certifications",
    "character_names",
    "created_by",
    "crew",
    "deathday",
    "episode",
    "episode_number",
    "episode_run_time",
    "freebase_id",
    "freebase_mid",
    "general",
    "genres",
    "guest_stars",
    "homepage",
    "images",
    "imdb_id",
    "languages",
    "name",
    "network",
    "origin_country",
    "original_name",
    "original_title",
    "overview",
    "parts",
    "place_of_birth",
    "plot_keywords",
    "production_code",
    "production_companies",
    "production_countries",
    "releases",
    "revenue",
    "runtime",
    "season",
    "season_number",
    "season_regular",
    "spoken_languages",
    "status",
    "tagline",
    "title",
    "translations",
    "tvdb_id",
    "tvrage_id",
    "type",
    "video",
    "videos"
  ]
}

예시

세 가지 요소들을 결합하여 다음과 같은 사진을 얻어올 수 있다. 이 사진은 <<인생은 아름다워>>라는 영화의 Guido Orefice 역을 연기한 Roberto Benigni라는 배우의 프로필 사진이다. 위의 configuration에서 base_urlprofile_sizes에 있는 w185, 그리고 영화 details에서 가져온 file_path를 결합한 URL을 사용하였다.

http://image.tmdb.org/t/p/w185/noelOhwX1oaNSvU9NLKhPrHTFI3.jpg

Countries

Countries

TMDB에서 사용하는 국가명 약어와 한글이름 데이터를 정의해둔 API이다. 고정값이므로 클라이언트에 저장해뒀다가 써도 될 것 같다.

Certifications

국가별 시청 등급을 확인할 수 있으며 MOVIE와 TV 두 개의 종류가 있다.

영화 시청등급

"KR": [
  {
    "certification": "All",
    "meaning": "Film suitable for all ages.",
    "order": 0
  },
  {
    "certification": "12",
    "meaning": "Film intended for audiences 12 and over. Underage audiences accompanied by a parent or guardian are allowed.",
    "order": 1
  },
  {
    "certification": "15",
    "meaning": "Film intended for audiences 15 and over. Underage audiences accompanied by a parent or guardian are allowed.",
    "order": 2
  },
  {
    "certification": "18",
    "meaning": "No one under 18 is allowed to watch this film.",
    "order": 3
  },
  {
    "certification": "Restricted Screening",
    "meaning": "Film needs a certain restriction in screening or advertisement as it is considered a highly bad influence to universal human dignity, social value, good customs or national emotion due to excessive expression of nudity, violence, social behavior, etc. (technically not an age restriction but films with this rating may only be screened at \"adults only\" theatres, with the age of majority set at 19).",
    "order": 4
  }
]

TV 시청등급

"KR": [
  {
    "certification": "Exempt",
    "meaning": "This rating is only for knowledge based game shows; lifestyle shows; documentary shows; news; current topic discussion shows; education/culture shows; sports that excludes MMA or other violent sports; and other programs that Korea Communications Standards Commission recognizes.",
    "order": 1
  },
  {
    "certification": "ALL",
    "meaning": "This rating is for programming that is appropriate for all ages. This program usually involves programs designed for children or families.",
    "order": 2
  },
  {
    "certification": "7",
    "meaning": "This rating is for programming that may contain material inappropriate for children younger than 7, and parental discretion should be used. Some cartoon programming not deemed strictly as ",
    "order": 3
  },
  {
    "certification": "12",
    "meaning": "This rating is for programs that may deemed inappropriate for those younger than 12, and parental discretion should be used. Usually used for animations that have stronger themes or violence then those designed for children, or for reality shows that have mild violence, themes, or language.",
    "order": 4
  },
  {
    "certification": "15",
    "meaning": "This rating is for programs that contain material that may be inappropriate for children under 15, and that parental discretion should be used. Examples include most dramas, and talk shows on OTA (over-the-air) TV (KBS, MBC, SBS), and many American TV shows/dramas on Cable TV channels like OCN and OnStyle. The programs that have this rating may include moderate or strong adult themes, language, sexual inference, and violence. As with the TV-MA rating in North America, this rating is commonly applied to live events where the occurrence of inappropriate dialogue is unpredictable. Since 2007, this rating is the most used rating for TV.",
    "order": 5
  },
  {
    "certification": "19",
    "meaning": "This rating is for programs that are intended for adults only. 19-rated programming cannot air during the hours of 7:00AM to 9:00AM, and 1:00PM to 10:00PM. Programmes that receive this rating will almost certainly have adult themes, sexual situations, frequent use of strong language and disturbing scenes of violence.",
    "order": 6
  }
]

API 사용 예시

개요

TMDB에서 작품을 구분할 때에는 크게 두 가지로 분류한다. 하나는 Movie, 그리고 나머지 하나는TV Series이다. 참고로 드라마, 다큐멘터리, 애니메이션 등이 TV Series에 해당한다. 사람들이 많이 보는 일본 애니메이션 같은 경우 TVA판과 극장판이 있는데, TVA는 TV Series, 극장판은 Movie로 분류된다.

TMDB <<귀멸의 칼날>> 검색결과 - 영화

TMDB <<귀멸의 칼날>> 검색결과 - TV Series

최근 OTT 시장이 활성화되고 자체적으로 작품을 제작/개봉하는 경우가 많아져서 영화관에서 보면 영화, TV로 보면 드라마. 이렇게 구분하는게 애매해져서 헷갈린다. 이 둘을 구분짓는건 이 프로젝트에서 그렇게 중요한 내용은 아닌 것 같아 링크를 첨부하고 대충 넘어가겠다.

드라마랑 영화랑 뭐가 달라요?

Movie 데이터

TMDB API - Movie - Details

Movie의 details 데이터를 API로 요청했을 때 어떤 정보들이 날라오고, 그 중에서 파싱해서 사용할지 알아보자. 헤더에 위에서 발급받았던 API 키 값을 넣어주고 API 주소(https://api.themoviedb.org/3/movie/637)에 request를 날려보자. 뒤에 붙어있는 쿼리문은 credits(제작 참여자 정보: 배우, 감독, 작가, 기타 스태프 등 포함) 정보들을 함께 불러오고 지원 언어는 한국어로 요청한다는 뜻이다.

API REQUEST 예시 <<인생은 아름다워>>

curl --request GET \
     --url 'https://api.themoviedb.org/3/movie/637?append_to_response=credits&language=ko-kr' \
     --header 'Authorization: Bearer {{API_KEY_VALUE}}' \
     --header 'accept: application/json'

추출해서 사용할 데이터

request를 날릴 때 append_to_responsecredits을 추가했으므로 배우와 스태프 관련 정보들도 함께 받을 수 있다. 이 중에서 배우와 감독 정보는 각각 별도의 데이터베이스에 저장하여 사용할 예정이다. 둘 모두 작품(art_work) 테이블과 M:N 관계를 갖는다. 자세한 내용은 다음 DB 설계 포스팅에서 설명하겠다.

[영화 정보]
title (제목)
original_title (원제)
original_language (원어)
genre (장르)
tagline (간단소개)
overview (개요)
poster_path (포스터 이미지)
production_countries (제작 국가)

release_date (개봉일)
status (개봉 여부)
runtime (상영시간)

[감독 및 배우]
known_for_department (역할) : Acting(배우), Directing(감독)
id (인물 id, PEOPLE API 통해서 검색 가능)
name (이름)
gender (성별) : 1이 여자, 2가 남자. 0일 경우에는 ㅁ?ㄹ
character (배역명, 배우인 경우에만)
profile_path (프로필 사진)

TV Series 데이터

TMDB API - TV Series - Details

TV SeriesDetails 정보를 얻어오려고 한다. 위와 달라진 내용은 작품 ID와 요청 URL 뿐이다. 미국에서 방송된 시트콤 프로그램인 <<빅뱅 이론>>을 예시로 들어보겠다.

API REQUEST 예시 <<빅뱅 이론>>

curl --request GET \
     --url 'https://api.themoviedb.org/3/tv/1418?language=ko-kr' \
     --header 'Authorization: Bearer {{API_KEY_VALUE}}' \
     --header 'accept: application/json'

추출해서 사용할 데이터

TV 프로그램은 영화와 다른 점이 몇 가지 있다. 여러 번에 걸쳐 방영되기 때문에 개봉일이 아닌 최초 방영일, 마지막 방영일 정보가 있고, 방송사와 에피소드, 시즌 개수 등의 정보도 가지고 있다. 또한 credits의 감독과는 별개로 created_by에 창작자, 작가 또는 PD 포지션의 인물 데이터가 존재한다.

시즌 정보도 있는데, 간략한 정보와 시즌 넘버링 정보를 가지고 있다. 따로 명시되어 있지는 않지만 season_number가 0인 경우 스페셜 같은 것에 해당하는 것 같다.

[TV 프로그램 정보]
name (작품 이름)
original_name (원제)
original_language (원어)
genres (장르)
tagline (간단소개)
overview (개요)
poster_path (포스터 이미지)
production_countries (제작 국가)

first_air_date (최초 방영일)
last_air_date (마지막 방영일)
networks (방송사)
number_of_episodes (에피소드 개수)
number_of_seasons (시즌 개수)

[창작자 정보]
created_by
	id (인물 아이디)
	name (이름)
	gender (성별)
	profile_path (프로필 사진)

[시즌]
seasons

id (시즌 아이디)
air_date (방영일)
episode_count (에피소드 개수)
overview (개요)
poster_path (포스터 이미지)
season_number (시즌 넘버링, 0인 경우 스페셜 같은 예외 사항)

[감독 및 배우]
known_for_department (역할) : Acting(배우), Directing(감독)
id (인물 id, PEOPLE API 통해서 검색 가능)
name (이름)
gender (성별) : 1이 여자, 2가 남자
character (배역명, 배우인 경우에만)
profile_path (프로필 사진)

마치며

TMDB API 문서를 읽어보고, 직접 사용해보면서 관련 내용들을 정리해았다. 사실 실제 프로젝트에 적용하기 위해서는 더 많은 종류의 API가 있겠지만 당장 사용하는데에는 이 정도만 알고 있어도 크게 문제는 없을 것 같다.

이 API 문서 분석의 가장 큰 목적이었던, DB 설계를 위한 데이터들을 추출해봤으니 다음에는 DB를 설계하고 코드로 적용해보자.

profile
일단 해보자

0개의 댓글