Ir para o conteúdo principal

Recipe: API request that returns JSON (prettified)

em Widgets
Lista de autores
Publicado: 12 de nov. de 2021|Última atualização: 12 de nov. de 2021

In this recipe we’re going to create a widget that will fetch some JSON data from a remote server and render it using a formatter to "prettify" the output so that the JSON is more readable.

Firstly, create a new widget and under the “Description” tab, give the widget a title and description.

We don’t to define any settings or special permissions. We do need to define the following:

  • Ticket Target - Under the "Settings" tab check "Ticket" under targets

We're going to use an existing JSON formatter so, under the “Code” tab, in the “head” section add the following code:

<script src="https://unpkg.com/json-formatter-js@2.3.4/dist/json-formatter.umd.js"></script>
copy

Then, under the "body" section of the "Code" tab add the following:

<div class="container" id="content"></div> <script> Deskpro.client.onShow(function () { fetch("https://dinoipsum.com/api/?format=json").then(function (response) { response.json().then(function (data) { var formatted = new JSONFormatter(data, Infinity).render(); document.getElementById('content').appendChild(formatted); Deskpro.client.resize(); }); }); }); </script>
copy

image.png

Let's break down this example. Firstly, the setup of this example is the same as our requesting HTML example, however this time we've told the API to return JSON instead of HTML. Next, we'll ask the fetch() response to return a JSON object instead of text/html using the json() method and promise.

Next, we pass the JSON to the formaller library and append the DOM elements it creates to the container div.

Ok, let's take a look at the widget in the Deskpro agent interface. Select any ticket and click on our newly created widget in the ticket sidebar and you should see the following:

image.png

ÚtilNão útil
próxima páginaRecipe: API request that uses the proxy
página anteriorRecipe: API request that returns HTML

Por favor, faça login ou registre-se para enviar um comentário.