# Install packages needed for getting internet data
install.packages("httr")
install.packages("jsonlite")

# Load the packages
library(httr)
library(jsonlite)

# Load the packages again (if already installed)
library(httr)
library(jsonlite)

# Make a request to the website
response <- GET("https://catfact.ninja/fact")

# Look at the response
print(response)

# Extract the data from the response
raw_data <- content(response, as = "text")
print("Raw data from website:")
print(raw_data)

# Convert JSON into R data
cat_data <- fromJSON(raw_data)
print("Clean data for R:")
print(cat_data)

# Use the specific data we want
print("Here's your cat fact:")
print(cat_data$fact)

print("Length of the fact:")
print(cat_data$length)

# Understanding API data at each stage
# Look at the raw response object
print("=== THE COMPLETE RESPONSE ===")
print(response)

# Look at the raw data (messy JSON format)
print("=== RAW DATA FROM WEBSITE (JSON) ===")
raw_data <- content(response, as = "text")
print(raw_data)

# Look at the converted data (clean R format)
print("=== CLEAN DATA FOR R ===")
cat_data <- fromJSON(raw_data)
print(cat_data)

# Get just the fact
print("=== JUST THE FACT ===")
print(cat_data$fact)

# Get the length
print("=== LENGTH OF THE FACT ===")
print(cat_data$length)
