Továbblépés a fő tartalomra

Recipe: API request that returns JSON (prettified)

Widgets szakaszban
Szerzők listája
Publikálva: 2021. nov. 12.|Legutóbbi Frissítés Időpontja: 2021. nov. 12.

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

HasznosNem hasznos
következő oldalRecipe: API request that uses the proxy
előző oldalRecipe: API request that returns HTML

Kérjük, jelentkezzen be vagy regisztráljon, ha megjegyzést szeretne hozzáfűzni.