Api Creation
This page is solely for educational purposes. It shows how to configure an api which per default connects to our BFF.
By default this is already configured in the default base and shop templates. Also this configuration most probably already exists in your project.
createApi
In order to execute api requests, you need to create a new api instance and create entity definitions which are then executing the fetch.
Create a new file api.ts in the src/shop/client/api/creators directory and create a new api instance as following:
import { createApi } from '@archibald/core';
const api = createApi({ options: DEFAULT_OPTIONS });
The createApi is a helper function for sending HTTP requests. It is fully integrated into Archibald's data fetching model. It has following parameters:
| Name | Type | Description |
|---|---|---|
| config | DefaultAppApiConfig | Provide config to override config defined in app.api property of the environments defined in the environment folder of the project. |
| options | Function | ApiRequestOptions | An object with options that will be passed to the HttpRequest. |
options
| Name | Type | Description |
|---|---|---|
| handleResponse | Function | A function that will be called on every response returned by a request created with createRequest function. |
| headers | Headers | Headers to be appended to every request created with createRequest function. |
| urlParams | URLSearchParams | SearchParams | Search params to be appended to every request created with createRequest function. |
| throwOnError | boolean | If true, the request will throw an error instead of returning a response with an error status. |
| handleResponse | Function | A function that will be called on every response returned by a request created with createRequest or passed directly in createApi options. |
| handleError | Function | A function that will be called on error response. Allows overriding global error handling logic. |
| body | TPayload | The payload to be sent with the request. |
| headers | Headers | Headers to be appended to every request. |
| params | URLSearchParams | SearchParams | Search parameters to be appended to the request URL. |
| retry | RetryOptions | Configuration for request retry strategy. |
| ssr | boolean | If false, the request will only be executed on the client. |
| version | string | Version segment to include in the request URL. |
| timeout | number | Aborts the request after the specified number of milliseconds. |
| allowEmptyString | boolean | If true, allows empty string values in the request payload. |
| skipBodyParsing | boolean | Skips automatic body parsing when set to true. |
| schema | z.ZodType<TBody, any, any> | Zod schema used for response validation. |
| throwOnError | boolean | If true, throws on non-2xx responses instead of resolving with an error. |
| cache | RequestCache | Cache strategy for the request. |
| block | Promise<any> | null | Blocks the request until the promise is resolved. |
| shouldRetry | (error: unknown) => boolean | Promise<boolean> | Custom logic to determine if a failed request should be retried. |
| middleware | { before?, after?, success?, error? } | Lifecycle hooks that run before and after the request. |
| handleUnauthorized | (exception, requestOptions) => void | Promise<void> | Custom handler for 401 Unauthorized errors. |
| replace | { headers?: boolean; params?: boolean } | If true, replaces default headers or params with provided ones. |
config
| Name | Type | Description |
|---|---|---|
| schema | string | Defines the schema for requests. E.g. https://localhost:3100/<schema>/path |
| version | string | Defines the version segment of the API URL. E.g. https://localhost:3100/jsapi/<version>/path |
| protocol | string | null | Defines protocol used in the request URL. E.g. https://localhost:3100/jsapi/v2/path |
| host | string | null | Defines host used in the request URL. E.g. https://<host>:3100/jsapi/v2/path |
| port | string | number | null | Defines port used in the request URL. E.g. https://localhost:<port>/jsapi/v2/path |
| base | string | Defines base for request to the server. E.g. https://localhost:3100/<base>/v2/path |
| baseSite | string | Defines base site needed to connect to SAP commerce. |
| retry | RetryOptions | Defines how many times a request should be resent if it fails and first wait time to delay. |
| headers | DefaultHeader | Defines static headers. |
| mocked | Mocked | If true, forces API calls to hit the local server and ignore remote config. |
createRequest
The createRequest function creates a new entity that can be called in the data fetching hooks.
const RETURN_VALUE = api.createRequest(PARAMETERS);
Parameters
- Type:
HttpFetchEntity|HttpMutateEntity
The HttpFetchEntity | HttpMutateEntity objects have the following properties:
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| url | string | ✔️ | A relative URL of the request. | |
| method | HttpMethod | A HTTP method. | ||
| target | string | Defines base for request to the server. E.g. https://localhost:3100/<base>/v2/path | ||
| handleResponse | Function |
| A function that will be called on the response returned by the request. | |
| throwOnError | boolean | If true, the request will throw an exception when an error occurs instead of returning it in the response. | ||
| handleError | Function | A function that will be called when the request fails. Can transform or enrich the error response. | ||
| body | generic value | unknown | The payload to send with the request. | |
| headers | Headers | Headers to be appended to the request. | ||
| params | URLSearchParams | SearchParams | Search parameters to be appended to the request. | ||
| schema | ZodType | A Zod schema that will validate the backend response and automatically infer the type of the resolved Promise | ||
| retry | RetryOptions | An object containing options for the retry functionality. | ||
| ssr | boolean | If false, the request will only be executed on the client. | ||
| timeout | number | 30s | Aborts the request when the defined timeout is reached. | |
| replace | { headers?: boolean; urlParams?: boolean; } | If true, the passed headers or search parameters will not be merged with default headers or search parameters. | ||
| version | string | Adds a version to the request URL. E.g. https://localhost:3100/jsapi/v<version>/path. | ||
| allowEmptyString | boolean | Allows empty strings in the request body. | ||
| skipBodyParsing | boolean | Skips automatic parsing of the response body. | ||
| cache | RequestCache | Controls the request’s caching behavior. | ||
| block | Promise<any> | null | Blocks the request execution until the given promise resolves. Useful for deferred logic. | ||
| shouldRetry | (error: unknown) => boolean | Promise<boolean> | A custom function to determine whether a failed request should be retried. | ||
| middleware | { before?, after?, success?, error? } | Middleware hooks for request and response lifecycle customization. | ||
| handleUnauthorized | (exception: HttpError<any> | unknown, requestOptions: DefaultRequestOptions) => void | Promise<void> | Callback triggered when the response is unauthorized (e.g. HTTP 401). |
Return value
The createRequest function returns a Promise that wraps the expected return value from the HTTP request.
register
The register function registers a middleware function that will be executed on the response of the HTTP request.
api.register(middleware);
unregister
The register function unregisters a middleware function.
api.unregister(middleware);