Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Table of Contents

...

maxLevel7
minLevel1

Introduction

Microsoft Power BI es una herramienta de visualización y análisis de datos que permite crear visualizaciones de forma visual, permite utilizar fuentes de datos como CSV, bases de datos y como es el caso e incluso APIs Rest.

A continuación explicaremos:

  • Cómo usar un API REST como fuente de datos para importar datos JSON en Power BI

  • Cómo transformar los datos JSON en un formato tabular.

  • Cómo hacer una visualización utilizando los datos importados.

Paso 1: Instalar Power BI

Lo primero será instalar Power BI, en el ejemplo usaremos Power BI Desktop que es gratuito y nos permite crear visualizaciones en un entorno desktop (sin publicación a web).st elink:

Puedo descargarlo desde Microsoft Store o desde esta is a data visualization and analysis tool that allows you to create visualizations in a friendly way, allows you to use data sources such as CSV, databases and even Rest APIs.

We will next explain:

  • How to use a REST API as a data source to import JSON data into Power BI.

  • How to transform JSON data into a tabular format.

  • How to make a visualization using the imported data.

Step 1: Install Power BI

The first step will be to install Power BI. In the example we will use Power BI Desktop, which is free and allows us to create visualizations in a desktop environment (without publishing to the web).

I can download it from the Microsoft Store or from this url: https://powerbi.microsoft.com/es-es/desktop/.

...

...

Step 2:

...

En el ejemplo usaremos un API pública del Entorno CloudLab de Onesait Platform.

...

Identify the REST API from which I will fetch the data

In the example, we will use a public API from the Onesait Platform CloudLab Environment.

If we don't have an account, we can create a user from https://lab.onesaitplatform.com/en la opción in the SIGN UP option:

 

...

Una vez logado puedo acceder a mi entorno en el que si no he creado ningún elemento de plataforma veré una pantalla inicial como esta:

...

Lo que me interesa es buscar un API REST con información que pueda pintar en PowerBI, para eso accedo a la opción DEVELOPMENT>My REST APIs:

...

Ahí seleccionaré alguna de las APIs a las que tengo acceso, por ejemplo puedo buscar el API con información sobre los Restaurantes en New York:

...

Lo primero que haré será invocar el API para comprobar que datos devuelve y su estructura, para eso primero voy a la opción User Tokens y copio mi Token

...

Y luego voy a la opción Swagger del API seleccionada:

...

Vemos que el API sólo tiene un método GET que me devuelve todos los restaurantes:

...

Voy al método y selecciono Try it out, copiaré mi Token y pulsaré Execute:

 

...

Al ejecutarlo podré ver la estructura de cada Restaurante en el array recibido:

...

Que es esta:

...

Paso 3: Importar datos desde el API REST

Ahora abriremos Power BI, e iremos a la opción Obtener Datos> Web

 

...

En la parte de URL copiaré la URL de mi API REST Once logged, we can access our environment where, if we have not created any platform element, we will see an initial screen like this:

...

What we want to is to search for a REST API with information that we can paint in PowerBI. To do that, we access the DEVELOPMENT> My REST APIs option:

...

There we will select some of the APIs to which we have access. For example we can search the API with information about Restaurants in New York:

...

The first thing we will do is call the API to check what data it returns and its structure. To do that, we first go to the User Tokens option and copy our Token.

...

And then we go to the Swagger option of the selected API:

...

We see that the API only has a GET method that returns all the restaurants:

...

We go to the method and select Try it out. We copy our Token and press Execute:

 

...

When executing it, we will be able to see the structure of each Restaurant in the received array:

...

Which is this one:

...

Step 3: Import data from the REST API

Now we will open Power BI, and go to the option Get Data> Web

 

...

In the URL part, we will copy the URL of our REST API( https://lab.onesaitplatform.com/api-manager/server/api/v1/Restaurants%20API ) indicando Uso avanzado, specifying Advanced Use:

...

Como cabecera HTTP pondréAs HTTP header, we will write

accept: application/json

X-OP-APIKey: <mytoken>

Quedando al finaland we will have:

...

Seleccionaré Aceptar y Conectar en la siguiente pantalla.

Tras esto Power BI abrirá el Query Editor presentándome el JSON importado desde la llamada al API REST en un formato tabular, como podemos ver en la imagen:

...

Si vamos navegando por el slide podemos ver todos los campos de cada elemento JSON:

...

Y si pinchamos sobre un elemento me dará la info completa:

...

Podemos ver que el atributo Restaurant.grades es una List, si pinchamos sobre ella en la tabla accedemos a los elementos:

...

Y si pincho sobre el elemento Record el detalle:

...

Para volver a la tabla original en la ventana de PASOS APLICADOS elimino los últimos pasos:

...

Paso 4: Convertir datos importados en una Pivot Table

Para crear una visualización, es mejor convertir los datos importados en una Tabla.

Para eso voy a PASOS APLICADOS y me sitúo en el primer elemento Origen:

...

Me aparecerá la opción Convertir a Tabla que seleccionaré:

...

Seleccionaré Aceptar:

 

...

Ahora quiero que mi tabla tenga varias columnas, para los campos del JSON, para eso usaré el botón que aparece a la derecha:

...

Seleccionaré todas:

...

Y luego volveré a hacer lo mismo sobre el atributo complejo Restaurant:

...

Haré lo mismo para Column1.Restaurante.address y Column1.Restaurants.grades:

...

Ahora ya estoy viendo todos los atributos que me interesan…así que puedo pulsar en Cerrar Y Aplicar:

...

 Tras esto tendré cargada la Tabla en mi modelo y puedo ver mis columnas:

...

Paso 5: Crear una visualización en la Vista Visualización

Una vez hemos transformado los datos en una tabla con el Editor de Consultas de Power BI podemos crear una visualización.

Vamos a crear diferentes tipos de visualización:

Empecemos por el gráfico de columnas agrupadas,

...

al seleccionarlo se me incluirá una visualización en mi paleta y podré configurar los campos a visualizar arrastrándolos a los diferentes componentes. Por ejemplo en Legend puedo arrastras Column1.Restaurant.cuisine y en Legend al arrastrar el campo _id me aparecerá como Recuento:

...

Ahora seleccionaré otro componente como un gráfico circular, en este caso con las valoracionesWe will select Accept and Connect on the next screen.

After this, Power BI will open the Query Editor, presenting us the imported JSON from the REST API call in a table format, as we can see in the next image:

...

If we navigate through the slide, we can see all the fields of each JSON element:

...

And if we click on an element, it will give us the complete information on it:

...

We can see that the Restaurant.grades attribute is a List. If we click on it in the table, we access its elements:

...

And if we click on the Record element, the detail:

...

To return to the original table in the APPLIED STEPS window, we remove the last steps:

...

Step 4: Convert imported data to a Pivot Table

To create a visualization, it is beter to convert the imported data to a Table.

To do that, we go to APPLIED STEPS and we place ourselves in the first Origin element:

...

The Convert to Table option will appear, and we will select it:

...

We will select Accept:

 

...

Now we want our table to have several columns, for the JSON fields. To do that, we will use the button that appears on the right:

...

We will select all of them:

...

And then we'll do the same thing again on the Restaurant complex attribute:

...

We'll do the same for Column1.Restaurante.address and Column1.Restaurants.grades:

...

Now we are already seeing all the attributes of our interest... So we can click on Close And Apply:

...

After this, we will have the Table loaded in our model and we can see our columns:

...

Step 5: Create a visualization in Visualization View

Once we have transformed the data into a table with the Power BI Query Editor, we can create a visualization.

We are going to create different types of visualizations:

Let's start with the grouped column chart:

...

When selecting it, a visualization will be included in our palette, and we will be able to configure the fields to be visualized by dragging them to the different components. For example, in Legend, we can drag Column1.Restaurant.cuisine and in Legend, when dragging the _id field, a Count appear:

...

Now we'll select another component like a pie chart, in this case with ratings:

...