Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@shopify/admin-api-client

Package Overview
Dependencies
Maintainers
24
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@shopify/admin-api-client

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

  • 1.0.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
74K
increased by0.8%
Maintainers
24
Weekly downloads
 
Created
Source

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
  • REST Client

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
PropertyTypeDescription
storeDomainstringThe myshopify.com domain
apiVersionstringThe requested Admin API version
accessTokenstringThe Admin API access token
userAgentPrefix?stringAny prefix you wish to include in the User-Agent for requests made by the library.
retries?numberThe 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) => voidA logger function that accepts log content objects. This logger will be called in certain conditions with contextual information.

Client properties

PropertyTypeDescription
configAdminApiClientConfigConfiguration 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) => stringReturns 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

NameTypeDescription
storeDomainstringThe myshopify.com domain
apiVersionstringThe Admin API version to use in the API request
accessTokenstringThe provided public access token. If privateAccessToken was provided, publicAccessToken will not be available.
headersRecord<string, string | string[]>The headers generated by the client during initialization
apiUrlstringThe API URL generated from the provided store domain and api version
retries?numberThe number of retries the client will attempt when the API responds with a Too Many Requests (429) or Service Unavailable (503) response

ApiClientRequestOptions properties

NameTypeDescription
variables?Record<string, any>Variable values needed in the graphQL operation
apiVersion?stringThe Admin API version to use in the API request
headers?Record<string, string | string[]>Customized headers to be included in the API request
retries?numberAlternative 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>

NameTypeDescription
data?TData | anyData returned from the Admin API. If TData was provided to the function, the return type is TData, else it returns type any.
errors?ResponseErrorsError 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

NameTypeDescription
networkStatusCode?numberHTTP response status code
message?stringThe provided error message
graphQLErrors?any[]The GraphQL API errors returned by the server
response?ResponseThe raw response object from the network fetch call
Client request() response examples
Successful response
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
      }
    }
  }
}
Error responses
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.

PropertyTypeDescription
typeLogType['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.

PropertyTypeDescription
typeLogType['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.

PropertyTypeDescription
typeLogType['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 request
lastResponse: previous response
retryAttempt: the current retry attempt count
maxRetries: the maximum number of retries
RequestParams
PropertyTypeDescription
urlstringRequested 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
PropertyTypeDescription
storeDomainstringThe myshopify.com domain
apiVersionstringThe requested Admin API version
accessTokenstringThe Admin API access token
userAgentPrefix?stringAny prefix you wish to include in the User-Agent for requests made by the library.
retries?numberThe 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) => voidA logger function that accepts log content objects. This logger will be called in certain conditions with contextual information.
scheme?http | httpsThe HTTP scheme to use for requests
defaultRetryTime?numberHow long to wait for a retry when missing the Retry-After header
formatPaths?booleanWhether to format paths, e.g. products/123 => /products/123.json

Client properties

PropertyTypeDescription
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

NameTypeDescription
apiVersion?stringThe 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?numberAlternative 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 } | stringRequest 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();
}

Keywords

FAQs

Package last updated on 29 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc