#!/usr/bin/env python
# coding: utf-8

# # Acceso a datos abiertos de AEMET

# Vamos a utilizar los aprendido hasta ahora para acceder a los datos meteorológicos que nos ofrece AEMET.
# 
# https://opendata.aemet.es/centrodedescargas/inicio
# 
# Para ello, necesitamos primero obtener una API Key que nos permitirá interactuar con la API
# 
# La API Key se obtiene a través del registro en AEMET
# https://opendata.aemet.es/centrodedescargas/altaUsuario?
# 
# En mi caso, tras registrarme, he obtendido la siguiente API Key: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZXJtYW5AY2FtcHVzMmIuY29tIiwianRpIjoiYjE1ZDZlMzMtODBlMS00MzhkLTlmYjEtMTZmM2JkNmZkNDJmIiwiaXNzIjoiQUVNRVQiLCJpYXQiOjE2NDI1OTMwNTAsInVzZXJJZCI6ImIxNWQ2ZTMzLTgwZTEtNDM4ZC05ZmIxLTE2ZjNiZDZmZDQyZiIsInJvbGUiOiIifQ.uwn4lQit0msHtS110NcXnNCLJWpxxd-xHHlDSG7v5Ag

# In[1]:


import requests
import json


# In[2]:


# Extraemos la información de las estaciones meteorológicas existentes

url = "https://opendata.aemet.es/opendata/api/valores/climatologicos/inventarioestaciones/todasestaciones/"
querystring = {"api_key":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZXJtYW5AY2FtcHVzMmIuY29tIiwianRpIjoiYjE1ZDZlMzMtODBlMS00MzhkLTlmYjEtMTZmM2JkNmZkNDJmIiwiaXNzIjoiQUVNRVQiLCJpYXQiOjE2NDI1OTMwNTAsInVzZXJJZCI6ImIxNWQ2ZTMzLTgwZTEtNDM4ZC05ZmIxLTE2ZjNiZDZmZDQyZiIsInJvbGUiOiIifQ.uwn4lQit0msHtS110NcXnNCLJWpxxd-xHHlDSG7v5Ag"}
headers = {'cache-control': "no-cache"}

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)
print(type(response.text))


# In[3]:


response.json()
print(type(response))


# In[4]:


datos = json.loads(response.text)
print(datos)
print(type(datos))


# In[5]:


# Extraemos la url con los datos relativos a la petición
url2 = datos['metadatos']
url3 = datos['datos']

response2 = requests.request("GET", url2, headers=headers, params=querystring)
response3 = requests.request("GET", url3, headers=headers, params=querystring)


# In[6]:


response2.json()


# In[7]:


response3.json()


# In[8]:


import pandas as pd


# In[9]:


# Extraemos la info de la url directamente
df = pd.read_json(datos['datos'], encoding='WINDOWS-1252')
df

# Probad a ejectuar el código anterior, sin el argumento encoding


# La información previa necesitaría ser reorganizada, determinadas columnas deberían estar juntas (latitud y longitud) y además las coordenadas de dichas columnas necesitan transformarse, ...

# In[89]:


df.to_csv('estaciones aemet.csv', index=False, sep="|", encoding='UTF-8')


# ## Segunda parte.  Extracción información meteorológica convencional para todas las estaciones

# Para el acceso a información meteorológica a nivel de municipio, necesitamos primero el municipio normalizado, según los datos de AEMET. ->> http://www.ine.es/daco/daco42/codmun/codmunmapa.htm
# La url para hacer get: 
# get /api/prediccion/especifica/municipio/diaria/{municipio} 

# In[10]:


municipios = pd.read_excel('https://www.ine.es/daco/daco42/codmun/codmun20/20codmun.xlsx')
municipios


# In[11]:


municipios.columns = municipios.iloc[0,:]
municipios = municipios.iloc [1:,:]
municipios


# In[12]:


# Eliminamos los espacios delante y detrás de los nombres de columna
municipios.columns.tolist()
municipios.columns = municipios.columns.str.replace(' ','')


# In[13]:


# Guardo el resultado.  Ojo, pq el set de datos usa la , en la columna nombre y por tanto no podríamos usar ese separador
municipios.to_csv('municipios_ine.csv', index=False, sep='|', encoding='UTF-8')


# In[14]:


municipios.info()


# In[57]:


# Extraemos datos de observación horarios de las últimas 24 horas todas las estaciones meteorológicas de las que se han recibido datos en ese período

url = 'https://opendata.aemet.es/opendata/api/observacion/convencional/todas'

querystring = {"api_key":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZXJtYW5AY2FtcHVzMmIuY29tIiwianRpIjoiYjE1ZDZlMzMtODBlMS00MzhkLTlmYjEtMTZmM2JkNmZkNDJmIiwiaXNzIjoiQUVNRVQiLCJpYXQiOjE2NDI1OTMwNTAsInVzZXJJZCI6ImIxNWQ2ZTMzLTgwZTEtNDM4ZC05ZmIxLTE2ZjNiZDZmZDQyZiIsInJvbGUiOiIifQ.uwn4lQit0msHtS110NcXnNCLJWpxxd-xHHlDSG7v5Ag"}
headers = {'cache-control': "no-cache"}

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)
print(type(response.text))


# In[53]:


datos = json.loads(response.text)
url2 = datos['metadatos']
url3 = datos['datos']

response2 = requests.request("GET", url2, headers=headers, params=querystring)
response3 = requests.request("GET", url3, headers=headers, params=querystring)


# In[54]:


response2.json()


# In[55]:


response3.json()


# In[56]:


df2 = pd.read_json(datos['datos'], encoding='WINDOWS-1252')
df2


# In[35]:


df2.info()


# In[34]:


df2.isnull().sum()


# # Tercera parte.  Extraemos predicciones marítimas para el mediterráneo
# 

# In[73]:


# Extraemos predicciones marítimas para el mediterráneo

url = 'https://opendata.aemet.es/opendata/api/prediccion/maritima/altamar/area/2'

querystring = {"api_key":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZXJtYW5AY2FtcHVzMmIuY29tIiwianRpIjoiYjE1ZDZlMzMtODBlMS00MzhkLTlmYjEtMTZmM2JkNmZkNDJmIiwiaXNzIjoiQUVNRVQiLCJpYXQiOjE2NDI1OTMwNTAsInVzZXJJZCI6ImIxNWQ2ZTMzLTgwZTEtNDM4ZC05ZmIxLTE2ZjNiZDZmZDQyZiIsInJvbGUiOiIifQ.uwn4lQit0msHtS110NcXnNCLJWpxxd-xHHlDSG7v5Ag"}
headers = {'cache-control': "no-cache"}

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)
print(type(response.text))


# In[74]:


datos = json.loads(response.text)
url2 = datos['metadatos']
url3 = datos['datos']

response2 = requests.request("GET", url2, headers=headers, params=querystring)
response3 = requests.request("GET", url3, headers=headers, params=querystring)
df3 = pd.json_normalize(response3.json())
df3


# # Cuarta parte.  Consultando AEMET a través de una librería

# In[75]:


pip install python-aemet


# In[77]:


from aemet import Aemet


# In[105]:


Aemet(api_key="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZXJtYW5AY2FtcHVzMmIuY29tIiwianRpIjoiYjE1ZDZlMzMtODBlMS00MzhkLTlmYjEtMTZmM2JkNmZkNDJmIiwiaXNzIjoiQUVNRVQiLCJpYXQiOjE2NDI1OTMwNTAsInVzZXJJZCI6ImIxNWQ2ZTMzLTgwZTEtNDM4ZC05ZmIxLTE2ZjNiZDZmZDQyZiIsInJvbGUiOiIifQ.uwn4lQit0msHtS110NcXnNCLJWpxxd-xHHlDSG7v5Ag").get_archivo_codigos_idema('codigosIDEMA')


# In[99]:


# Extracción de los valores climatológicos (mensuales), de la estación meteorológica del aeropuerto de Loiu
aemet_client = Aemet(api_key="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJnZXJtYW5AY2FtcHVzMmIuY29tIiwianRpIjoiYjE1ZDZlMzMtODBlMS00MzhkLTlmYjEtMTZmM2JkNmZkNDJmIiwiaXNzIjoiQUVNRVQiLCJpYXQiOjE2NDI1OTMwNTAsInVzZXJJZCI6ImIxNWQ2ZTMzLTgwZTEtNDM4ZC05ZmIxLTE2ZjNiZDZmZDQyZiIsInJvbGUiOiIifQ.uwn4lQit0msHtS110NcXnNCLJWpxxd-xHHlDSG7v5Ag").get_valores_climatologicos_mensuales(anyo="2021", estacion="1082")


# In[100]:


aemet_client


# In[101]:


df4 = pd.json_normalize(aemet_client)
df4

