Skip to content

JsonApiClient

Defined in: packages/json-api-client/src/JsonApiClient.ts:31

JSON:API Client class provides functionality specific to JSON:API server.

  • ApiClient
new JsonApiClient(baseUrl, options?): JsonApiClient;

Defined in: packages/json-api-client/src/JsonApiClient.ts:57

Creates a new instance of the JsonApiClient.

string

The base URL of the API. BaseUrl

JsonApiClientOptions

(Optional) Additional options for configuring the API client. JsonApiClientOptions

JsonApiClient

ApiClient.constructor
apiPrefix: string | undefined;

Defined in: packages/api-client/dist/index.d.mts:216

ApiClientOptions.apiPrefix

ApiClient.apiPrefix

authentication: Authentication | undefined;

Defined in: packages/api-client/dist/index.d.mts:224

ApiClientOptions.authentication

ApiClient.authentication

baseUrl: string;

Defined in: packages/api-client/dist/index.d.mts:212

BaseUrl

ApiClient.baseUrl

cache: Cache | undefined;

Defined in: packages/api-client/dist/index.d.mts:232

ApiClientOptions.cache

ApiClient.cache

customFetch:
| ((input, init?) => Promise<Response>)
| undefined;

Defined in: packages/api-client/dist/index.d.mts:220

ApiClientOptions.customFetch

ApiClient.customFetch

debug: boolean | undefined;

Defined in: packages/api-client/dist/index.d.mts:244

ApiClientOptions.debug

ApiClient.debug

decoupledRouterApiPrefix: string | undefined;

Defined in: packages/json-api-client/src/JsonApiClient.ts:45

JsonApiClientOptions.decoupledRouterApiPrefix


defaultLocale: string | undefined;

Defined in: packages/api-client/dist/index.d.mts:228

ApiClientOptions.defaultLocale

ApiClient.defaultLocale

indexLookup: boolean | undefined;

Defined in: packages/json-api-client/src/JsonApiClient.ts:40

JsonApiClientOptions.indexLookup


languagePathPrefix: boolean;

Defined in: packages/json-api-client/src/JsonApiClient.ts:50

JsonApiClientOptions.languagePathPrefix


logger:
| {
debug?: LogMethod;
error?: LogMethod;
http?: LogMethod;
info?: LogMethod;
silly?: LogMethod;
verbose?: LogMethod;
warn?: LogMethod;
}
| undefined;

Defined in: packages/api-client/dist/index.d.mts:240

ApiClientOptions.logger

ApiClient.logger

router: DecoupledRouterClient;

Defined in: packages/json-api-client/src/JsonApiClient.ts:35

link DecoupledRouterClient


serializer: Serializer | undefined;

Defined in: packages/api-client/dist/index.d.mts:236

ApiClientOptions.serializer

ApiClient.serializer
addAuthorizationHeader(options): Promise<RequestInit>;

Defined in: packages/api-client/dist/index.d.mts:274

Adds an authorization header to the provided RequestInit options if authentication of type “Basic” is configured. If the authentication type is “OAuth”, it will fetch a new access token or use the stored access token if it exists and is still valid. if the authentication type is “Custom”, it will use the provided value.

RequestInit | undefined

The RequestInit options to which the authorization header should be added.

Promise<RequestInit>

The updated RequestInit options with the authorization header, if applicable.

ApiClient.addAuthorizationHeader

createResource<T>(
type,
body,
options?): Promise<
| T
| RawApiResponseWithData<T>>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:781

Create a resource of the specified type using the provided body.

T

string

The type of the entity with bundle information.

string | object

The body of the request.

CreateOptions

(Optional) Additional options for customizing the request. CreateOptions

Promise< | T | RawApiResponseWithData<T>>

A Promise that resolves to a Response object or RawApiResponseWithData.

This method initiates the creation of a resource by sending a POST request to the API.

const responseBody = await createResource("node--page", `{
"data": {
"type": "node--page",
"attributes": {
"title": "My custom title",
"body": {
"value": "Custom value",
"format": "plain_text"
}
}
}
}, { rawResponse: false });

createTranslation<T>(
type,
resourceId,
body,
options?): Promise<
| T
| RawApiResponseWithData<T>>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:870

Creates a new translation of an existing resource.

Unlike createResource (a collection POST that creates a new entity), this POSTs to the individual resource path with langCode to add a translation in the language given by locale. Requires a backend that supports creating a translation on the individual path (the jsonapi_multilingual module / core issue #3199697): the payload’s langcode attribute, if present, must match locale, and a translation that already exists is rejected as a 409 conflict.

T

string

The type of the entity with bundle information.

string

The ID of the entity to add a translation to.

string | object

The body of the request.

CreateOptions

(Optional) Additional options; locale is the target language. CreateOptions

Promise< | T | RawApiResponseWithData<T>>

A Promise that resolves to a Response object or RawApiResponseWithData.

const responseBody = await createTranslation("node--page", "7cbb8b73-8bcb-4008-874e-2bd496bd419d", body, { locale: "de" });

createURL(__namedParameters): Promise<string>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:308

Generates an endpoint URL based on the provided parameters.

EndpointUrlSegments

Promise<string>

The endpoint URL as a string.

params - The parameters to use for creating the URL. EndpointUrlSegments


deleteResource<T>(
type,
resourceId,
options?): Promise<
| T
| RawApiResponseWithData<T>>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:403

Deletes a resource of the specified type using the provided resource ID.

T

string

The type of the entity with bundle information.

string

The ID of the resource to be deleted.

DeleteOptions

(Optional) Additional options for customizing the request. DeleteOptions

Promise< | T | RawApiResponseWithData<T>>

A Promise that resolves to a Response object or RawApiResponseWithData.

const responseBody = await deleteResource("node--page", "7cbb8b73-8bcb-4008-874e-2bd496bd419d", { rawResponse: false });

fetch(input, init?): Promise<FetchReturn>;

Defined in: packages/api-client/dist/index.d.mts:257

Uses customFetch if it is set, otherwise uses the default fetch

URL | RequestInfo

RequestInfo

RequestInit

RequestInit

Promise<FetchReturn>

a response wrapped in a promise

ApiClient.fetch

protected getAccessToken(__namedParameters): Promise<OAuthTokenResponse>;

Defined in: packages/api-client/dist/index.d.mts:262

Fetch the OAuth token from the BaseUrl

OAuthCredentials

Promise<OAuthTokenResponse>

params - The credentials for getting an OAuth token. OAuthCredentials

ApiClient.getAccessToken

getCachedResponse<T>(cacheKey): Promise<
| NonNullable<Awaited<T>>
| null>;

Defined in: packages/api-client/dist/index.d.mts:286

Retrieves a cached response from the cache.

T

string

The cache key to use for retrieving the cached response.

Promise< | NonNullable<Awaited<T>> | null>

A promise wrapping the cached response as a generic type.

ApiClient.getCachedResponse

getCollection<T>(type, options?): Promise<
| T
| RawApiResponseWithData<T>>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:152

Retrieves a collection of data of a specific entity type and bundle from the JSON:API.

T

string

The type of resource to retrieve, in the format “entityType—bundle”. For example, “node—page”. EntityTypeWithBundle

GetOptions

(Optional) Additional options for customizing the request. GetOptions

Promise< | T | RawApiResponseWithData<T>>

A Promise that resolves to the JSON data of the requested resource.

Using JSONAPI.CollectionResourceDoc type from the jsonapi-typescript package

const collection = await jsonApiClient.get<JSONAPI.CollectionResourceDoc<string, Recipe>>("node--recipe");

getResource<T>(
type,
resourceId,
options?): Promise<
| T
| RawApiResponseWithData<T>>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:233

Retrieves data for a resource by ID of a specific entity type and bundle from the JSON:API.

T

string

The type of resource to retrieve, often in the format “entityType—bundle”, but may be rewritten as a single string.

string

The ID of the individual resource to retrieve.

GetOptions

(Optional) Additional options for customizing the request. GetOptions

Promise< | T | RawApiResponseWithData<T>>

A Promise that resolves to the JSON data of the requested resource.

Using JSONAPI.CollectionResourceDoc type from the jsonapi-typescript package

const collection = await jsonApiClient.get<JSONAPI.CollectionResourceDoc<string, Recipe>>("node--recipe");

getResourceByPath(path, options?): Promise<unknown>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:620

Attempts to resolve a path to a resource and then fetches the resolved resource.

string

The path to resolve and fetch.

GetOptions

(Optional) Additional options for customizing the request. GetOptions

Promise<unknown>

  • A promise that resolves to either the JSON data of the requested resource or an UnResolvedPath if the path could not be resolved.
const article = await jsonApiClient.getResourceByPath("/articles/give-it-a-go-and-grow-your-own-herbs");

getView<T>(type, options?): Promise<
| T
| RawApiResponseWithData<T>>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:544

Retrieves a collection of data of a specific view display via JSON:API views. Requires that the jsonapi_views module is enabled on your Drupal site.

T

string

The type of resource to retrieve, in the format “name—display_id”. For example, “content—page_1”.

GetOptions

(Optional) Additional options for customizing the request. GetOptions

Promise< | T | RawApiResponseWithData<T>>

A Promise that resolves to the JSON data of the requested collection.

Using JSONAPI.CollectionResourceDoc type from the jsonapi-typescript package

const view = await jsonApiClient.getView<JSONAPI.CollectionResourceDoc<string, Recipe>>("recipes--page_1");

log(level, message): void;

Defined in: packages/api-client/dist/index.d.mts:280

Calls the appropriate logger method based on level

LogLevels

level based on npm log levels

string

the message to log

void

ApiClient.log

processApiResponseAndParseBody<T>(
response,
cacheKey,
options?): Promise<string | T>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:952

Processes the API response and returns the JSON data.

T

Response

The response object from the API.

string

The cache key to use for caching the response.

| GetOptions | UpdateOptions | CreateOptions

(Optional) Additional options for customizing the request. UpdateOptions | CreateOptions

Promise<string | T>


protected resolveLanguage(locale?): object;

Defined in: packages/json-api-client/src/JsonApiClient.ts:101

Resolves how the targeted language is carried on the wire.

The language is sent twice so the same request works whether the backend selects a translation by URL prefix (stock Drupal, which ignores langCode) or by the langCode query parameter (the jsonapi_multilingual module, whose only language selector is langCode): as the /{locale}/ path prefix (disable via languagePathPrefix: false, recommended for jsonapi_multilingual backends) and as langCode.

string

The target language, or undefined for none.

object

The path prefix and langCode to apply, each present only when it should be sent.

optional langCode?: string;
optional prefix?: string;

updateResource<T>(
type,
resourceId,
body,
options?): Promise<
| T
| RawApiResponseWithData<T>>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:678

Updates a resource of the specified type using the provided resource ID.

T

string

The type of the entity with bundle information.

string

The ID of the resource to be updated.

string | object

The body of the request.

UpdateOptions

(Optional) Additional options for customizing the request. UpdateOptions

Promise< | T | RawApiResponseWithData<T>>

A Promise that resolves to a Response object or RawApiResponseWithData.

This method initiates the update of a resource by sending a PATCH request to the API.

const responseBody = await updateResource("node--page", "7cbb8b73-8bcb-4008-874e-2bd496bd419d", `{
"data": {
"type": "node--page",
"id": "11fc449b-aca0-4b74-bc3b-677da021f1d7",
"attributes": {
"drupal_internal__nid": 2,
"drupal_internal__vid": 3,
"langcode": "en",
"revision_log": null,
"status": true,
"title": "test 2"
}
}
}`, { rawResponse: false });

static createCacheKey(__namedParameters): Promise<string>;

Defined in: packages/json-api-client/src/JsonApiClient.ts:495

Generates a cache key based on the provided parameters. If the cacheKey parameter is provided, it will be used as the cache key.

EndpointUrlSegments

Promise<string>

A promise wrapping the generated cache key as a string.

params - The parameters to use for generating the cache key. EndpointUrlSegments

// Generate a cache key with entityTypeId and bundleId only
const key1 = await MyClass.createCacheKey('entity1', 'bundle1');
// key1: 'entity1--bundle1'
// Generate a cache key with entityTypeId, bundleId, localeSegment, and queryString
const key2 = await MyClass.createCacheKey('entity2', 'bundle2', 'en-US', 'param1=value1&param2=value2');
// key2: 'en-US--entity2--bundle2--<sha256_hash_of_query_string>'

static getEntityTypeIdAndBundleId(type): object;

Defined in: packages/json-api-client/src/JsonApiClient.ts:468

string

object

bundleId: string;
entityTypeId: string;

protected static languageQuery(
queryString?,
langCode?,
includeFallback?): string | undefined;

Defined in: packages/json-api-client/src/JsonApiClient.ts:125

Merges the language-selection query parameters into a caller-supplied query string. langCode targets one translation; includeFallback=1 defers a missing translation to the site’s language fallback chain and is only valid alongside langCode, so it is dropped without one.

string

The caller-supplied query string, if any.

string

The language to target, if any.

boolean

Whether to opt into server-side fallback.

string | undefined

The combined query string, or undefined when empty.