Hey everyone, I need some help with making API calls in R.
I’m working with a RapidAPI endpoint and keep running into authentication issues. The sample code from RapidAPI doesn’t work directly because of the hyphenated header names.
Here’s what I’ve tried:
library(httr)
# My API credentials
api_token <- "my_secret_key"
api_host <- "financial-data.p.rapidapi.com"
endpoint_url <- "https://financial-data.p.rapidapi.com/market/v2/stock-history"
# First attempt - building URL manually
full_url <- paste0(endpoint_url,
"?ticker=AAPL",
"&x-rapidapi-host:", api_host,
"&x-rapidapi-key:", api_token,
"&format=json")
result <- GET(full_url)
print(result)
This gives me a 401 error even though my API key works fine on the RapidAPI website.
Second attempt using proper headers:
library(httr)
base_url <- "https://financial-data.p.rapidapi.com/market/v2/stock-history"
params <- list(
ticker = "AAPL",
period = "1mo"
)
api_response <- VERB("GET",
base_url,
add_headers(`x-rapidapi-host` = 'financial-data.p.rapidapi.com',
`x-rapidapi-key` = 'my_secret_key'),
query = params,
content_type("application/json"))
print(api_response)
print(content(api_response, "text"))
Still getting 401 errors. What am I doing wrong here? The API key definitely works when I test it directly on RapidAPI’s interface.
Any ideas on how to fix this authentication issue?