Skip to content

Commit 05c9a9a

Browse files
committed
docs: adds article on http-client
1 parent beaf4d3 commit 05c9a9a

File tree

1 file changed

+131
-0
lines changed

1 file changed

+131
-0
lines changed
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
---
2+
description: Learn more about working with the HTTP Client in Umbraco.
3+
---
4+
5+
# HTTP Client
6+
7+
Umbraco provides a built-in HTTP client that you can use to make network requests. This client is generated using **@hey-api/openapi-ts** around the OpenAPI specification and is available through the `@umbraco-cms/backoffice/http-client` package.
8+
9+
```javascript
10+
import { umbHttpClient } from '@umbraco-cms/backoffice/http-client';
11+
12+
const { data } = await umbHttpClient.get({
13+
url: '/umbraco/api/management/v1/server/status'
14+
});
15+
16+
if (data) {
17+
console.log('Server status:', data);
18+
}
19+
```
20+
21+
The above example shows how to use the 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 takes an options object that specifies the URL, headers, and body of the request.
22+
23+
The 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.
24+
25+
## Executing the request
26+
27+
The Backoffice also provides a `tryExecute` function that you can use to execute requests. This function will additionally wrap the request in a try/catch block and handle any errors that occur during the request. It will also show a notification if the request fails.
28+
29+
```javascript
30+
import { umbHttpClient } from '@umbraco-cms/backoffice/http-client';
31+
import { tryExecute } from '@umbraco-cms/backoffice/resources';
32+
33+
const { data, error } = await tryExecute(this, umbHttpClient.get({
34+
url: '/umbraco/api/management/v1/server/status'
35+
}));
36+
37+
if (error) {
38+
console.error('There was a problem with the fetch operation:', error);
39+
} else {
40+
console.log(data); // Do something with the data
41+
}
42+
```
43+
44+
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.
45+
46+
## Custom Generated Client
47+
48+
The HTTP client is generated using the [@hey-api/openapi-ts](https://heyapi.dev/openapi-ts/get-started) library. This library allows anyone to generate a TypeScript client from an OpenAPI specification. The generated client provides a convenient way to make requests to that specific API with type-safety without having to manually write the requests yourself. You can consider generating a client. This can save you a lot of time and effort when working with custom API controllers.
49+
50+
If you want to generate your own client, you can use the following command:
51+
52+
```bash
53+
npm install @hey-api/openapi-ts
54+
```
55+
56+
Then, you can use the `openapi-ts` command to generate a client from your OpenAPI specification:
57+
58+
```bash
59+
npx openapi-ts generate --url https://example.com/openapi.json --output ./my-client
60+
```
61+
62+
This will generate a TypeScript client in the `./my-client` folder. You can then import the client into your project and use it to make requests to the Management API.
63+
64+
### Connecting to the Management API
65+
66+
You will need to set up a few configuration options in order to connect to the Management API. The following options are required:
67+
68+
- `auth`: The authentication method to use. This is typically `Bearer` for the Management API.
69+
- `baseUrl`: The base URL of the Management API. This is typically `https://example.com/umbraco/api/management/v1`.
70+
- `credentials`: The credentials to use for the request. This is typically `same-origin` for the Management API.
71+
72+
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:
73+
74+
```javascript
75+
import { UMB_AUTH_CONTEXT } from '@umbraco-cms/backoffice/auth';
76+
import { client } from './my-client/client.gen';
77+
78+
export const onInit = (host) => {
79+
host.consumeContext(UMB_AUTH_CONTEXT, async (authContext) => {
80+
// Get the token info from Umbraco
81+
const config = authContext?.getOpenApiConfiguration();
82+
83+
client.setConfig({
84+
auth: config?.token ?? undefined,
85+
baseUrl: config?.base ?? "",
86+
credentials: config?.credentials ?? "same-origin",
87+
});
88+
};
89+
```
90+
91+
This will set up the HTTP client to use the Management API base URL and authentication method. You can then use the client to make requests to the Management API.
92+
93+
{% hint style="info" %}
94+
You can see the above example in action by looking at the [Umbraco Extension Template](../../development-flow/umbraco-extension-template.md).
95+
{% endhint %}
96+
97+
**Fetch API**
98+
99+
The approach with a Backoffice Entry Point is good if you have a lot of requests to make. However, if you only have a few requests to make, you can use the `fetch` function directly. Read more about that here:
100+
101+
{% content-ref url="fetch-api.md" %}
102+
[fetch-api.md](fetch-api.md)
103+
{% endcontent-ref %}
104+
105+
**Setting the client directly**
106+
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.
107+
108+
```javascript
109+
import { getMyControllerAction } from './my-client';
110+
import { tryExecute } from '@umbraco-cms/backoffice/resources';
111+
import { umbHttpClient } from '@umbraco-cms/backoffice/http-client';
112+
113+
const { data } = await tryExecute(this, getMyControllerAction({
114+
client: umbHttpClient,
115+
}));
116+
117+
if (data) {
118+
console.log('Server status:', data);
119+
}
120+
```
121+
122+
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 built-in HTTP client over its own to make the request to the Management API.
123+
124+
## Further reading
125+
126+
- [@hey-api/openapi-ts](https://heyapi.dev/openapi-ts/get-started)
127+
- [@umbraco-cms/backoffice/http-client](https://apidocs.umbraco.com/v16/ui-api/modules/packages_core_http-client.html)
128+
- [Using the Fetch API](fetch-api.md)
129+
- [Working with Data](../working-with-data/README.md)
130+
- [Creating a Backoffice API](../../../tutorials/creating-a-backoffice-api/README.md)
131+
- [Creating a Backoffice Entry Point](../../extending-overview/extension-types/backoffice-entry-point.md)

0 commit comments

Comments
 (0)