'download data from CoinMarketCap API

I want to download coinmarketcap of cryptocoins data. When compiling the code below:

rm(list = ls())
cat("\014")
library(httr)
library(jsonlite)
library(tidyverse)
base_url <- "https://pro-api.coinmarketcap.com/"
path <- "v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD&CMC_PRO_API_KEY="
endpoint <- paste(base_url, path, sep="/")
key_api <- Sys.getenv("MyKey")
res_api <- GET(
  url = endpoint, 
  query = list(
    apikey= key_api,
    details = "true"
  )
)
res_api

I get the following answer:

Response [https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD&CMC_PRO_API_KEY=&apikey=&details=true]
  Date: 2021-09-02 17:14
  Status: 401
  Content-Type: application/json; charset=utf-8
  Size: 195 B
{
    "status": {
        "timestamp": "2021-09-02T17:14:20....
        "error_code": 1002,
        "error_message": "API key missing.",
        "elapsed": 0,
        "credit_count": 0
    }

A 401 status means that my request does not have valid authentication credentials and that I probably have some problem with my API key. However, my key is correct. can anybody help me?



Solution 1:[1]

I'm Normally using python to interact with the API, But reading your post I found something

This is part of your response

https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD&CMC_PRO_API_KEY=&apikey=&details=true

Check the query parameters

&CMC_PRO_API_KEY=&apikey=&details=true

Both CMC_PRO_API_KEY and apikey are empty.

You need to pass the API key either as part of the string query or as part of the headers, it seems you are trying to do both.

I think a request using headers will be a good option, and it must be something like this:

GET('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD', 
      accept_json(), 
      add_headers('CMC_PRO_API_KEY' = 'YOUR_API_KEY'))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Victor Andres Aguirre Fernande