Skip to content

JsonApiClient

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

See

Extends

  • ApiClient

Constructors

new JsonApiClient()

new JsonApiClient(baseUrl, options?): JsonApiClient

Creates a new instance of the JsonApiClient.

Parameters

baseUrl: string

The base URL of the API. BaseUrl

options?: JsonApiClientOptions

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

Returns

JsonApiClient

Overrides

ApiClient.constructor

Source

json-api-client/src/JsonApiClient.ts:48

Properties

#private

private #private: any;

Inherited from

ApiClient.#private

Source

api-client/dist/index.d.mts:192


apiPrefix

apiPrefix: undefined | string;

ApiClientOptions.apiPrefix

Inherited from

ApiClient.apiPrefix

Source

api-client/dist/index.d.mts:200


authentication

authentication: undefined | Authentication;

ApiClientOptions.authentication

Inherited from

ApiClient.authentication

Source

api-client/dist/index.d.mts:208


baseUrl

baseUrl: string;

BaseUrl

Inherited from

ApiClient.baseUrl

Source

api-client/dist/index.d.mts:196


cache

cache: undefined | Cache;

ApiClientOptions.cache

Inherited from

ApiClient.cache

Source

api-client/dist/index.d.mts:216


customFetch

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

ApiClientOptions.customFetch

Inherited from

ApiClient.customFetch

Source

api-client/dist/index.d.mts:204


debug

debug: undefined | boolean;

ApiClientOptions.debug

Inherited from

ApiClient.debug

Source

api-client/dist/index.d.mts:228


decoupledRouterApiPrefix

decoupledRouterApiPrefix: undefined | string;

See

JsonApiClientOptions.decoupledRouterApiPrefix

Source

json-api-client/src/JsonApiClient.ts:41


defaultLocale

defaultLocale: undefined | string;

ApiClientOptions.defaultLocale

Inherited from

ApiClient.defaultLocale

Source

api-client/dist/index.d.mts:212


indexLookup

indexLookup: undefined | boolean;

See

JsonApiClientOptions.indexLookup

Source

json-api-client/src/JsonApiClient.ts:36


logger

logger: undefined | object;

ApiClientOptions.logger

Inherited from

ApiClient.logger

Source

api-client/dist/index.d.mts:224


router

router: DecoupledRouterClient;

link DecoupledRouterClient

Source

json-api-client/src/JsonApiClient.ts:31


serializer

serializer: undefined | Serializer;

ApiClientOptions.serializer

Inherited from

ApiClient.serializer

Source

api-client/dist/index.d.mts:220

Methods

addAuthorizationHeader()

addAuthorizationHeader(options): Promise<RequestInit>

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.

Parameters

options: undefined | RequestInit

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

Returns

Promise<RequestInit>

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

Inherited from

ApiClient.addAuthorizationHeader

Source

api-client/dist/index.d.mts:261


createResource()

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

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

Type parameters

T

Parameters

type: string

The type of the entity with bundle information.

body: string | object

The body of the request.

options?: CreateOptions

(Optional) Additional options for customizing the request. CreateOptions

Returns

Promise<T | RawApiResponseWithData<T>>

A Promise that resolves to a Response object or RawApiResponseWithData.

Remarks

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

Example

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

Source

json-api-client/src/JsonApiClient.ts:581


createURL()

createURL(__namedParameters): Promise<string>

Generates an endpoint URL based on the provided parameters.

Parameters

__namedParameters: EndpointUrlSegments

Returns

Promise<string>

The endpoint URL as a string.

Params

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

Source

json-api-client/src/JsonApiClient.ts:223


deleteResource()

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

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

Type parameters

T

Parameters

type: string

The type of the entity with bundle information.

resourceId: string

The ID of the resource to be deleted.

options?: DeleteOptions

(Optional) Additional options for customizing the request. DeleteOptions

Returns

Promise<T | RawApiResponseWithData<T>>

A Promise that resolves to a Response object or RawApiResponseWithData.

Example

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

Source

json-api-client/src/JsonApiClient.ts:301


fetch()

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

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

Parameters

input: RequestInfo | URL

RequestInfo

init?: RequestInit

RequestInit

Returns

Promise<FetchReturn>

a response wrapped in a promise

Inherited from

ApiClient.fetch

Source

api-client/dist/index.d.mts:241


getAccessToken()

protected getAccessToken(__namedParameters): Promise<OAuthTokenResponse>

Fetch the OAuth token from the BaseUrl

Parameters

__namedParameters

__namedParameters.clientId: string

__namedParameters.clientSecret: string

Returns

Promise<OAuthTokenResponse>

Inherited from

ApiClient.getAccessToken

Param0

the Client ID

Param1

the Client secret

Source

api-client/dist/index.d.mts:247


getCachedResponse()

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

Retrieves a cached response from the cache.

Type parameters

T

Parameters

cacheKey: string

The cache key to use for retrieving the cached response.

Returns

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

A promise wrapping the cached response as a generic type.

Inherited from

ApiClient.getCachedResponse

Source

api-client/dist/index.d.mts:273


getCollection()

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

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

Type parameters

T

Parameters

type: string

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

options?: GetOptions

(Optional) Additional options for customizing the request. GetOptions

Returns

Promise<T | RawApiResponseWithData<T>>

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

Example

Using JSONAPI.CollectionResourceDoc type from the jsonapi-typescript package

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

Source

json-api-client/src/JsonApiClient.ts:83


getResource()

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

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

Type parameters

T

Parameters

type: string

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

resourceId: string

The ID of the individual resource to retrieve.

options?: GetOptions

(Optional) Additional options for customizing the request. GetOptions

Returns

Promise<T | RawApiResponseWithData<T>>

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

Example

Using JSONAPI.CollectionResourceDoc type from the jsonapi-typescript package

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

Source

json-api-client/src/JsonApiClient.ts:156


getResourceByPath()

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

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

Parameters

path: string

The path to resolve and fetch.

options?: GetOptions

(Optional) Additional options for customizing the request. GetOptions

Returns

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.

Example

const article = await jsonApiClient.getResourceByPath("/articles/give-it-a-go-and-grow-your-own-herbs");

Source

json-api-client/src/JsonApiClient.ts:427


log()

log(level, message): void

Calls the appropriate logger method based on level

Parameters

level: LogLevels

level based on npm log levels

message: string

the message to log

Returns

void

Inherited from

ApiClient.log

Source

api-client/dist/index.d.mts:267


processApiResponseAndParseBody()

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

Processes the API response and returns the JSON data.

Type parameters

T

Parameters

response: Response

The response object from the API.

cacheKey: string

The cache key to use for caching the response.

options?: GetOptions | UpdateOptions | CreateOptions

(Optional) Additional options for customizing the request. CreateOptions

Returns

Promise<string | T>

Source

json-api-client/src/JsonApiClient.ts:650


updateResource()

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

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

Type parameters

T

Parameters

type: string

The type of the entity with bundle information.

resourceId: string

The ID of the resource to be updated.

body: string | object

The body of the request.

options?: UpdateOptions

(Optional) Additional options for customizing the request. UpdateOptions

Returns

Promise<T | RawApiResponseWithData<T>>

A Promise that resolves to a Response object or RawApiResponseWithData.

Remarks

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

Example

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 });

Source

json-api-client/src/JsonApiClient.ts:480


createCacheKey()

static createCacheKey(__namedParameters): Promise<string>

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

Parameters

__namedParameters: EndpointUrlSegments

Returns

Promise<string>

A promise wrapping the generated cache key as a string.

Params

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

Examples

// 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>'

Source

json-api-client/src/JsonApiClient.ts:391


getEntityTypeIdAndBundleId()

static getEntityTypeIdAndBundleId(type): object

Parameters

type: string

Returns

object

bundleId
bundleId: string;
entityTypeId
entityTypeId: string;

Source

json-api-client/src/JsonApiClient.ts:364