Skip to content

Commit beaf4d3

Browse files
committed
docs: adds article on working with the Fetch API
1 parent cde2745 commit beaf4d3

File tree

1 file changed

+148
-0
lines changed
  • 16/umbraco-cms/customizing/foundation/fetching-data

1 file changed

+148
-0
lines changed
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
---
2+
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.
3+
---
4+
5+
# Fetch API
6+
7+
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.
8+
9+
## Fetch API in Umbraco
10+
11+
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.
12+
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.
13+
14+
### Example
15+
16+
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. If there is an error with the request, it is caught and logged to the console:
17+
18+
```javascript
19+
const data = await fetch('/umbraco/MyApiController/GetData')
20+
.then(response => {
21+
if (!response.ok) {
22+
throw new Error('Network response was not ok');
23+
}
24+
return response.json();
25+
})
26+
.catch(error => {
27+
console.error('There was a problem with the fetch operation:', error);
28+
});
29+
30+
if (data) {
31+
console.log(data); // Do something with the data
32+
}
33+
```
34+
35+
{% hint style="info" %}
36+
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.
37+
{% endhint %}
38+
39+
## Authentication
40+
41+
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.
42+
43+
The Fetch API does not automatically include authentication tokens in requests. You need to manually add the authentication token to the request headers. This can be done by adding an `Authorization` header to the request:
44+
45+
```javascript
46+
const token = 'your-auth-token';
47+
const data = await fetch('/umbraco/MyApiController/GetData', {
48+
method: 'GET',
49+
headers: {
50+
'Authorization': `Bearer ${token}`,
51+
'Content-Type': 'application/json'
52+
}
53+
});
54+
```
55+
56+
{% hint style="info" %}
57+
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.
58+
{% endhint %}
59+
60+
## Management API Controllers
61+
62+
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.
63+
64+
### API User
65+
66+
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.
67+
68+
You can read more about this concept in the [API Users](../../../fundamentals/data/users/api-users.md) article.
69+
70+
### Backoffice Token
71+
72+
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.
73+
74+
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:
75+
76+
- `base`: The base URL of the Management API.
77+
- `credentials`: The credentials to use for the request.
78+
- `token()`: A function that returns the current access token.
79+
80+
Read more about this in the [UmbOpenApiConfiguration](https://apidocs.umbraco.com/v16/ui-api/interfaces/packages_core_auth.UmbOpenApiConfiguration.html) interface.
81+
82+
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:
83+
84+
```typescript
85+
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';
86+
import type { UmbClassInterface } from '@umbraco-cms/backoffice/class-api';
87+
88+
/**
89+
* Make an authorized request to any Backoffice API.
90+
* @param host A reference to the host element that can request a context.
91+
* @param url The URL to request.
92+
* @param method The HTTP method to use.
93+
* @param body The body to send with the request (if any).
94+
* @returns The response from the request as JSON.
95+
*/
96+
async function makeRequest(host: UmbClassInterface, url: string, method = 'GET', body?: any) {
97+
const authContext = await host.getContext(UMB_AUTH_CONTEXT);
98+
const token = await authContext.getLatestToken();
99+
const response = await fetch(url, {
100+
method,
101+
body: body ? JSON.stringify(body) : undefined,
102+
headers: {
103+
'Content-Type': 'application/json',
104+
'Authorization': `Bearer ${token}`,
105+
},
106+
});
107+
return response.json();
108+
}
109+
```
110+
111+
The above example serves to illustrate some of the process to make 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.
112+
113+
## Executing the request
114+
115+
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.
116+
117+
```javascript
118+
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';
119+
import { tryExecute } from '@umbraco-cms/backoffice/resources';
120+
121+
const authContext = await this.getContext(UMB_AUTH_CONTEXT);
122+
const token = await authContext.getLatestToken();
123+
const request = fetch(url, {
124+
method,
125+
body: body ? JSON.stringify(body) : undefined,
126+
headers: {
127+
'Content-Type': 'application/json',
128+
'Authorization': `Bearer ${token}`,
129+
},
130+
});
131+
const { data, error } = await tryExecute(this, request);
132+
133+
if (error) {
134+
console.error('There was a problem with the fetch operation:', error);
135+
} else {
136+
console.log(data); // Do something with the data
137+
}
138+
```
139+
140+
{% hint style="info" %}
141+
The above example requires a host element illustrated by the use of `this`. This is typically a custom element that extends the `UmbLitElement` class.
142+
{% endhint %}
143+
144+
## Conclusion
145+
146+
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 especially useful, if you have but a few requests to make.
147+
148+
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.

0 commit comments

Comments
 (0)