Skip to main content

Api Creation

note

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:

NameTypeDescription
configDefaultAppApiConfigProvide config to override config defined in app.api property of the environments defined in the environment folder of the project.
optionsFunction | ApiRequestOptionsAn object with options that will be passed to the HttpRequest.

options

NameTypeDescription
handleResponseFunctionA function that will be called on every response returned by a request created with createRequest function.
headersHeadersHeaders to be appended to every request created with createRequest function.
urlParamsURLSearchParams | SearchParamsSearch params to be appended to every request created with createRequest function.
throwOnErrorbooleanIf true, the request will throw an error instead of returning a response with an error status.
handleResponseFunctionA function that will be called on every response returned by a request created with createRequest or passed directly in createApi options.
handleErrorFunctionA function that will be called on error response. Allows overriding global error handling logic.
bodyTPayloadThe payload to be sent with the request.
headersHeadersHeaders to be appended to every request.
paramsURLSearchParams | SearchParamsSearch parameters to be appended to the request URL.
retryRetryOptionsConfiguration for request retry strategy.
ssrbooleanIf false, the request will only be executed on the client.
versionstringVersion segment to include in the request URL.
timeoutnumberAborts the request after the specified number of milliseconds.
allowEmptyStringbooleanIf true, allows empty string values in the request payload.
skipBodyParsingbooleanSkips automatic body parsing when set to true.
schemaz.ZodType<TBody, any, any>Zod schema used for response validation.
throwOnErrorbooleanIf true, throws on non-2xx responses instead of resolving with an error.
cacheRequestCacheCache strategy for the request.
blockPromise<any> &#124; nullBlocks the request until the promise is resolved.
shouldRetry(error: unknown) => boolean &#124; 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 &#124; Promise<void>Custom handler for 401 Unauthorized errors.
replace{ headers?: boolean; params?: boolean }If true, replaces default headers or params with provided ones.

config

NameTypeDescription
schemastringDefines the schema for requests. E.g. https://localhost:3100/<schema>/path
versionstringDefines the version segment of the API URL. E.g. https://localhost:3100/jsapi/<version>/path
protocolstring | nullDefines protocol used in the request URL. E.g. https://localhost:3100/jsapi/v2/path
hoststring | nullDefines host used in the request URL. E.g. https://<host>:3100/jsapi/v2/path
portstring | number | nullDefines port used in the request URL. E.g. https://localhost:<port>/jsapi/v2/path
basestringDefines base for request to the server. E.g. https://localhost:3100/<base>/v2/path
baseSitestringDefines base site needed to connect to SAP commerce.
retryRetryOptionsDefines how many times a request should be resent if it fails and first wait time to delay.
headersDefaultHeaderDefines static headers.
mockedMockedIf 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:

NameTypeDefaultRequiredDescription
urlstring✔️A relative URL of the request.
methodHttpMethodA HTTP method.
targetstringDefines base for request to the server. E.g. https://localhost:3100/<base>/v2/path
handleResponseFunction
  • handleResponse function defined in the parameters of createApi or
  • DefaultHandleResponse function
A function that will be called on the response returned by the request.
throwOnErrorbooleanIf true, the request will throw an exception when an error occurs instead of returning it in the response.
handleErrorFunctionA function that will be called when the request fails. Can transform or enrich the error response.
bodygeneric valueunknownThe payload to send with the request.
headersHeadersHeaders to be appended to the request.
paramsURLSearchParams | SearchParamsSearch parameters to be appended to the request.
schemaZodTypeA Zod schema that will validate the backend response and automatically infer the type of the resolved Promise
retryRetryOptionsAn object containing options for the retry functionality.
ssrbooleanIf false, the request will only be executed on the client.
timeoutnumber30sAborts 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.
versionstringAdds a version to the request URL. E.g. https://localhost:3100/jsapi/v<version>/path.
allowEmptyStringbooleanAllows empty strings in the request body.
skipBodyParsingbooleanSkips automatic parsing of the response body.
cacheRequestCacheControls the request’s caching behavior.
blockPromise<any> &#124; nullBlocks the request execution until the given promise resolves. Useful for deferred logic.
shouldRetry(error: unknown) => boolean &#124; 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> &#124; unknown, requestOptions: DefaultRequestOptions) => void &#124; 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);