API

API de DataChile

DataChile posee una API de datos que entrega la información para construir los gráficos y generar todos los textos del sitio.

Primeros Pasos

DataChile utiliza para su funcionamiento como capa lógica Mondrian-REST, que es un componente del lado del servidor que permite la creación de APIs HTTP para acceder a una base de datos especificando la estructura lógica de la información.

Para utilizar la API de DataChile, es necesario conocer algunos conceptos que facilitarán su uso, los cuáles explicaremos a continuación.

Cubo

Un cubo es una colección de dimensions y measures.

En DataChile, cada dataset está agrupado en un cubo. El diseño del lenguaje de consultas a la API está centrado en torno a 3 operaciones: Drilldown, Cut, Measure. Para ejemplificar los conceptos, se utilizará el dataset exports -que representa las exportaciones de Chile- como referencia.

Drilldown
Algunas definiciones previas:
  • Un member es un valor dentro de una dimensión determinada por un set de valores. La jerarquía género tiene los miembros 'Masculino' y 'Femenino'. 'Concepción', 'Bío-Bío' y 'Chile' son todos miembros de la jerarquía Geográfica.
  • Un level es un conjunto de miembros que se encuentran a la misma distancia del inicio de la jerarquía. Concepción, Tucapel, Arica, se encuentran en el mismo level.
  • Una hierarchy es un conjunto de miembros organizados estructuradamente para su análisis. Por ejemplo, la jerarquía Geográfica consiste de nombre de comuna, regiones y país. La jerarquización permite obtener valores intermedios: Total de exportaciones de la región de Valparaíso es la suma de todas las exportaciones de las comunas de dicha región.
  • Una dimension es un conjunto de jerarquías que discriminan el mismo atributo (Por ejemplo, el día que se produjo una exportación)

Un drilldown permite pasar de un nivel de detalle al siguiente. La estructura de un drilldown para las consultas en el cubo es [Dimension].[Hierarchy].[Level]

Medición

Variable escalar asociada con un valor particular en los datos del cubo.

Corte

Permite al usuario especificar un filtro, que restringe las tuplas disponibles del cubo. Por ejemplo, en exports, cortar el cubo en torno al miembro [Region].[8] en la dimensión Geography, sólo considerará celdas de la región de Bío-Bío. Múltiples cortes pueden ser especificados en una simple consulta.

Sintaxis

URL BASE https://chilecube.datachile.io
GET /cubes/{{cube_name}}/dimensions/{{dimension_name}}/levels/{{level_name}}/members

Para un cubo en particular, obtiene los miembros pertenecientes a un determinado level presente en una dimension.

GET /cubes/{{cube_name}}/aggregate

El punto de entrada para las operaciones de agregación es /aggregate, que acepta los parámetros descritos a continuación.

ParámetroTipoDescripción
drilldown[]stringPara generar un drilldown, se debe tener en cuenta: Dimension, Hierarchy, Level. [Dimension].[Hierarchy].[Level]
measures[]string
cut[]stringSe debe concatenar el drilldown sobre el cuál se desea hacer el corte, con Level ID. [Dimension].[Hierarchy].[Level].&[member_id]1
nonemptybooleanDevuelve el conjunto de tuplas que no están vacías de un especificado conjunto, basado en el producto cartesiano del conjunto especificado.
distinctbooleanEvalúa un conjunto específico, elimina tuplas duplicadas del conjunto y devuelve el conjunto resultante.
parentsbooleanEn caso de encontrarse en un nivel de profundidad mayor a 1, obtiene el ID y nombre de los niveles padres.
sparsebooleanVerifica si una determinada tupla NO está en la agregación, no se incluye en la tabla resultante.
1. Si se hace la consulta directamente en URL, se debe reemplazar & por %26 para evitar problemas de parseo del corte.

Listado de Campos

CubeDrilldownsMeasures
tax_data
[Date].[Date].[Year]
[Tax Geography].[Geography].[Region]
[Tax Geography].[Geography].[Comuna]
[ISICrev4].[ISICrev4].[Level 1]
[ISICrev4].[ISICrev4].[Level 2]
[ISICrev4].[ISICrev4].[Level 3]
[ISICrev4].[ISICrev4].[Level 4]
Output
Labour
Labour Cost
Investment
Intermediates
Value Added
Production per worker
Value added per worker
Output RCA
internet_access
[Geography].[Geography].[Region]
[Zone].[Zone].[Zone]
[Internet Plan].[Binary Survey Response].[Binary Survey Response]
[Home Access].[Binary Survey Response].[Binary Survey Response]
[Desktop Access].[Binary Survey Response].[Binary Survey Response]
[Laptop Access].[Binary Survey Response].[Binary Survey Response]
[Tablet Access].[Binary Survey Response].[Binary Survey Response]
[Cellphone Access].[Binary Survey Response].[Binary Survey Response]
[Games or Consoles Access].[Binary Survey Response].[Binary Survey Response]
[TV Access].[Binary Survey Response].[Binary Survey Response]
[Date].[Date].[Year]
Number of records
Expansion factor
population_estimate
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Sex].[Sex].[Sex]
[Age Range].[Age Range].[Age Range]
Number of records
Population
Population Rank
Population Rank Decile
Population Rank Total
exports_and_imports
[Date].[Date].[Year]
[Date].[Date].[Month]
[Date].[Date].[Day]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Country].[Country].[Continent]
[Country].[Country].[Country]
FOB
CIF
Trade Balance
Trade Exchange
casen_banking
[Date].[Date].[Year]
[Date].[Date].[Month]
[Date].[Date].[Day]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Debit Card].[Binary Survey Response].[Binary Survey Response]
[Bank Credit Card].[Binary Survey Response].[Binary Survey Response]
[Store Credit Card].[Binary Survey Response].[Binary Survey Response]
[Checks].[Binary Survey Response].[Binary Survey Response]
[Credit Line].[Binary Survey Response].[Binary Survey Response]
Number of records
Expansion Factor Region
Expansion Factor Comuna
Expansion Factor
education_sned
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Institutions].[Institution].[Institution]
[Cluster].[Cluster].[Stage 1a]
[Cluster].[Cluster].[Stage 1b]
[Cluster].[Cluster].[Stage 2]
[Administration].[Administration].[Administration]
[Subsidized 100%].[Subsidized 100%].[Subsidized 100%]
[Subsidized 60%].[Subsidized 60%].[Subsidized 60%]
Number of records
Avg efectiveness
Avg overcoming
Avg initiative
Avg integration
Avg improvement
Avg fairness
Avg sned_score
education_enrollment
[Date].[Date].[Year]
[Date].[Date].[Month]
[Date].[Date].[Day]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Sex].[Sex].[Sex]
[Zone].[Zone].[Zone]
[Administration].[Administration].[Administration]
[Institutions].[Institution].[Institution]
[Teachings].[Teaching].[Teaching]
Number of records
Average Age
imports
[Date].[Date].[Year]
[Origin Country].[Country].[Continent]
[Origin Country].[Country].[Country]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Import HS].[HS].[HS0]
[Import HS].[HS].[HS2]
[Import HS].[HS].[HS4]
[Country].[Country].[Continent]
[Country].[Country].[Country]
CIF US
Geo Rank Across Time
immigration
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Origin Country].[Country].[Continent]
[Origin Country].[Country].[Country]
[Sex].[Sex].[Sex]
[Education].[Education].[Education]
[Activity].[Activity].[Activity]
[Visa Type].[Visa Type].[Visa Type]
[Calculated Age Range].[Calculated Age Range].[Age Range]
Number of visas
Average Age
imports_old
[Date].[Date].[Year]
[Date].[Date].[Month]
[Date].[Date].[Day]
[Origin Country].[Country].[Continent]
[Origin Country].[Country].[Country]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Import HS].[HS].[HS0]
[Import HS].[HS].[HS2]
[Import HS].[HS].[HS4]
[Country].[Country].[Continent]
[Country].[Country].[Country]
CIF US
Geo Rank Across Time
nesi_income
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Sex].[Sex].[Sex]
[Age Range].[Age Range].[Age Range]
[ISCO].[ISCO].[ISCO]
[ICSE].[ICSE].[ICSE]
[ISCED].[ISCED].[ISCED]
[Occupation Length].[Occupation Length].[Occupation Length]
[Workday].[Workday].[Workday]
[Income Range].[Income Range].[Income Range]
Income
Expansion Factor
Median Income
Weighted Income
Weighted Median Income Rank
Weighted Median Income Decile
Weighted Median Income Total
casen_household
[Date].[Date].[Year]
[Date].[Date].[Month]
[Date].[Date].[Day]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Zone Id].[Zone Id].[Zone Id]
[Household Type].[Household Type].[Household Type]
[Walls Material].[Walls Material].[Walls Material]
[Floor Material].[Floor Material].[Floor Material]
[Ceiling Material].[Ceiling Material].[Ceiling Material]
[Households In Land].[Households In Land].[Households In Land]
[Land Using].[Land Using].[Land Using]
[Household Sq Meters].[Household Sq Meters].[Household Sq Meters]
[Household Using].[Household Using].[Household Using]
[Family Member Owner].[Family Member Owner].[Family Member Owner]
[Family Member Owner 2].[Family Member Owner 2].[Family Member Owner 2]
[Subsidy Or Program].[Subsidy Or Program].[Subsidy or Program]
[Credit].[Credit].[Credit]
[Paying Credit].[Paying Credit].[Paying Credit]
[Water Source].[Water Source].[Water Source]
[Water Distribution].[Water Distribution].[Water Distribution]
[Waste Disposal].[Waste Disposal].[Waste Disposal]
[Electricity].[Electricity].[Electricity]
[Rooms].[Rooms].[Rooms]
[Bathrooms].[Bathrooms].[Bathrooms]
[Families In Household].[Families In Household].[Families In Household]
[Reason To Share].[Reason To Share].[Reason To Share]
[Cooking Energy Source].[Energy Source Survey Response].[Energy Source Survey Response]
[Heating Energy Source].[Energy Source Survey Response].[Energy Source Survey Response]
[Hot Water Energy Source].[Energy Source Survey Response].[Energy Source Survey Response]
[Less Than 8 Blocks Public Transport].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Educational Center].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Health Center].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Market].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Atm].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Sports Center].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Green Areas].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Community Equipment].[Binary Survey Response].[Binary Survey Response]
[Less Than 20 Blocks Pharmacy].[Binary Survey Response].[Binary Survey Response]
[Affected By Acoustic Contamination].[Frequency Survey Response].[Frequency Survey Response]
[Affected By Air Contamination].[Frequency Survey Response].[Frequency Survey Response]
[Affected By River Or Lake Contamination].[Frequency Survey Response].[Frequency Survey Response]
[Affected By Public Water Source Contamination].[Frequency Survey Response].[Frequency Survey Response]
[Affected By Graffitis Or Advertising].[Frequency Survey Response].[Frequency Survey Response]
[Affected By Accumulation Of Trash Public Areas].[Frequency Survey Response].[Frequency Survey Response]
[Affected By Animal Or Insect Plague].[Frequency Survey Response].[Frequency Survey Response]
Number of records
Expansion Factor Region
Expansion Factor Comuna
Expansion Factor
life_expectancy
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Sex].[Sex].[Sex]
Number of records
Life Expectancy AVG
Mortality rate per 100 inhabitants AVG
exports
[Date].[Date].[Year]
[Destination Country].[Country].[Continent]
[Destination Country].[Country].[Country]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Export HS].[HS].[HS0]
[Export HS].[HS].[HS2]
[Export HS].[HS].[HS4]
[Country].[Country].[Continent]
[Country].[Country].[Country]
FOB US
Geo Rank
Geo Rank Across Time
HS Rank
HS Rank Decile
HS Rank Total
Exports for year (sum_c_p_xcp)
Exports RCA
education_performance_new
[Year].[Year].[Year]
[Institution].[Institution].[Administration]
[Institution].[Institution].[Institution]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Sex].[Sex].[Sex]
[Administration].[Administration].[Administration]
Number of records
Average PSU
Average NEM
disabilities
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Sex].[Sex].[Sex]
[Disability Grade].[Disability Grade].[Disability Grade]
Number of records
Expansion Factor Region
election_participation
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Election Type].[Election Type].[Election Type]
Number of records
Electors
Votes
Participation
casen_health_system
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Health System].[Health System].[Health System Group]
[Health System].[Health System].[Health System]
Number of records
Expansion Factor Region
Expansion Factor Comuna
Expansion Factor
election_results_update
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Election Type].[Election Type].[Election Type]
[Party].[Party].[Partido]
[Candidates].[Candidates].[Candidate]
[Coalition].[Coalition].[Coalition]
[Elected].[Elected].[Elected]
Number of records
Votes
rd_survey
[Date].[Date].[Year]
[Date].[Date].[Month]
[Date].[Date].[Day]
[Headquarters Country].[Country].[Continent]
[Headquarters Country].[Country].[Country]
[ISICrev4].[ISICrev4].[Level 1]
[Business Type].[Business Type].[Business Type]
[Ownership Type].[Ownership Type].[Ownership Type]
sales
exports
Total Spending
gasto_region_15
gasto_region_1
gasto_region_2
gasto_region_3
gasto_region_4
gasto_region_5
gasto_region_6
gasto_region_7
gasto_region_8
gasto_region_9
gasto_region_14
gasto_region_10
gasto_region_11
gasto_region_12
gasto_region_13
staff_region_15
staff_region_1
staff_region_2
staff_region_3
staff_region_4
staff_region_5
staff_region_6
staff_region_7
staff_region_8
staff_region_9
staff_region_14
staff_region_10
staff_region_11
staff_region_12
staff_region_13
health_access
[Date].[Date].[Year]
[Geography].[Geography].[Region]
Number of records
Primary Healthcare SUM
Specialized Healthcare SUM
Urgency Healthcare SUM
Primary Healthcare AVG
Specialized Healthcare AVG
Urgency Healthcare AVG
Dental Discharges Per 100 inhabitants AVG
education_employability
[Careers].[Careers].[Career Group]
[Careers].[Careers].[Career]
[Higher Institutions].[Higher Institutions].[Higher Institution Group]
[Higher Institutions].[Higher Institutions].[Higher Institution Subgroup]
[Higher Institutions].[Higher Institutions].[Higher Institution]
[Accreditations].[Accreditations].[Accreditation]
[Avg Income 4th year].[Avg Income 4th year].[Avg Income 4th year]
Number of records
Avg subsidized
Avg Retention 1st year
Avg Duration in semesters
Avg employability 1st year
Avg anual payment 2016
Sum anual payment 2016
psu
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Sex].[Sex].[Sex]
[Calculated PSU Bucket].[Calculated PSU Bucket].[Bucket]
Number of records
Avg language test
Avg math test
PSU AVG individual
PSU Average
PSU Rank
PSU Rank Decile
PSU Rank Total
death_causes
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Sex].[Sex].[Sex]
[CIE 10].[CIE 10].[CIE 10]
Number of records
Casualities Count AVG
Casualities Count SUM
Casualities rate per 100 inhabitants
crimes
[Date].[Date].[Year]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Crime].[Crime].[Crime Group]
[Crime].[Crime].[Crime]
Number of records
Cases
nene_quarter
[Date].[Date].[Year]
[Date].[Date].[Moving Quarter]
[ISIC CAENES].[ISIC CAENES].[ISIC CAENES]
[Occupational Situation].[Occupational Situation].[Occupational Situation]
[General Economic Condition].[General Economic Condition].[General Economic Condition]
[Geography].[Geography].[Region]
[Sex].[Sex].[Sex]
[Age Range].[Age Range].[Age Range]
[ISCED].[ISCED].[ISCED]
[ICSE].[ICSE].[ICSE]
[ISCO].[ISCO].[ISCO]
Number of records
Expansion factor
Number of records Decile
Expansion Factor Decile
education_performance
[Date].[Date].[Year]
[Date].[Date].[Month]
[Date].[Date].[Day]
[Geography].[Geography].[Region]
[Geography].[Geography].[Comuna]
[Sex].[Sex].[Sex]
[Zone].[Zone].[Zone]
[Administration].[Administration].[Administration]
[Institutions].[Institution].[Institution]
[Teachings].[Teaching].[Teaching]
Number of records
Average Score Average (?)

Estos datos son obtenidos directamente desde https://chilecube.datachile.io/cubes

Ejemplo de llamada de datos

Los siguientes ejemplos ilustran cómo son construidas las consultas, restringiendo la búsqueda con drilldowns, cuts y measures. Aquí se muestra el aspecto de la URL y el JSON devuelto cuando se pregunta ¿Qué número de personas está en cada previsión de salud en Concepción?

Query

Output


    {
      "axes": [
        {
          "members": [
            {
              "name": "Expansion Factor Comuna",
              "full_name": "[Measures].[Expansion Factor Comuna]",
              "caption": "Expansion Factor Comuna",
              "key": "Expansion Factor Comuna",
              ...
            }
          ]
        },
        {
          "members": [
            {
              "name": "FONASA",
              "full_name": "[Health System].[FONASA]",
              "caption": "FONASA",
              "key": 1,
              ...
            },
            {
              "name": "Isapre",
              "full_name": "[Health System].[Isapre]",
              "caption": "Isapre",
              "key": 3,
              ...
            }
            ...
          ]
        }
      ],
      "axis_dimensions": [
        {
          "name": "Measures",
          "caption": "Measures",
          "type": "measures",
          "level": "MeasuresLevel",
          "level_depth": 0
        },
        {
          "name": "Health System",
          "caption": "Health System",
          "type": "standard",
          "level": "Health System Group",
          "level_depth": 1
        }
      ],
      "values": [
        [ 1130724.0 ],
        [ 62378.0 ],
        [ 255801.0 ],
        [ 81866.0 ]
      ]
    }
                

Combinaciones Complejas

Estos criterios se pueden combinar para definir consultas robustas. Aquí están algunos ejemplos.

Seleccionar los valores de las regiones de Valparaíso (ID 5) y de Coquimbo (ID 4)

Para realizar cortes por más de un ID, cada cut debe estar separado por , dentro de {}.

Obtener las importaciones de todas las comunas de Chile entre los años 2013 y 2015.

Para realizar cortes por más de un ID, cada cut debe estar separado por , dentro de {}.

Cliente Mondrian-REST para npm

https://github.com/Datawheel/mondrian-rest-client

Cliente API para Python

Para fomentar el uso de la API de DataChile, hemos habilitado en Python un módulo que permite interactuar con todos los datos disponibles.

Para instalar, puedes usar pip: pip install datachile


    from datachile import ChileCube

    client = ChileCube()

    query = client.get(
        "exports", 
        {
            "drilldowns": [
                ["Date", "Year"],
                ["Destination Country", "Country", "Country"]
            ],
            "measures": ["FOB US"],
            "cuts": [
                {
                    "drilldown": ["Date", "Year"],
                    "values": [2012, 2013, 2014]
                }
            ],
            "parents": True
        }
    )

    print(query)
            

Mayor información en https://github.com/datachile/datachile-python-client/