Skip to content
Merged
Show file tree
Hide file tree
Changes from 63 commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
beaf4d3
docs: adds article on working with the Fetch API
iOvergaard May 8, 2025
05c9a9a
docs: adds article on http-client
iOvergaard May 8, 2025
a129be6
docs: adds overview and main README
iOvergaard May 8, 2025
5661fcc
docs: updates code samples after testing
iOvergaard May 8, 2025
20a72e7
docs: corrects wrong variable use
iOvergaard May 8, 2025
2154db3
docs: adds an article on how to execute requests
iOvergaard May 14, 2025
bf64093
docs: adds reference to new article
iOvergaard May 14, 2025
5d7e975
docs: removes warning
iOvergaard May 14, 2025
590dfe5
docs: adds an article on generating your own custom client
iOvergaard May 14, 2025
1b2687d
docs: adds bullets to why to choose the http-client
iOvergaard May 14, 2025
dd9ce4a
docs: name the client the same
iOvergaard May 14, 2025
ae00ae6
docs: clarify what a custom client is
iOvergaard May 14, 2025
dc0ad38
docs: clarify what the umbraco http client is
iOvergaard May 14, 2025
a5177c5
docs: adds an advanced topics section
iOvergaard May 14, 2025
f90e7c7
docs: adds examples on authentication
iOvergaard May 14, 2025
1ad9cee
docs: adds extra bullet
iOvergaard May 14, 2025
0666e56
docs: align naming of http client
iOvergaard May 14, 2025
d4a4236
docs: simplify example
iOvergaard May 14, 2025
d3e6d16
docs: adds warning about error handling
iOvergaard May 14, 2025
e60bde1
docs: adds links and other helpful tips
iOvergaard May 14, 2025
fa5af18
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
iOvergaard May 14, 2025
cf56998
Update 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
iOvergaard May 16, 2025
c6a5c94
Apply suggestions from code review
iOvergaard May 16, 2025
95e3067
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
ce084da
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
efca7a4
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
8478a29
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
1610574
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
fb99c21
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
8e7b26a
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
656054a
Update 16/umbraco-cms/customizing/foundation/fetching-data/try-execut…
eshanrnh May 16, 2025
ed25570
Update 16/umbraco-cms/customizing/foundation/fetching-data/try-execut…
eshanrnh May 16, 2025
1e03647
Update 16/umbraco-cms/customizing/foundation/fetching-data/try-execut…
eshanrnh May 16, 2025
0459273
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
a4d1712
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
a3b17c3
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
150a085
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
538ed00
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
a29574f
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
3fceda7
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
89e917f
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
742d345
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
ed1df4f
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
16dfc18
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
f957799
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
fcba065
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
5822ddd
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
ebae84f
Update 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
eshanrnh May 16, 2025
7e796c8
Update 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
eshanrnh May 16, 2025
e7fa87b
Update 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
eshanrnh May 16, 2025
97b8ac9
Update 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
eshanrnh May 16, 2025
c91b4f9
Update 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
eshanrnh May 16, 2025
ac48356
Update 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
eshanrnh May 16, 2025
7b4d4bf
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
69b4b52
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
8131140
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
9eece0d
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
9eefa33
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
930d333
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
b90ba6a
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
545c7cd
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
d4b5a1a
Update 16/umbraco-cms/customizing/foundation/fetching-data/http-clien…
eshanrnh May 16, 2025
3dc3c9e
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
d88e2d2
Update 16/umbraco-cms/customizing/foundation/fetching-data/README.md
eshanrnh May 16, 2025
682e137
Update 16/umbraco-cms/customizing/foundation/fetching-data/custom-gen…
eshanrnh May 16, 2025
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions 16/umbraco-cms/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,11 @@
* [Extension Conditions](customizing/extending-overview/extension-conditions.md)
* [Custom Extension types](customizing/extending-overview/custom-extension-type.md)
* [Foundation](customizing/foundation/README.md)
* [Fetching Data](customizing/foundation/fetching-data/README.md)
* [Fetch API](customizing/foundation/fetching-data/fetch-api.md)
* [Umbraco HTTP Client](customizing/foundation/fetching-data/http-client.md)
* [Executing Requests](customizing/foundation/fetching-data/try-execute.md)
* [Custom Generated Client](customizing/foundation/fetching-data/custom-generated-client.md)
* [Working with Data](customizing/foundation/working-with-data/README.md)
* [Repositories](customizing/foundation/working-with-data/repositories.md)
* [Context API](customizing/foundation/working-with-data/context-api.md)
Expand Down
64 changes: 64 additions & 0 deletions 16/umbraco-cms/customizing/foundation/fetching-data/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
---
description: Learn how to request data when extending the Backoffice.
---

# Fetching Data

## Fetch Data Through HTTP

There are two main ways to fetch data through HTTP in the Umbraco Backoffice:

- [Fetch API](#fetch-api)
- [Umbraco HTTP Client](#umbraco-http-client).

The Fetch API is a modern way to make network requests in JavaScript, while the Umbraco HTTP client is a wrapper around it, providing a more convenient interface.

Check warning on line 14 in 16/umbraco-cms/customizing/foundation/fetching-data/README.md

View workflow job for this annotation

GitHub Actions / runner / vale

[vale] reported by reviewdog 🐶 [UmbracoDocs.SentenceLength] Write shorter sentences (less than 25 words). Raw Output: {"message": "[UmbracoDocs.SentenceLength] Write shorter sentences (less than 25 words).", "location": {"path": "16/umbraco-cms/customizing/foundation/fetching-data/README.md", "range": {"start": {"line": 14, "column": 1}}}, "severity": "WARNING"}


For most scenarios, the Umbraco HTTP Client is recommended because it:

- Automatically handles authentication and error handling.
- Provides type safety for requests and responses.
- Simplifies request and response parsing.
- Integrates seamlessly with the Backoffice.

The Fetch API is an alternative for simpler use cases.

The following table provides a comparison of the two options:

| Feature | [Fetch API](fetch-api.md) | [Umbraco HTTP Client](http-client.md) |
|------------------------|-------------------------------|------------------------------|
| Authentication | Manual | Automatic |
| Error Handling | Manual | Built-in |
| Type Safety | No | Yes |
| Request Cancellation | Yes (via AbortController) | Yes (via AbortController) |
| Recommended Use Case | Common requests | Complex or frequent requests |

After selecting a method, refer to the sections below for implementation details and guidance on handling the received data.

### [Fetch API](fetch-api.md)

The Fetch API is a modern way to make network requests in JavaScript. It provides a more powerful and flexible feature set than the older XMLHttpRequest.

### [Umbraco HTTP Client](http-client.md)

The Umbraco HTTP Client is a wrapper around the Fetch API that provides a more convenient way to make network requests. It handles request and response parsing, error handling, and retries.

## Handle Requests

Once you have chosen a method to fetch data, the next step is to handle the execution of requests. This includes managing errors, refreshing tokens, and ensuring proper authentication.

## [Executing Requests](try-execute.md)

After fetching data, the next step is to execute the request. You can use the `tryExecute` function to handle errors and refresh the token if it is expired.

## Advanced Topics

### [Custom Generated Client](custom-generated-client.md)

For advanced scenarios, you can generate a custom client for your API using tools like `[@hey-api/openapi-ts](https://github.com/hey-api/openapi-ts)`. This approach is ideal when working with custom API controllers or when you need type-safe, reusable client code.

## Further Reading

### [Working with Data](../working-with-data/README.md)

After retrieving data using one of the methods above, see the [Working with Data](../working-with-data/README.md) article for more information.
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
---
description: Learn how to create a custom generated client with TypeScript types for your OpenAPI specification.
---

# Custom Generated Client

Umbraco uses [@hey-api/openapi-ts](https://heyapi.dev/openapi-ts/get-started) to generate its HTTP client for the OpenAPI specification of the Management API. It is available through the `@umbraco-cms/backoffice/http-client` package.

Check warning on line 7 in 16/umbraco-cms/customizing/foundation/fetching-data/custom-generated-client.md

View workflow job for this annotation

GitHub Actions / runner / vale

[vale] reported by reviewdog 🐶 [UmbracoDocs.Names] We prefer TypeScript over 'ts' Raw Output: {"message": "[UmbracoDocs.Names] We prefer TypeScript over 'ts'", "location": {"path": "16/umbraco-cms/customizing/foundation/fetching-data/custom-generated-client.md", "range": {"start": {"line": 7, "column": 32}}}, "severity": "WARNING"}

{% content-ref url="http-client.md" %}
[http-client.md](http-client.md)
{% endcontent-ref %}

The following examples show how to generate a client from an OpenAPI specification and how to use it in the project. Below, the `@hey-api/openapi-ts` library is used, but the same principles apply to any other library that generates a TypeScript client.

## Generate your own client

The generated client provides a convenient way to make requests to the specified API with type-safety without having to manually write the requests yourself. Consider generating a client to save time and reduce effort when working with custom API controllers.

To get started, install the generator using the following command:

```bash
npm install @hey-api/openapi-ts
```

Then, use the `openapi-ts` command to generate a client from your OpenAPI specification:

```bash
npx openapi-ts generate --url https://example.com/openapi.json --output ./my-client
```

This will generate a TypeScript client in the `./my-client` folder. Import the generated client into your project to make requests to the Management API.

To learn more about OpenAPI and how to define your API specification, visit the [OpenAPI Documentation](https://swagger.io/specification/).

## Connecting to the Management API

You will need to set up a few configuration options in order to connect to the Management API. The following options are required:

- `auth`: The authentication method to use. This is typically `Bearer` for the Management API.
- `baseUrl`: The base URL of the Management API. This is typically `https://example.com/umbraco/api/management/v1`.
- `credentials`: The credentials to use for the request. This is typically `same-origin` for the Management API.

You can set these options either directly with the `openapi-ts` command or in a central place in your code. For example, you can create a [BackofficeEntryPoint](../../extending-overview/extension-types/backoffice-entry-point.md) that sets up the configuration options for the HTTP client:

```javascript
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';
import { client } from './my-client/client.gen';

export const onInit = (host) => {
host.consumeContext(UMB_AUTH_CONTEXT, (authContext) => {
// Get the token info from Umbraco
const config = authContext?.getOpenApiConfiguration();

client.setConfig({
auth: config?.token ?? undefined,
baseUrl: config?.base ?? "",
credentials: config?.credentials ?? "same-origin",
});
});
};
```

This sets up the HTTP client with the Management API’s base URL and authentication method.. You can then use the client to make requests to the Management API.

Check warning on line 63 in 16/umbraco-cms/customizing/foundation/fetching-data/custom-generated-client.md

View workflow job for this annotation

GitHub Actions / runner / vale

[vale] reported by reviewdog 🐶 [UmbracoDocs.SentenceLength] Write shorter sentences (less than 25 words). Raw Output: {"message": "[UmbracoDocs.SentenceLength] Write shorter sentences (less than 25 words).", "location": {"path": "16/umbraco-cms/customizing/foundation/fetching-data/custom-generated-client.md", "range": {"start": {"line": 63, "column": 1}}}, "severity": "WARNING"}

{% hint style="info" %}
See the example in action in the [Umbraco Extension Template](../../development-flow/umbraco-extension-template.md).
{% endhint %}

### Fetch API

A Backoffice Entry Point is recommended when working with multiple requests. However, if you only have a few requests to make, you can use the `fetch` function directly. Read more about that here:

{% content-ref url="fetch-api.md" %}
[fetch-api.md](fetch-api.md)
{% endcontent-ref %}

**Setting the client directly**
You can also set the client directly in your code. This is useful if you only have a few requests to make and don't want to set up a Backoffice Entry Point.

```javascript
import { getMyControllerAction } from './my-client';
import { tryExecute } from '@umbraco-cms/backoffice/resources';
import { umbHttpClient } from '@umbraco-cms/backoffice/http-client';

const { data } = await tryExecute(this, getMyControllerAction({
client: umbHttpClient, // Use Umbraco's HTTP client
}));

if (data) {
console.log('Server status:', data);
}
```

The above example shows how to use the `getMyControllerAction` function, which is generated through `openapi-ts`. The `client` parameter is the HTTP client that you want to use. You can use any HTTP client that implements the underlying interface from `@hey-api/openapi-ts`, which the Umbraco HTTP Client does. The `getMyControllerAction` function will then use the Umbraco HTTP client over its own to make the request to the Management API.

## Further reading

- `[@hey-api/openapi-ts](https://heyapi.dev/openapi-ts/get-started)`
- [Creating a Backoffice API](../../../tutorials/creating-a-backoffice-api/README.md)
183 changes: 183 additions & 0 deletions 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
---
description: The Fetch API is a modern way to make network requests in JavaScript. It provides a more powerful and flexible feature set than the older XMLHttpRequest.
---

# Fetch API

The [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is a Promise-based API that allows you to make network requests similar to XMLHttpRequest. It is a modern way to make network requests in JavaScript and provides a more powerful and flexible feature set than the older XMLHttpRequest. It is available in all modern browsers and is the recommended way to make network requests in JavaScript.

## Fetch API in Umbraco

The Fetch API can also be used in Umbraco to make network requests to the server. Since it is built into the browser, you do not need to install any additional libraries or packages to use it. The Fetch API is available in the global scope and can be used directly in your JavaScript code.
The Fetch API is a great way to make network requests in Umbraco because it provides a lot of flexibility. You can use it to make GET, POST, PUT, DELETE, and other types of requests to the server. You can also use it to handle responses in a variety of formats, including JSON, text, and binary data.

### Example

For this example, we are using the Fetch API to make a GET request to the `/umbraco/MyApiController/GetData` endpoint. The response is then parsed as JSON and logged to the console.

{% hint style="info" %}
The example assumes that you have a controller set up at the `/umbraco/MyApiController/GetData` endpoint that returns JSON data. You can replace this with your own endpoint as needed. Read more about creating a controller in the [Controllers](../../../implementation/controllers.md) article.
{% endhint %}

If there is an error with the request, it is caught and logged to the console:

```javascript
const data = await fetch('/umbraco/MyApiController/GetData')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});

if (data) {
console.log(data); // Do something with the data
}
```


{% hint style="warning" %}
When using the Fetch API, you need to manually handle errors and authentication. For most scenarios, we recommend using the Umbraco HTTP Client, which provides built-in error handling and authentication.
{% endhint %}

## Authentication

When making requests to the Umbraco API controllers, you may need to include an authorization token in the request headers. This is especially important when making requests to endpoints that require authentication.

The Fetch API does not automatically include authentication tokens in requests. You need to manually add the authentication token to the request headers. While you can manage tokens manually, the recommended approach in the Backoffice is to use the **UMB_AUTH_CONTEXT**. This context provides tools to manage authentication tokens and ensures that your requests are properly authenticated.

### Example: Using `UMB_AUTH_CONTEXT` for Authentication

{% hint style="info" %}
The example assumes that you have a valid authentication token. You can replace this with your own token as needed. Read more about authentication in the [Security](../../../implementation/security.md) article.
{% endhint %}

The following example demonstrates how to use `UMB_AUTH_CONTEXT` to retrieve the latest token and make an authenticated request:

```javascript
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';

async function fetchData(host, endpoint) {
const authContext = await host.getContext(UMB_AUTH_CONTEXT);
const token = await authContext?.getLatestToken();

const response = await fetch(endpoint, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});

if (!response.ok) {
throw new Error('Failed to fetch data');
}

return response.json();
}

// Example usage
const data = await fetchData(this, '/umbraco/management/api/v1/server/status');
console.log(data);
```


{% hint style="warning" %}
When using the Fetch API with `UMB_AUTH_CONTEXT`, you need to handle token expiration errors manually. If the token is expired, the request will return a 401 error. You will need to refresh the token or prompt the user to log in again.
{% endhint %}

Why Use **UMB_AUTH_CONTEXT**?

- Simplifies Token Management: Automatically retrieves and refreshes tokens when needed.
- Aligns with Best Practices: Ensures your requests are authenticated in a way that integrates seamlessly with the Backoffice.
- Reduces Errors: Avoids common pitfalls like expired tokens or incorrect headers.

{% hint style="info" %}
The **UMB_AUTH_CONTEXT** is only available in the Backoffice. For external applications, you will need to manage tokens manually or use an API user. Read more about API users in the [API Users](../../../fundamentals/data/users/api-users.md) article.
{% endhint %}

## Management API Controllers

The Fetch API can also be used to make requests to the Management API controllers. The Management API is a set of RESTful APIs that allow you to interact with Umbraco programmatically. You can use the Fetch API to make requests to the Management API controllers like you would with any other API. The Management API controllers are located in the `/umbraco/api/management` namespace. You can use the Fetch API to make requests to these controllers like you would with any other API.

### API User

You can create an API user in Umbraco to authenticate requests to the Management API. This is useful for making requests from external applications or services. You can create an API user in the Umbraco backoffice by going to the Users section and creating a new user with the "API" role. Once you have created the API user, you can make requests to the Management API using the API user's credentials. You can find these in the Umbraco backoffice.

You can read more about this concept in the [API Users](../../../fundamentals/data/users/api-users.md) article.

### Backoffice Token

The Fetch API can also be used to make requests to the Management API using a Backoffice token. This is useful for making requests from custom components that are running in the Backoffice. The concept is similar to the API Users, but the Backoffice token represents the current user in the Backoffice. You will share the access policies of the current user, so you can use the token to make requests on behalf of the current user.

To use the Backoffice access token, you will have to consume the **UMB_AUTH_CONTEXT** context. This context is only available in the Backoffice and includes tools to hook on to the authentication process. You can use the [getOpenApiConfiguration](https://apidocs.umbraco.com/v16/ui-api/classes/packages_core_auth.UmbAuthContext.html#getopenapiconfiguration) method to get a configuration object that includes a few useful properties:

- `base`: The base URL of the Management API.
- `credentials`: The credentials to use for the request.
- `token()`: A function that returns the current access token.

Read more about this in the [UmbOpenApiConfiguration](https://apidocs.umbraco.com/v16/ui-api/interfaces/packages_core_auth.UmbOpenApiConfiguration.html) interface.

It is rather tiresome to manually add the token to each request. Therefore, you can wrap the Fetch API in a custom function that automatically adds the token to the request headers. This way, you can use the Fetch API without worrying about adding the token manually:

```typescript
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';
import type { UmbClassInterface } from '@umbraco-cms/backoffice/class-api';

/**
* Make an authorized request to any Backoffice API.
* @param host A reference to the host element that can request a context.
* @param url The URL to request.
* @param method The HTTP method to use.
* @param body The body to send with the request (if any).
* @returns The response from the request as JSON.
*/
async function makeRequest(host: UmbClassInterface, url: string, method = 'GET', body?: any) {
const authContext = await host.getContext(UMB_AUTH_CONTEXT);
const token = await authContext?.getLatestToken();
const response = await fetch(url, {
method,
body: body ? JSON.stringify(body) : undefined,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
});
return response.json();
}
```

The above example illustrates the process of making a request to the Management API. You can use this function to make requests to any endpoint in the Management API. The function does not handle errors or responses, so you will need to add that logic yourself, nor does it handle the authentication process. If the token is timed out, you will get a 401 error back, if the `getLatestToken` method failed to refresh the token.

## Executing the request

Regardless of method, you can execute the fetch requests through Umbraco's [tryExecute](https://apidocs.umbraco.com/v16/ui-api/classes/packages_core_auth.UmbAuthContext.html#tryexecute) function. This function will handle any errors that occur during the request and will automatically refresh the token if it is expired. If the session is expired, the function will also make sure the user logs in again.

**Example:**

```javascript
import { tryExecute } from '@umbraco-cms/backoffice/resources';

const request = makeRequest(this, '/umbraco/management/api/v1/server/status');
const response = await tryExecute(this, request);

if (response.error) {
console.error('There was a problem with the fetch operation:', response.error);
} else {
console.log(response); // Do something with the data
}
```

You can read more about the `tryExecute` function in this article:

{% content-ref url="try-execute.md" %}
[try-execute.md](try-execute.md)
{% endcontent-ref %}

## Conclusion

The Fetch API is a powerful and flexible way to make network requests in JavaScript. It is available in all modern browsers and is the recommended way to make network requests in JavaScript. The Fetch API can be used in Umbraco to make network requests to the server. It can also be used to make requests to the Management API controllers. You can use the Fetch API to make requests to any endpoint in the Management API. You can also use it to handle responses in a variety of formats. This is useful if you only need to make a few requests.

However, if you have a lot of requests to make, you might want to consider an alternative approach. You could use a library like [@hey-api/openapi-ts](https://heyapi.dev/openapi-ts/get-started) to generate a TypeScript client. The library requires an OpenAPI definition and allows you to make requests to the Management API without having to manually write the requests yourself. The generated client will only need the token once. This can save you a lot of time and effort when working with the Management API. The Umbraco Backoffice itself is running with this library and even exports its internal HTTP client. You can read more about this in the [HTTP Client](http-client.md) article.

Check warning on line 183 in 16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md

View workflow job for this annotation

GitHub Actions / runner / vale

[vale] reported by reviewdog 🐶 [UmbracoDocs.Names] We prefer TypeScript over 'ts' Raw Output: {"message": "[UmbracoDocs.Names] We prefer TypeScript over 'ts'", "location": {"path": "16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md", "range": {"start": {"line": 183, "column": 148}}}, "severity": "WARNING"}
Loading
Loading