Access external APIs
If you fetch data from external APIs in a Dynatrace App, you'll get the following error in the console:
Refused to connect to example.com/api because it violates the following Content Security Policy directive: "connect-src https://widget.usersnap.com https://fonts.googleapis.com https://dt-cdn.net 'self'"
This is because the Content Security Policy rules don't allow external APIs. By using app functions you can access any external APIs.
Create app function
Run the following command in your project directory to create an app function:
npx dt-app generate function third-party-api
It will create a api/third-party-api.ts
file. Replace the default content of the file with the following:
export default async () => {
return fetch('https://swapi.dev/api/people/1/').then((response) => response.json());
};
This app function makes a call to an external API https://swapi.dev/api/people/1
and returns the json
response.
Ensure the external host is declared in the allowlist (see this guide for more details).
Call app function
Following the API call, the app function is now available via /api/third-party-api
in our app.
Here is how you can fetch this API:
fetch(`/api/third-party-api`)
.then((response) => response.json())
.then((response) => {
console.log(response); // json object from swapi.dev
});
The response from fetch
has two methods: json()
and text()
. These methods return a promise which resolves with the result of parsing the body text as json
or text
respectively, as shown in the earlier example.