- Notifications
You must be signed in to change notification settings - Fork 811
V16: Documents Fetch and http-client in the Backoffice #7083
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 63 commits
beaf4d3
05c9a9a
a129be6
5661fcc
20a72e7
2154db3
bf64093
5d7e975
590dfe5
1b2687d
dd9ce4a
ae00ae6
dc0ad38
a5177c5
f90e7c7
1ad9cee
0666e56
d4a4236
d3e6d16
e60bde1
fa5af18
cf56998
c6a5c94
95e3067
ce084da
efca7a4
8478a29
1610574
fb99c21
8e7b26a
656054a
ed25570
1e03647
0459273
a4d1712
a3b17c3
150a085
538ed00
a29574f
3fceda7
89e917f
742d345
ed1df4f
16dfc18
f957799
fcba065
5822ddd
ebae84f
7e796c8
e7fa87b
97b8ac9
c91b4f9
ac48356
7b4d4bf
69b4b52
8131140
9eece0d
9eefa33
930d333
b90ba6a
545c7cd
d4b5a1a
3dc3c9e
d88e2d2
682e137
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 | ||
| ||
| ||
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 | ||
eshanrnh marked this conversation as resolved. Show resolved Hide resolved | ||
| ||
{% content-ref url="http-client.md" %} | ||
[http-client.md](http-client.md) | ||
iOvergaard marked this conversation as resolved. Show resolved Hide resolved | ||
{% 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 | ||
| ||
{% 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) | ||
iOvergaard marked this conversation as resolved. Show resolved Hide resolved | ||
{% 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)` | ||
eshanrnh marked this conversation as resolved. Outdated Show resolved Hide resolved | ||
- [Creating a Backoffice API](../../../tutorials/creating-a-backoffice-api/README.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: | ||
eshanrnh marked this conversation as resolved. Show resolved Hide resolved | ||
| ||
```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 |
Uh oh!
There was an error while loading. Please reload this page.