Discover the methods for obtaining numerous JSON URLs and extracting dynamic information

I am currently in the process of developing my first application that extracts data from TMDB's API.

Initially, I was successful in loading and parsing data from a single URL using the following code:

uri = URI.parse("http://api.themoviedb.org/3/tv/#{URI.escape(@id)}?api_key=#{@api_key}")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
@results = JSON.load(response.body)

Now, I am facing a challenge with parsing JSON from the following endpoint:

/tv/{tv_id}/season/{season_number}/episode/{episode_number}

In this case, {tv_id} corresponds to @id = params[:id]

{season_number} and {episode_number} are related to the seasons and episodes fetched from the initial URL. Despite trying various approaches, I keep encountering different errors each time.

You can find the complete code on Github. The functioning application is available at TOMDB App on Heroku.

The objective is to present the season title and episodes within the same page for each series. For instance, upon parsing the URL:

https://api.themoviedb.org/3/tv/2432?api_key=**********

The response includes information such as:

{
"backdrop_path":"/hl9mC6fc2adfeGpI1ijKCfQ0KzI.jpg",
"name":"Taken",
"number_of_episodes":10,
"number_of_seasons":1
}

This indicates there are 10 episodes in one season. For every episode, an individual URL can be generated by substituting the episode number {1..5..10} into:

https://api.themoviedb.org/3/tv/8681/season/1/episode/*1*?api_key=********

The goal is to showcase the names of each episode, thereby generating a JSON output like:

{
"name":"Beyond the Sky","overview":"......",
"id":183273,
"vote_average":0.0,
"vote_count":0
}

Answer №1

It is crucial to utilize https for that specific request, pay close attention to the sections I highlighted with #** that necessitate modification. Note the usage of Net::HTTP.start instead of Net::HTTP.new. Also, kudos on the fantastic app!

require 'net/http'
require 'net/https' #*add*
require 'json'
require 'open-uri'

url = 'https://api.themoviedb.org/3/tv/1418/season/1/episode/1?api_key=**************************&language=en-US'
uri = URI.parse(url)
# *adapt following line*
http = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
json = JSON.load(response.body)


# {"air_date"=>"2007-09-24", "crew"=>[{"id"=>157437, "credit_id"=>"5256cfee19c2956ff60a280c", "name"=>"James Burrows", "department"=>"Directing", "job"=>"Director", "profile_path"=>"/lTcRumFOm6HkfOyPuUElV4l4n4r.jpg"}, {"id"=>160172, "credit_id"=>"5256cfbc19c2956ff60a0483", "name"=>"Chuck Lorre", "department"=>"Writing", "job"=>"Writer", "profile_path"=>"/btpYlMV71sjQXrV142I9kogEINI.jpg"}, {"id"=>163528, "credit_id"=>"5256cfbd19c2956ff60a04f0", "name"=>"Bill Prady", "department"=>"Writing", "job"=>"Writer", "profile_path"=>"/duXUvo8JtivQR0BHiXHGQwoNYB4.jpg"}, {"id"=>1480308, "credit_id"=>"55881d37925141681800...

UPDATE: To access all episodes from a season, you simply need to iterate through numbers 1 to the total number of episodes and construct a new url request. Similarly, enumerate all seasons of a series by implementing similar logic. Some room for improvement but good luck with your endeavors!

require 'net/http'
require 'net/https'
require 'json'
require 'open-uri'
require 'pp'

# Repeated process, so keeping it DRY
def get_json url
  uri = URI.parse(url)
  http = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE) #**
  request = Net::HTTP::Get.new(uri.request_uri)
  response = http.request(request)
  JSON.load(response.body)
end

API_KEY  = '****************************'
url = "https://api.themoviedb.org/3/tv/2432?api_key=#{API_KEY}"
season = get_json url

season['number_of_episodes'].to_i.times do |episode|
  episode += 1
  url = "https://api.themoviedb.org/3/tv/8681/season/1/episode/#{episode}?api_key=#{API_KEY}"
  episode = get_json url
  # pp episode
  puts episode['name']
end

Output:

# Great White Shark: The True Story of Jaws
# Polar Bear: The Arctic Warrior
# Crocodile: The Smiling Predator
# Leopard: The Agent of Darkness
# Eagle: The Master of the Skies
# Humpback Whale: The Giant of the Oceans
# Wolf: The Legendary Outlaw
# Tiger: The Elusive Princess
# Lions: Spy in the Den
# Grizzly: Face to Face

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Aggregation in MongoDB with the match and group functions for data analysis

I want to calculate the total sum of "paid_amount" based on "user_id", "real_currency_spend", and "paid_currency". The objective is to obtain totals per user per currency type, ensuring Yen "paid_amount" are not mixed with USD, GBP, etc. The current code ...

ruby use JSON library to import data

How can I utilize the parsed information from the data.rb file within the main.rb file? I am attempting to determine the frequency of the years "2017" and "2014". I aim to send back both counts to the count_years method found in main.rb. What is the corr ...

Ways to convert a JSON file into a ListView using Volley

I'm currently developing an app that requires fetching data from the internet, such as names and email addresses. I followed tutorials on using Volley to parse a JSON file and successfully retrieved the data. However, I encountered an issue when tryin ...

Can PHP send back data to AJAX using variables, possibly in an array format?

My goal is to transmit a datastring via AJAX to a PHP page, receive variables back, and have jQuery populate different elements with those variables. I envision being able to achieve this by simply writing: $('.elemA').html($variableA); $('. ...

Converting XML to JSON object by formatting string into scientific notation

I am facing an issue where a specific XML tag value is being converted to scientific notation when parsed into a JSON object. The original value is "09031454866678e6", but it gets transformed into "9.031454866678E6". Is there a way to ...

Executing an authenticated Guzzle POST request

Just starting out with guzzle and I need help on how to make a Guzzle call for this specific request. curl -X POST -u username:password -H "Content-Type: application/json" https://xyz/api/v1/accounts.json -d '{"user":{"username":"test","password":"xy ...

Remove a JSON object that corresponds to a particular value

I am in need of modifying a JSON file in a specific way. My goal is to remove an entire object from the file based on a certain condition. In this case, the condition is that "name": "value1_1:value1_2" The value of value1_1 is what I am targeting for ...

Integrating HTTP JSON responses into HTML using Ionic 2, Angular 2, TypeScript, and PHP: A comprehensive guide

Currently in the midst of developing my first Ionic 2 app, however, my understanding of typescript is still limited.. I aim to execute the authenticate() method within my constructor and then to: Retrieve the entire JSON response into the textarea and/o ...

How to connect Kendo UI Grid column headers with a JSON data source

Currently, I am working with a Kendo UI grid and my goal is to dynamically bind the column headers to a JSON file instead of hardcoding it in the controller. Is there a way to achieve this similar to how we bind data using the dataSource? If not, what wo ...

Why is my PHP json_decode function returning null?

I have spent countless hours searching on various platforms like Google and Stack Overflow, but unfortunately, I haven't been able to find a suitable solution for my problem. The issue lies with the JSON data that is being retrieved from the database ...

Sending Java Servlet JSON Array to HTML

I am currently engaged in a project that requires extracting data from a MySQL database and implementing pagination. My approach involves utilizing JSON AJAX and JavaScript, although I am fairly new to JSON and AJAX. After successfully retrieving the neces ...

Utilizing a FutureBuilder for fetching JSON data in a Flutter DropDownButton

I have been developing an app using Flutter and I am currently working on implementing a Dropdown Button that will display values received from a JSON response via an API built with Django. Here is the JSON response: [{"name": "FC1", "username": "admin"} ...

Generating a nested list structure from a dictionary with varying levels of nesting

I am working with a dictionary obtained from a cURL call in Python 3.8 and my goal is to extract information from just two specific keys to create a list that can be written into a csv file. The dictionary contains only one key-value pair, where the value ...

What is the best way to extract a single String element from a List<MyList> Array list?

I have been working on implementing a RecyclerView where I retrieve data from an API in JSON format. To achieve this, I created two models - one for my RecyclerView data and the other for my calendar view. The data retrieval for the RecyclerView using a cu ...

Struggling with UI-Grid's single filter feature when dealing with intricate data structures?

I'm currently working with UI-Grid and facing a challenge while applying a filter to some complex data using their single filter example. Initially, everything runs smoothly when I use simple selectors. However, as soon as I attempt to delve one level ...

Tips on storing JSON array data in mongoose via req.body?

I've been struggling with this issue for some time now. After successfully using JSON and req.body to save data to my MongoDB database in Postman, I decided to work with arrays for the first time. However, I'm encountering difficulties. (Just t ...

Using Python to navigate JSON files containing multiple arrays

When attempting to extract data from a JSON file and transform it into an object type, I encountered multiple arrays of latitudes and longitudes. How can I handle this using Python? Snippet of Python code* import os from flask import Flask, render_templat ...

Generate HttpRequestHeaders using JObject

One of my challenges has been creating an API for my desktop software to streamline the process of changing HttpClient headers without having to constantly code and rebuild. My main hurdle now is figuring out how to generate a custom list of HttpRequestHea ...

Serialization and encoding using json.NewEncoder and json.NewDecoder

I am currently delving into Backend development by constructing a very basic REST API using the gorilla mux library in Go (referring to this tutorial) Here is the code that I have developed so far: package main import ( "encoding/json" "ne ...

Creating an index on a JSON array type in MySQL 5.7 can optimize the performance of your

Currently, I am using an SQL script similar to SELECT * FROM user WHERE JSON_CONTAINS(users, '[1]');. However, this method scans the entire table and is inefficient. I would like to create an index on the users column. For instance, if I have a ...