Struggling with R HTTP requests to RapidAPI - Getting 401 authentication errors

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?

Check if you’re accidentally including the host URL in your x-rapidapi-host header. I did this once - passed the full https://financial-data.p.rapidapi.com instead of just financial-data.p.rapidapi.com. RapidAPI servers reject requests when the host header doesn’t match exactly. Try curl_options(verbose = TRUE) to see the raw request headers. Sometimes R adds weird characters or encoding that breaks authentication. Also verify your subscription includes access to that endpoint. RapidAPI returns 401 even with valid keys if you don’t have the right plan tier.

Had the same authentication nightmare with RapidAPI a few months ago. You’re putting headers in the URL parameters instead of actual HTTP headers - that’s your problem with the first attempt. Second approach looks right, but make sure you’re using backticks around header names, not regular quotes. R gets weird about that syntax. Also check if your API key has permissions for that specific endpoint. RapidAPI loves having different access levels. Use verbose() in your GET call to log the exact headers being sent so you can see what’s actually going through.

had this exact issue last week! remove the content_type line - rapidapi gets picky about it. also check ur not accidentally wrapping quotes around your api key when pasting it in.