Skip to main content

Access external data

The new Dynatrace platform not only allows you to use data stored within Dynatrace, but also access any external APIs to enrich the data within your app.

Whenever you want to access APIs outside the Dynatrace platform, you have to use App functions. In this article, you'll learn how to create such a function, query data from a third-party API, and use the data in your app.

Prerequisites

As mentioned in our use case for this tutorial, the booking analytics app uses currency exchange rates to convert USD values into EUR values. To achieve this, you can use a dummy API, which returns fictional exchange rates. This API is available under https://dt-url.net/currencyrates.

1. Create app function

The first step within this section is the creation of an app function. The Dynatrace App Toolkit helps you to do this, by providing the generate function command. By executing the following command in your project directory, a file with the name get-currency-rates.ts is created in the api directory within your root project directory.

npm run generate:function get-currency-rates
note

Make sure you execute the command mentioned above in the root of your project directory.

After creating the app function, the Dynatrace App Toolkit prints some information on how you can use this function. You'll learn more about this further below in this tutorial. Every created TypeScript file in the api directory is exposed as an app function via the relative URL /api/filename.

The created function file already contains the function signature and a basic example.

2. Fetch data from external API

To fetch data within your app function, you can use the Fetch API. Fetch is always returning a Promise. That's why you've to use a Promise chain to be able to return the JSON object from the API. As the API you're using doesn't need any authentication, the code in your app function is straightforward:

api/get-currency-rates.ts
export default async () => {
return fetch('https://dt-url.net/currencyrates').then((response) => response.json());
};

You can now double-check if your function returns the data you'd expect. Make sure your local development server is running or run the following command:

npm run start

Then open the following URL in a browser of your choice:

http://localhost:3000/api/get-currency-rates

The URL should return the following JSON response:

{
"USD_EUR": 0.88,
"USD_AUD": 1.39,
"USD_PLN": 3.94,
"EUR_USD": 1.14,
"AUD_USD": 0.72,
"PLN_USD": 0.25
}

3. Use data in UI

You can now focus on consuming the function in your UI and use it accordingly. To do so, create a new function called fetchCurrencyRate in the App.tsx file. As it's a helper function and isn't directly related to the React component itself, you can place it outside the App function, directly after the import statements.

The app function returns multiple currency exchange rates. That's why the fetchCurrencyRate function takes two parameters, from and to. Based on the input, the function returns the requested currency rate.

Dynatrace offers the @dynatrace-sdk/app-utils package, making consuming your app functions very easy. To use this package, first install it by running:

npm install @dynatrace-sdk/app-utils

This package offers the call function within the functions namespace. You've to pass the name of the app function, which you want to consume. The fetchCurrencyRate function should look like the following:

src/app/App.tsx
import { functions } from '@dynatrace-sdk/app-utils';

const fetchCurrencyRate = (from: string, to: string) => {
const currencyString = `${from}_${to}`;

return functions
.call('get-currency-rates')
.then((response) => response.json())
.then((response) => response[currencyString]);
};

To only fetch the data during the first render of the page, wrap the function call within a useEffect hook and pass an empty array as the dependency list. Secondly, create a new state variable for the currencyRate via the useState hook. When calling the fetchCurrencyRate function, ensure that the result of that function is stored in the created state variable by using the setCurrencyRate function. Again, don't forget to import both useState and useEffect.

src/app/App.tsx
const [currencyRate, setCurrencyRate] = useState(0);

useEffect(() => {
fetchCurrencyRate('USD', 'EUR').then((res) => setCurrencyRate(res));
}, []);

The last step of this section is to render the fetched data in the UI. Render two additional Cards, which display the converted sum of the amount property of the respective events. As previously done, extract the final result in dedicated variables and add them before the return statement of your App.tsx file. The results from the DQL queries are multiplied with the currencyRate.

src/app/App.tsx
const totalRevenueBookingsStartedEUR = totalRevenueBookingsStarted * currencyRate;

const totalRevenueBookingsFinishedEUR = totalRevenueBookingsFinished * currencyRate;

You can copy the last two Card instances in your App.tsx file and modify their input. Pass the created variables as input for the value prop and change the chartSuffix to the Euro symbol. Additionally, you've to consider the isLoading variable and if the currency rate is already fetched to decide whether the Skeleton should be displayed or not.

The following code snippet shows the two additional Card instances:

src/app/App.tsx
 <Card
value={totalRevenueBookingsStartedEUR}
chartLabel="Total Revenue / Bookings Started"
chartSuffix=""
chartPrecision={2}
isLoading={isLoadingSumStarted || currencyRate === 0}
/>
<Card
value={totalRevenueBookingsFinishedEUR}
chartLabel="Total Revenue / Bookings Finished"
chartSuffix=""
chartPrecision={2}
isLoading={isLoadingSumFinished || currencyRate === 0}
/>
Checkpoint

Click here to see the final project source code.

Summary and next steps

In this section, you learned how to use app functions to be able to use external data and display it in your UI. This part concluded the app-building process. In the next and last section, you'll learn how you can deploy your app to the Dynatrace environment of your choice.

Still have questions?
Find answers in the Dynatrace Community