# Cargar librerías necesarias
library(httr)
library(jsonlite)
library(dplyr)
library(tidyr)
library(openxlsx)
library(purrr)
library(stringr)
library(writexl)
# Definir la URL de la petición
url <- "https://app.bde.es/bierest/resources/srdatosapp/listaSeries?idioma=es&series=DEEQ.N.ES.W1.S1.S1.T.B.G._Z._Z._Z.EUR._T._X.N.ALL,DEEQ.N.ES.W1.S1.S1.T.B.SD._Z._Z._Z.EUR._T._X.N.ALL,DEEQ.N.ES.W1.S1.S1.T.B.OS._Z._Z._Z.EUR._T._X.N.ALL&rango=MAX"
# Hacer la petición
response <- GET(url)
# Comprobar si fue correcta
if (status_code(response) == 200) {
  data <- content(response, as = "parsed", type = "application/json")
  print("Datos obtenidos correctamente")
} else {
  stop(paste("Error en la llamada a la API:", status_code(response)))
}
## [1] "Datos obtenidos correctamente"
# Ver el JSON que devuelve la API (únicamente la estructura de la primera serie)

# En R la respuesta JSON se convierte en una lista, por lo que se visualiza
# su estructura con str() en lugar de mostrar el JSON completo

str(data[[1]], max.level = 1)
## List of 11
##  $ serie           : chr "DEEQ.N.ES.W1.S1.S1.T.B.G._Z._Z._Z.EUR._T._X.N.ALL"
##  $ descripcion     : chr "BP. Bienes. Saldos"
##  $ descripcionCorta: chr "BP. Bienes"
##  $ codFrecuencia   : chr "Q"
##  $ decimales       : int 0
##  $ simbolo         : chr "M&euro;"
##  $ informacion     :List of 12
##  $ fechaInicio     : chr "1993-01-01T09:15:00Z"
##  $ fechaFin        : chr "2026-01-01T09:15:00Z"
##  $ fechas          :List of 133
##  $ valores         :List of 133
# Obtener la unidad de medida de cada serie
get_unidad <- function(info) {
  unidad <- info %>%
    keep(~ identical(.x$titulo, "Unidades")) %>%
    map_chr(~ .x$descripcion, .default = NA_character_)

  if (length(unidad) == 0) NA_character_ else unidad[1]
}
# Convertir la respuesta JSON en un data frame
df <- map_df(data, ~ tibble(
  serie       = .x$serie,
  descripcion = .x$descripcion,
  frecuencia  = .x$codFrecuencia,
  unidad      = get_unidad(.x$informacion),
  decimales   = as.integer(.x$decimales),
  fecha       = as.Date(substr(unlist(.x$fechas), 1, 10)),
  valor       = as.numeric(unlist(.x$valores))
))

# Mostrar las primeras filas
head(df)
## # A tibble: 6 × 7
##   serie                descripcion frecuencia unidad decimales fecha       valor
##   <chr>                <chr>       <chr>      <chr>      <int> <date>      <dbl>
## 1 DEEQ.N.ES.W1.S1.S1.… BP. Bienes… Q          Millo…         0 2026-01-01 -11867
## 2 DEEQ.N.ES.W1.S1.S1.… BP. Bienes… Q          Millo…         0 2025-10-01 -12125
## 3 DEEQ.N.ES.W1.S1.S1.… BP. Bienes… Q          Millo…         0 2025-07-01 -15050
## 4 DEEQ.N.ES.W1.S1.S1.… BP. Bienes… Q          Millo…         0 2025-04-01  -9343
## 5 DEEQ.N.ES.W1.S1.S1.… BP. Bienes… Q          Millo…         0 2025-01-01 -12448
## 6 DEEQ.N.ES.W1.S1.S1.… BP. Bienes… Q          Millo…         0 2024-10-01 -10713
# Exportar el data frame a Excel
write_xlsx(df, "df_api_bde_ejemplo-r.xlsx")