Getting 401 error when using httr package to call RapidAPI in R

I’m having trouble connecting to RapidAPI using the httr library in R. Every time I make a request, I get a 401 status error.

Here’s my code:

library(httr)
api_url <- "https://weather-data.p.rapidapi.com/current"
params <- list(city = "New York")
result <- GET(api_url, 
              add_headers(
                'X-RapidAPI-Key' = "your-key-here",
                'X-RapidAPI-Host' = "weather-data.p.rapidapi.com"
              ),
              query = params)
print(content(result, "text"))

The response I keep getting is:

Status: 401

I’ve tried this with different RapidAPI endpoints but always get the same authentication error. My API key should be valid. What am I doing wrong here? Any help would be great!

Had this exact problem last month with RapidAPI endpoints. Yeah, 401 usually means auth issues, but here’s what actually fixes it most of the time. First - check your API key for trailing spaces or line breaks. I’ve screwed this up way too many times. Second, make sure your subscription’s still active and you haven’t hit rate limits. Here’s the tricky part: some endpoints need specific user-agent headers or extra auth params that their docs don’t mention clearly. Go to your RapidAPI dashboard and test the endpoint there first. If it works, compare those headers to what you’re sending. Also verify your endpoint URL matches their docs exactly - version numbers and all.

Make sure you’re using your actual API key, not the “your-key-here” placeholder from the example. That won’t work. Double-check that your X-RapidAPI-Host header matches the API endpoint domain exactly - sometimes the subdomain’s slightly different and causes auth failures. Also verify your RapidAPI subscription covers that endpoint. Some APIs have tiers and you might be hitting a premium endpoint with a basic plan. Print your headers before making the request to see if everything looks right, and check your RapidAPI dashboard to confirm the requests are reaching their servers.

Double-check you’re copying the key right from the RapidAPI dashboard - invisible characters sometimes sneak in and break things. Also try adding a user-agent header like 'User-Agent' = 'R/httr' since some APIs block requests without one. Had the same problem and that’s what fixed it for me.