diff --git a/16/umbraco-cms/SUMMARY.md b/16/umbraco-cms/SUMMARY.md index 4b67e4f3a66..644240cc184 100644 --- a/16/umbraco-cms/SUMMARY.md +++ b/16/umbraco-cms/SUMMARY.md @@ -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) diff --git a/16/umbraco-cms/customizing/foundation/fetching-data/README.md b/16/umbraco-cms/customizing/foundation/fetching-data/README.md new file mode 100644 index 00000000000..46469d6762e --- /dev/null +++ b/16/umbraco-cms/customizing/foundation/fetching-data/README.md @@ -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. + + +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. diff --git a/16/umbraco-cms/customizing/foundation/fetching-data/custom-generated-client.md b/16/umbraco-cms/customizing/foundation/fetching-data/custom-generated-client.md new file mode 100644 index 00000000000..0729a3e1921 --- /dev/null +++ b/16/umbraco-cms/customizing/foundation/fetching-data/custom-generated-client.md @@ -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. + +{% 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. + +{% 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) diff --git a/16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md b/16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md new file mode 100644 index 00000000000..b21582a6b94 --- /dev/null +++ b/16/umbraco-cms/customizing/foundation/fetching-data/fetch-api.md @@ -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. diff --git a/16/umbraco-cms/customizing/foundation/fetching-data/http-client.md b/16/umbraco-cms/customizing/foundation/fetching-data/http-client.md new file mode 100644 index 00000000000..a1d353338d5 --- /dev/null +++ b/16/umbraco-cms/customizing/foundation/fetching-data/http-client.md @@ -0,0 +1,55 @@ +--- +description: Learn more about working with the Umbraco HTTP Client. +--- + +# HTTP Client + +The Umbraco Backoffice includes a built-in HTTP client commonly referred to as the Umbraco HTTP Client for making network requests. It is generated using `@hey-api/openapi-ts` around the OpenAPI specification and is available through the `@umbraco-cms/backoffice/http-client` package. + +**Example:** + +```javascript +import { umbHttpClient } from '@umbraco-cms/backoffice/http-client'; + +const { data } = await umbHttpClient.get({ + url: '/umbraco/management/api/v1/server/status' +}); + +if (data) { + console.log('Server status:', data); +} +``` + +The above example shows how to use the Umbraco HTTP client to make a GET request to the Management API. The `umbHttpClient` object provides methods for making requests, including `get`, `post`, `put`, and `delete`. Each method accepts an options object with the URL, headers, and body of the request. + +The Umbraco HTTP client automatically handles authentication and error handling, so you don't have to worry about those details. It also provides a convenient way to parse the response data as JSON. + +## Using the Umbraco HTTP Client + +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. The Umbraco HTTP client is available through the `@umbraco-cms/backoffice/http-client` package, which is included in the Umbraco Backoffice. You can use it to make requests to any endpoint in the Management API or to any other API. + +The recommended way to use the Umbraco HTTP Client is with the `tryExecute` function. This function handles any errors that occur during the request and automatically refreshes the token if it has expired. If the session has expired, it prompts the user to log in again. + +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 %} + +## Generating a Custom Client + +You can also generate your own client using the `@hey-api/openapi-ts` library. This library allows you to generate a TypeScript client from an OpenAPI specification. The generated client will handle authentication and error handling for you, so you don't have to worry about those details. + +Read more about generating your own client here: + +{% content-ref url="custom-generated-client.md" %} +[custom-generated-client.md](custom-generated-client.md) +{% endcontent-ref %} + +## Further reading + +- [@hey-api/openapi-ts](https://heyapi.dev/openapi-ts/get-started) +- [@umbraco-cms/backoffice/http-client](https://apidocs.umbraco.com/v16/ui-api/modules/packages_core_http-client.html) +- [Using the Fetch API](fetch-api.md) +- [Working with Data](../working-with-data/README.md) +- [Creating a Backoffice Entry Point](../../extending-overview/extension-types/backoffice-entry-point.md) diff --git a/16/umbraco-cms/customizing/foundation/fetching-data/try-execute.md b/16/umbraco-cms/customizing/foundation/fetching-data/try-execute.md new file mode 100644 index 00000000000..ee4f3bd3238 --- /dev/null +++ b/16/umbraco-cms/customizing/foundation/fetching-data/try-execute.md @@ -0,0 +1,64 @@ +--- +description:: Learn how to execute requests in the Backoffice. +--- + +# Executing Requests + +Requests can be made using the Fetch API or the Umbraco HTTP client. The Backoffice also provides a `tryExecute` function that you can use to execute requests. This function handles any errors that occur during the request and automatically refreshes the token if it has expired. If the session has expired, it prompts the user to log in again. + +{% hint style="info" %} +You can read the technical documentation for the `tryExecute` function in the [UI API Documentation](https://apidocs.umbraco.com/v16/ui-api/functions/packages_core_resources.tryExecute.html) class. +{% endhint %} + +## Using the Umbraco HTTP Client + +Here is an example of how to use the `tryExecute` function with the Umbraco HTTP client: + +```javascript +import { tryExecute } from '@umbraco-cms/backoffice/resources'; +import { umbHttpClient } from '@umbraco-cms/backoffice/http-client'; + +const { data, error } = await tryExecute(this, umbHttpClient.get({ + url: '/umbraco/management/api/v1/server/status' +})); + +if (error) { + console.error('There was a problem with the fetch operation:', error); +} else { + console.log(data); // Do something with the data +} +``` + +The `tryExecute` function takes the context of the current class or element as the first argument and the request as the second argument. Therefore, the above example can be used in any class or element that extends from either the [UmbController](https://apidocs.umbraco.com/v16/ui-api/interfaces/libs_controller-api.UmbController.html) or [UmbLitElement](https://apidocs.umbraco.com/v16/ui-api/classes/packages_core_lit-element.UmbLitElement.html) classes. + +{% hint style="info" %} +The above example requires a host element illustrated by the use of `this`. This is typically a custom element that extends the `UmbLitElement` class. +{% endhint %} + +It is recommended to always use the `tryExecute` function to wrap HTTP requests. It simplifies error handling, manages token expiration, and ensures a consistent user experience in the Backoffice. + +### Disabling Notifications + +The `tryExecute` function will automatically show error bubbles if a request fails. There may be valid cases where you want to handle errors yourself. This could, for instance, be if you want to show a custom error message. You can disable the notifications by passing the `disableNotifications` option to the `tryExecute` function: + +```javascript +tryExecute(this, request, { + disableNotifications: true, +}); +``` + +### Cancelling Requests + +The `tryExecute` function also supports cancelling requests. This is useful in scenarios where a request is taking too long, or the user navigates away from the page before the request completes. You can cancel a request by using the [AbortController API](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). The `AbortController` API is a built-in API in modern browsers that allows you to cancel requests. You can use it directly with tryExecute: + +```javascript +const abortController = new AbortController(); + +// Cancel the request before starting it for illustration purposes +abortController.abort(); + +tryExecute(this, request, { + disableNotifications: true, + abortSignal: abortController.signal, +}); +``` diff --git a/16/umbraco-cms/customizing/foundation/working-with-data/README.md b/16/umbraco-cms/customizing/foundation/working-with-data/README.md index bff06641049..ee3ed8c1093 100644 --- a/16/umbraco-cms/customizing/foundation/working-with-data/README.md +++ b/16/umbraco-cms/customizing/foundation/working-with-data/README.md @@ -2,10 +2,6 @@ Learn how to work with data or request the data when extending the backoffice. -{% hint style="warning" %} -This page is a work in progress and may undergo further revisions, updates, or amendments. The information contained herein is subject to change without notice. -{% endhint %} - ## [Repositories](repositories.md) Repositories are used for talking to the server by requesting data and getting notified about updates.