Shopify GraphQL Client - A lightweight generic GraphQL JS client to interact with Shopify GraphQL APIs
npm install @shopify/graphql-clientThe GraphQL Client can be used to interact with any Shopify's GraphQL APIs. Client users are expected to provide the full API URL and necessary headers.
``sh`
yarn add @shopify/graphql-client
`sh`
npm install @shopify/graphql-client --s
`sh`
pnpm add @shopify/graphql-client
CDN`htmlv0.9.3
// The minified version of the GraphQL API Client
`
`typescript
import {createGraphQLClient} from '@shopify/graphql-client';
const client = createGraphQLClient({
url: 'http://your-shop-name.myshopify.com/api/2023-10/graphql.json',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': 'public-token',
},
retries: 1
});
`
In order to use the client within a server, a server enabled JS Fetch API will need to be provided to the client at initialization. By default, the client uses window.fetch for network requests.
`typescript
import {createGraphQLClient} from '@shopify/graphql-client';
import {fetch as nodeFetch} from 'node-fetch';
const client = createGraphQLClient({
url: 'http://your-shop-name.myshopify.com/api/2023-10/graphql.json',
headers: {
'Content-Type': 'application/json',
'X-Shopify-Storefront-Access-Token': 'public-token',
},
customFetchApi: nodeFetch
});
`
| Property | Type | Description |
| -------- | ------------------------ | ---------------------------------- |
| url | string | The GraphQL API URL |Record
| headers | | Headers to be included in requests |number
| retries? | | The number of HTTP request retries if the request was abandoned or the server responded with a Too Many Requests (429) or Service Unavailable (503) response. Default value is 0. Maximum value is 3. |(url: string, init?: {method?: string, headers?: HeaderInit, body?: string}) => Promise
| customFetchApi? | | A replacement fetch function that will be used in all client network requests. By default, the client uses window.fetch(). |(logContent:
| logger? | HTTPResponseLog\|HTTPRetryLog\|HTTPResponseGraphQLDeprecationNotice) => void | A logger function that accepts log content objects. This logger will be called in certain conditions with contextual information. |
| Property | Type | Description |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| config | {url: string, headers: Record | Configuration for the client |(operation: string, options?:
| fetch | RequestOptions) => Promise | Fetches data from the GraphQL API using the provided GQL operation string and RequestOptions object and returns the network response |
| request | RequestOptions) => Promise<ClientResponse> | Fetches data from the GraphQL API using the provided GQL operation string and RequestOptions object and returns a normalized response object |
| requestStream | RequestOptions) => Promise | Fetches GQL operations that can result in a streamed response from the API (eg. Storefront API's @defer directive). The function returns an async iterator and the iterator will return normalized stream response objects as data becomes available through the stream. |
properties| Name | Type | Description |
| ---------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| variables? | Record | Variable values needed in the graphQL operation |string
| url? | | Alternative request API URL |Record
| headers? | | Additional and/or replacement headers to be used in the request |number
| retries? | | Alternative number of retries for the request. Retries only occur for requests that were abandoned or if the server responds with a Too Many Request (429) or Service Unavailable (503) response. Minimum value is 0 and maximum value is 3. |boolean
| keepalive? | | Whether to keep a connection alive when page is unloaded before a request has completed. Default value is false. |AbortSignal
| signal? | | If this option is set, the request can be canceled by calling abort() on the corresponding AbortController. |
| Name | Type | Description |
| ----------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| data? | TData \| any | Data returned from the GraphQL API. If TData was provided to the function, the return type is TData, else it returns type any. |ResponseErrors
| errors? | | Errors object that contains any API or network errors that occured while fetching the data from the API. It does not include any UserErrors. |Record
| extensions? | | Additional information on the GraphQL response data and context. It can include the context object that contains the context settings used to generate the returned API response. |
| Name | Type | Description |
| ----------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| data? | TData \| any | Currently available data returned from the GraphQL API. If TData was provided to the function, the return type is TData, else it returns type any. |ResponseErrors
| errors? | | Errors object that contains any API or network errors that occured while fetching the data from the API. It does not include any UserErrors. |Record
| extensions? | | Additional information on the GraphQL response data and context. It can include the context object that contains the context settings used to generate the returned API response. |boolean
| hasNext | | Flag to indicate whether the response stream has more incoming data |
| Name | Type | Description |
| ----------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| networkStatusCode? | number | HTTP response status code |string
| message? | | The provided error message |any[]
| graphQLErrors? | | The GraphQL API errors returned by the server |Response
| response? | | The raw response object from the network fetch call |
`typescript
const productQuery =
query ProductQuery($handle: String) {
product(handle: $handle) {
id
title
handle
}
};
const {data, errors, extensions} = await client.request(productQuery, {
variables: {
handle: 'sample-product',
},
});
`
`typescript
const productQuery =
query ProductQuery($handle: String) {
product(handle: $handle) {
id
handle
... @defer(label: "deferredFields") {
title
description
}
}
};
const responseStream = await client.requestStream(productQuery, {
variables: {handle: 'sample-product'},
});
// await available data from the async iterator
for await (const response of responseStream) {
const {data, errors, extensions, hasNext} = response;
}
`
`typescript
const productQuery =
query ProductQuery($handle: String) {
product(handle: $handle) {
id
title
handle
}
};
const {data, errors, extensions} = await client.request(productQuery, {
variables: {
handle: 'sample-product',
},
headers: {
'Shopify-Storefront-Id': 'shop-id',
},
});
`
`typescript
const productQuery =
query ProductQuery($handle: String) {
product(handle: $handle) {
id
title
handle
}
};
const {data, errors, extensions} = await client.request(productQuery, {
variables: {
handle: 'sample-product',
},
url: 'http://your-shop-name.myshopify.com/api/unstable/graphql.json',
});
`
`typescript
const shopQuery =
query ShopQuery {
shop {
name
id
}
};
// Will retry the HTTP request to the server 2 times if the requests were abandoned or the server responded with a 429 or 503 error
const {data, errors, extensions} = await client.request(shopQuery, {
retries: 2,
});
`
`typescript
const shopQuery =
query ShopQuery {
shop {
name
id
}
};
const {data, errors, extensions} = await client.request(shopQuery, {
keepalive: true,
});
`
`typescript
import {print} from 'graphql/language';
// GQL operation types are usually auto generated during the application build
import {CollectionQuery, CollectionDeferredQuery} from 'types/appTypes';
import collectionQuery from './collectionQuery.graphql';
import collectionDeferredQuery from './collectionDeferredQuery.graphql';
const {data, errors, extensions} = await client.request
print(collectionQuery),
{
variables: {
handle: 'sample-collection',
},
}
);
const responseStream = await client.requestStream
print(collectionDeferredQuery),
{
variables: {handle: 'sample-collection'},
}
);
`
`typescript
const shopQuery =
query shop {
shop {
name
id
}
};
const response = await client.fetch(shopQuery);
if (response.ok) {
const {errors, data, extensions} = await response.json();
}
`
This log content is sent to the logger whenever a HTTP response is received by the client.
| Property | Type | Description |
| -------- | ------------------------ | ---------------------------------- |
| type | LogType['HTTP-Response'] | The type of log content. Is always set to HTTP-Response |{
| content | requestParams: [url, init?], response: Response} | Contextual data regarding the request and received response |
This log content is sent to the logger whenever the client attempts to retry HTTP requests.
| Property | Type | Description |
| -------- | ------------------------ | ---------------------------------- |
| type | LogType['HTTP-Retry'] | The type of log content. Is always set to HTTP-Retry |{
| content | requestParams: [url, init?], lastResponse?: Response, retryAttempt: number, maxRetries: number} | Contextual data regarding the upcoming retry attempt. requestParams: parameters used in the requestlastResponse: previous response retryAttempt
: the current retry attempt count maxRetries
: the maximum number of retries |
This log content is sent to the logger whenever a HTTP response with a X-Shopify-API-Deprecated-Reason is received by the client.
| Property | Type | Description |
| -------- | ------------------------ | ---------------------------------- |
| type | LogType['HTTP-Response-GraphQL-Deprecation-Notice'] | The type of log content. Is always set to HTTP-Response-GraphQL-Deprecation-Notice |{
| content | requestParams: [url, init?], deprecationNotice: string} | Contextual data regarding the request and received deprecation information |
| Property | Type | Description |
| -------- | ------------------------ | ---------------------------------- |
| url | string | Requested URL |{method?: string, headers?: HeaderInit, body?: string}` | The request information |
| init? |