npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@shopify/admin-api-client

v1.0.4

Published

Shopify Admin API Client - A lightweight JS client to interact with Shopify's Admin API

Downloads

359,001

Readme

Admin API Client

The Admin API Client library is for developers who want to interact with Shopify's Admin API. The features of this library are designed to be lightweight and minimally opinionated.

npm install @shopify/admin-api-client -s

GraphQL Client

Getting Started

Initialize the client:

import {createAdminApiClient} from '@shopify/admin-api-client';

const client = createAdminApiClient({
  storeDomain: 'your-shop-name.myshopify.com',
  apiVersion: '2023-04',
  accessToken: 'your-admin-api-access-token',
});

Query for a product:

const operation = `
  query ProductQuery($id: ID!) {
    product(id: $id) {
      id
      title
      handle
    }
  }
`;

const {data, errors, extensions} = await client.request(operation, {
  variables: {
    id: 'gid://shopify/Product/7608002183224',
  },
});

[!NOTE] If you want to query the Admin REST API, you can use the REST client instead.

createAdminApiClient() parameters

| Property | Type | Description | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | storeDomain | string | The myshopify.com domain | | apiVersion | string | The requested Admin API version | | accessToken | string | The Admin API access token | | userAgentPrefix? | string | Any prefix you wish to include in the User-Agent for requests made by the library. | | retries? | number | 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. | | customFetchApi? | (url: string, init?: {method?: string, headers?: HeaderInit, body?: string}) => Promise<Response> | A replacement fetch function that will be used in all client network requests. By default, the client uses window.fetch(). | | logger? | (logContent:UnsupportedApiVersionLog \|HTTPResponseLog\|HTTPRetryLog) => void | A logger function that accepts log content objects. This logger will be called in certain conditions with contextual information. |

Client properties

| Property | Type | Description | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | config | AdminApiClientConfig | Configuration for the client | | getHeaders | (headers?: Record<string, string \| string[]>) => Record<string, string \| string[]> | Returns Admin API specific headers needed to interact with the API. If additional headers are provided, the custom headers will be included in the returned headers object. | | getApiUrl | (apiVersion?: string) => string | Returns the shop specific API url. If an API version is provided, the returned URL will include the provided version, else the URL will include the API version set at client initialization. | | fetch | (operation: string, options?:AdminAPIClientRequestOptions) => Promise<Response> | Fetches data from Admin API using the provided GQL operation string and AdminAPIClientRequestOptions object and returns the network response. | | request | <TData>(operation: string, options?:AdminAPIClientRequestOptions) => Promise<ClientResponse<TData>> | Requests data from Admin API using the provided GQL operation string and AdminAPIClientRequestOptions object and returns a normalized response object. |

AdminApiClientConfig properties

| Name | Type | Description | | ----------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | storeDomain | string | The myshopify.com domain | | apiVersion | string | The Admin API version to use in the API request | | accessToken | string | The provided public access token. If privateAccessToken was provided, publicAccessToken will not be available. | | headers | Record<string, string \| string[]> | The headers generated by the client during initialization | | apiUrl | string | The API URL generated from the provided store domain and api version | | retries? | number | The number of retries the client will attempt when the API responds with a Too Many Requests (429) or Service Unavailable (503) response |

ApiClientRequestOptions properties

| Name | Type | Description | | ----------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | variables? | Record<string, any> | Variable values needed in the graphQL operation | | apiVersion? | string | The Admin API version to use in the API request | | headers? | Record<string, string \| string[]> | Customized headers to be included in the API request | | retries? | number | 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. |

ClientResponse<TData>

| Name | Type | Description | | ----------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | data? | TData \| any | Data returned from the Admin API. If TData was provided to the function, the return type is TData, else it returns type any. | | errors? | ResponseErrors | Error object that contains any API or network errors that occured while fetching the data from the API. It does not include any UserErrors. | | extensions? | Record<string, any> | Additional information on the GraphQL response data and context. It can include the context object that contains the localization context information used to generate the returned API response. |

ResponseErrors

| Name | Type | Description | | ------------------ | ---------- | --------------------------------------------------- | | networkStatusCode? | number | HTTP response status code | | message? | string | The provided error message | | graphQLErrors? | any[] | The GraphQL API errors returned by the server | | response? | Response | The raw response object from the network fetch call |

Client request() response examples

API response

{
  "data": {
    "product": {
      "id": "gid://shopify/Product/7608002183224",
      "title": "Aera",
      "handle": "aera-helmet"
    }
  },
  "extensions": {
    "cost": {
      "requestedQueryCost": 1,
      "actualQueryCost": 1,
      "throttleStatus": {
        "maximumAvailable": 1000.0,
        "currentlyAvailable": 999,
        "restoreRate": 50.0
      }
    }
  }
}

Network error

{
  "networkStatusCode": 401,
  "message": "Unauthorized"
}

Admin API graphQL error

{
  "networkStatusCode": 200,
  "message": "An error occurred while fetching from the API. Review the `graphQLErrors` object for details.",
  "graphQLErrors": [
    {
      "message": "Field 'testField' doesn't exist on type 'Product'",
      "locations": [
        {
          "line": 17,
          "column": 3
        }
      ],
      "path": ["fragment ProductFragment", "testField"],
      "extensions": {
        "code": "undefinedField",
        "typeName": "Product",
        "fieldName": "testField"
      }
    }
  ]
}

Usage examples

Query for a product

const productQuery = `
  query ProductQuery($id: ID!) {
    product(id: $id) {
      id
      title
      handle
    }
  }
`;

const {data, errors, extensions} = await client.request(productQuery, {
  variables: {
    id: 'gid://shopify/Product/7608002183224',
  },
});

Dynamically set the Admin API version per data fetch

const productQuery = `
  query ProductQuery($id: ID!) {
    product(id: $id) {
      id
      title
      handle
    }
  }
`;

const {data, errors, extensions} = await client.request(productQuery, {
  variables: {
    id: 'gid://shopify/Product/7608002183224',
  },
  apiVersion: '2023-01',
});

Add custom headers to API request

const productQuery = `
  query ProductQuery($id: ID!) {
    product(id: $id) {
      id
      title
      handle
    }
  }
`;

const {data, errors, extensions} = await client.request(productQuery, {
  variables: {
    id: 'gid://shopify/Product/7608002183224',
  },
  headers: {
    'X-GraphQL-Cost-Include-Fields': true,
  },
});

Using client.fetch() to get API data

const shopQuery = `
  query shop {
    shop {
      name
    }
  }
`;

const response = await client.fetch(shopQuery);

if (response.ok) {
  const {errors, data, extensions} = await response.json();
}

Dynamically set the number of retries per request

const productQuery = `
  query ProductQuery($handle: String) {
    product(handle: $handle) {
      id
      title
      handle
    }
  }
`;

const {data, errors, extensions} = await client.request(productQuery, {
  variables: {
    handle: 'sample-product',
  },
  retries: 2,
});

Typing variables and return objects

This client is compatible with the @shopify/api-codegen-preset package. You can use that package to create types from your operations with the Codegen CLI.

There are different ways to configure codegen with it, but the simplest way is to:

  1. Add the preset package as a dev dependency to your project, for example:

    npm install --save-dev @shopify/api-codegen-preset
  2. Create a .graphqlrc.ts file in your root containing:

    import {ApiType, shopifyApiProject} from '@shopify/api-codegen-preset';
    
    export default {
      schema: 'https://shopify.dev/admin-graphql-direct-proxy',
      documents: ['*.ts', '!node_modules'],
      projects: {
        default: shopifyApiProject({
          apiType: ApiType.Admin,
          apiVersion: '2023-10',
          outputDir: './types',
        }),
      },
    };
  3. Add "graphql-codegen": "graphql-codegen" to your scripts section in package.json.

  4. Tag your operations with #graphql, for example:

    const {data, errors, extensions} = await client.request(
      `#graphql
      query Shop {
        shop {
          name
        }
      }`,
    );
    console.log(data?.shop.name);
  5. Run npm run graphql-codegen to parse the types from your operations.

[!NOTE] Remember to ensure that your tsconfig includes the files under ./types!

Once the script runs, it'll create the file ./types/admin.generated.d.ts. When TS includes that file, it'll automatically cause the client to detect the types for each query.

Log Content Types

UnsupportedApiVersionLog

This log content is sent to the logger whenever an unsupported API version is provided to the client.

| Property | Type | Description | | -------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | | type | LogType['Unsupported_Api_Version'] | The type of log content. Is always set to Unsupported_Api_Version | | content | {apiVersion: string, supportedApiVersions: string[]} | Contextual info including the provided API version and the list of currently supported API versions. |

HTTPResponseLog

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 |

HTTPRetryLog

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 |

RequestParams

| Property | Type | Description | | -------- | -------------------------------------------------------- | ----------------------- | | url | string | Requested URL | | init? | {method?: string, headers?: HeaderInit, body?: string} | The request information |

REST Client

Getting Started

Initialize the client:

import {createAdminRestApiClient} from '@shopify/admin-api-client';

const client = createAdminRestApiClient({
  storeDomain: 'your-shop-name.myshopify.com',
  apiVersion: '2023-04',
  accessToken: 'your-admin-api-access-token',
});

Query for a product:

const response = await client.get('products/1234567890');

if (response.ok) {
  const body = await response.json();
}

createAdminRestApiClient() parameters

| Property | Type | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | storeDomain | string | The myshopify.com domain | | apiVersion | string | The requested Admin API version | | accessToken | string | The Admin API access token | | userAgentPrefix? | string | Any prefix you wish to include in the User-Agent for requests made by the library. | | retries? | number | 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. | | customFetchApi? | (url: string, init?: {method?: string, headers?: HeaderInit, body?: string}) => Promise<Response> | A replacement fetch function that will be used in all client network requests. By default, the client uses window.fetch(). | | logger? | (logContent:UnsupportedApiVersionLog \|HTTPResponseLog\|HTTPRetryLog) => void | A logger function that accepts log content objects. This logger will be called in certain conditions with contextual information. | | scheme? | http | https | The HTTP scheme to use for requests | | defaultRetryTime? | number | How long to wait for a retry when missing the Retry-After header | | formatPaths? | boolean | Whether to format paths, e.g. products/123 => /products/123.json |

Client properties

| Property | Type | Description | | -------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------- | | get | (path: string, options?:GetRequestOptions) => Promise<Response> | Performs a GET request to the API. | | post | (path: string, options?:PostRequestOptions) => Promise<Response> | Performs a POST request to the API. | | put | (path: string, options?:PutRequestOptions) => Promise<Response> | Performs a PUT request to the API. | | delete | (path: string, options?:DeleteRequestOptions) => Promise<Response> | Performs a DELETE request to the API. |

GetRequestOptions properties

| Name | Type | Description | | ------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | apiVersion? | string | The Admin API version to use in the API request. | | headers? | {[key: string]: string} | Customized headers to be included in the API request. | | searchParams? | { [key: string]: string \| number[] } | Any extra query string arguments to include in the request. | | retries? | number | 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. | | data? | { [key: string]: any } \| string | Request body data. |

PostRequestOptions properties

Same options as for GET requests, but data isn't optional.

PutRequestOptions properties

Same options as for POST requests.

DeleteRequestOptions properties

Same options as for GET requests.

Usage examples

Query for a product

const response = await client.get('products/1234567890');

if (response.ok) {
  const body = await response.json();
}

Update a product

const response = await client.put('products/1234567890', {
  data: {
    product: {
      handle: 'my-new-handle',
    },
  },
});

if (response.ok) {
  const body = await response.json();
}

Dynamically set the Admin API version per data fetch

const response = await client.get('products/1234567890', {
  apiVersion: '2023-01',
});

if (response.ok) {
  const body = await response.json();
}

Add custom headers to API request

const response = await client.get('products/1234567890', {
  headers: {
    'X-My-Custom-Header': '1',
  },
});

if (response.ok) {
  const body = await response.json();
}

Dynamically set the number of retries per request

const response = await client.get('products/1234567890', {
  retries: 2,
});

if (response.ok) {
  const body = await response.json();
}