Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork279
Node Shopify connector sponsored by MONEI
License
MONEI/Shopify-api-node
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Shopify API bindings for Node.js.
$ npm install --save shopify-api-node
This module exports a constructor function which takes an options object.
Creates a newShopify instance.
options- Required - A plain JavaScript object that contains theconfiguration options.
shopName- Required - A string that specifies the shop name. The shop's"myshopify.com" domain is also accepted.apiKey- Required forprivate apps - Astring that specifies the API key of the app. This option must be used inconjunction with thepasswordoption and is mutually exclusive with theaccessTokenoption.password- Required forprivate apps - Astring that specifies the private app password. This option must be used inconjunction with theapiKeyoption and is mutually exclusive with theaccessTokenoption.accessToken- Required for public apps - A string representing the permanentOAuth 2.0 access token. This option is mutually exclusive with theapiKeyandpasswordoptions. If you are looking for a premade solution toobtain an access token, take a look at theshopify-token module.agent- Optional - An object that is passed as theagentoption togot.This allows to use a proxy server. SeeGot documentationfor more details.apiVersion- Optional - A string to specify theShopify APIversion to use for requests. Defaults to the oldest supportedstable version.autoLimit- Optional - This option allows you to regulate the request ratein order to avoid hitting therate limit. Requests arelimited using the token bucket algorithm. Accepted values are a boolean or aplain JavaScript object. When using an object, thecallsproperty and theintervalproperty specify the refill rate and thebucketSizeproperty thebucket size. For example{ calls: 2, interval: 1000, bucketSize: 35 }specifies a limit of 2 requests per second with a burst of 35 requests. Whenset totruerequests are limited as specified in the above example. Defaultstofalse. Mutually exclusive with themaxRetriesoption.hooks- Optional - A list ofgotrequest hooks toattach to all outgoing requests, likebeforeRetry,afterResponse, etc.Hooks should be provided in the same format that Got expects them and willreceive the same arguments Got passes unchanged.maxRetries- Optional - The number of times to attempt to make the requestto Shopify before giving up. Defaults to0, which means no automaticretries. If set to a value greater than0,shopify-api-nodewill make upto that many retries.shopify-api-nodewill respect theRetry-Afterheaderfor requests to the REST API, and the throttled cost data for requests to theGraphQL API, and retry the request after that time has elapsed. Mutuallyexclusive with theautoLimitoption.parseJson- Optional - The function used to parse JSON. The function ispassed a single argument. This option allows the use of a custom JSON parserthat might be needed to properly handle long integer IDs. Defaults toJSON.parse().presentmentPrices- Optional - Whether to include the header to pullpresentment prices for products. Defaults tofalse.stringifyJson- Optional - The function used to serialize to JSON. Thefunction is passed a single argument. This option allows the use of a customJSON serializer that might be needed to properly handle long integer IDs.Defaults toJSON.stringify().timeout- Optional - The number of milliseconds before the request timesout. If the request takes longer thantimeout, it will be aborted. Defaultsto60000, or 1 minute.
AShopify instance.
Throws anError exception if the required options are missing.
constShopify=require('shopify-api-node');constshopify=newShopify({shopName:'your-shop-name',apiKey:'your-api-key',password:'your-app-password'});
ThecallLimits property allows you to monitor the API call limit. The value isan object like this:
{remaining:30,current:10,max:40}
Values start atundefined and are updated every time a request is made. Afterevery update thecallLimits event is emitted with the updated limits asargument.
shopify.on('callLimits',(limits)=>console.log(limits));
When using the GraphQL API, a different property is used to track the API calllimit:callGraphqlLimits.
Keep in mind that theautoLimit option is ignored while using GraphQL API.
shopify.on('callGraphqlLimits',(limits)=>console.log(limits));
Every resource is accessed via yourshopify instance:
constshopify=newShopify({shopName:'your-shop-name',accessToken:'your-oauth-token'});// shopify.<resource_name>.<method_name>
Each method returns aPromise that resolves with the result:
shopify.order.list({limit:5}).then((orders)=>console.log(orders)).catch((err)=>console.error(err));
The Shopify API requires that you send a valid JSON string in the request bodyincluding the name of the resource. For example, the request body to create acountry should be:
{"country": {"code":"FR","tax":0.25 }}When usingshopify-api-node you don't have to specify the full object but onlythe nested one as the module automatically wraps the provided data. Using theabove example this translates to:
shopify.country.create({code:'FR',tax:0.25}).then((country)=>console.log(country)).catch((err)=>console.error(err));
Similarly, the Shopify API includes the resource name in the JSON string that isreturned in the response body:
{"country": {"id":1070231510,"name":"France","tax":0.2,"code":"FR","tax_name":"TVA","provinces": [] }}shopify-api-node automatically unwraps the parsed object and returns:
{id:1070231510,name:'France',tax:0.2,code:'FR',tax_name:'TVA',provinces:[]}
This behavior is valid for all resources.
Shopify allows for adding metafields to various resources. You can use theowner_resource andowner_id properties to work with metafields that belongto a particular resource as shown in the examples below.
Get metafields that belong to a product:
shopify.metafield.list({metafield:{owner_resource:'product',owner_id:632910392}}).then((metafields)=>console.log(metafields),(err)=>console.error(err));
Create a new metafield for a product:
shopify.metafield.create({key:'warehouse',value:25,type:'integer',namespace:'inventory',owner_resource:'product',owner_id:632910392}).then((metafield)=>console.log(metafield),(err)=>console.error(err));
Pagination in API version 2019-07 and above can bedone as shown in the following example:
(async()=>{letparams={limit:10};do{constproducts=awaitshopify.product.list(params);console.log(products);params=products.nextPageParameters;}while(params!==undefined);})().catch(console.error);
Each set of results may have thenextPageParameters andpreviousPageParameters properties. These properties specify respectively theparameters needed to fetch the next and previous page of results.
This feature is only available on version 2.24.0 and above.
shopify-api-node has two optional mechanisms for avoiding requests failingwith429 Rate Limit Exceeded errors from Shopify.
TheautoLimit option implements a client side leaky bucket algorithm fordelaying requests until Shopify is likely to accept them. WhenautoLimit ison, eachShopify instance will track how many requests have been made, anddelay sending subsequent requests if the rate limit has been exceeded.autoLimit is very efficient because it almost entirely avoids sending requestswhich will return 429 errors, but, it does not coordinate between multipleShopify instances or across multiple processes. If you're usingshopify-api-node in many different processes,autoLimit will not correctlyavoid 429 errors.
ThemaxRetries option implements a retry based strategy for getting requeststo Shopify, where when a 429 error occurs, the request is automatically retriedafter waiting. Shopify usually replies with aRetry-After header indicating tothe client when the rate limit is available, and soshopify-api-node will waitthat long before retrying. If you are usingshopify-api-node in many differentprocesses, they will all be competing to use the same rate limit shopifyenforces, so there is no guarantee that retrying after theRetry-After headerdelay will work. It is recommended to setmaxRetries to a high value like10if you are making many concurrent requests in many processes to ensure eachrequest is retried for long enough to succeed.
autoLimit andmaxRetries can't be used simultaneously. Both are off bydefault.
- accessScope
list()
- apiPermission
delete()
- applicationCharge
activate(id[, params])create(params)get(id[, params])list([params])
- applicationCredit
create(params)get(id[, params])list([params])
- article
authors()count(blogId[, params])create(blogId, params)delete(blogId, id)get(blogId, id[, params])list(blogId[, params])tags([blogId][, params])update(blogId, id, params)
- asset
create(themeId, params)delete(themeId, params)get(themeId, params)list(themeId[, params])update(themeId, params)
- balance
list()transactions([params])
- blog
count()create(params)delete(id)get(id[, params])list([params])update(id, params)
- cancellationRequest
accept(fulfillmentOrderId[, message])create(fulfillmentOrderId[, message])reject(fulfillmentOrderId[, message])
- carrierService
create(params)delete(id)get(id)list()update(id, params)
- checkout
complete(token)count([params])create(params)get(token)list([params])shippingRates(token)update(token, params)
- collect
count([params])create(params)delete(id)get(id[, params])list([params])
- collection
get(id[, params])products(id[, params])
- collectionListing
get(id)list([params])productIds(id[, params])
- comment
approve(id)count([params])create(params)get(id[, params])list([params])notSpam(id)remove(id)restore(id)spam(id)update(id, params)
- country
count()create(params)delete(id)get(id[, params])list([params])update(id, params)
- currency
list()
- customCollection
count([params])create(params)delete(id)get(id[, params])list([params])update(id, params)
- customer
accountActivationUrl(id)count([params])create(params)delete(id)get(id[, params])list([params])orders(id[, params])search(params)sendInvite(id[, params])update(id, params)
- customerAddress
create(customerId, params)default(customerId, id)delete(customerId, id)get(customerId, id)list(customerId[, params])set(customerId, params)update(customerId, id, params)
- customerSavedSearch
count([params])create(params)customers(id[, params])delete(id)get(id[, params])list([params])update(id, params)
- deprecatedApiCall
list()
- discountCode
create(priceRuleId, params)delete(priceRuleId, id)get(priceRuleId, id)list(priceRuleId)lookup(params)update(priceRuleId, id, params)
- discountCodeCreationJob
create(priceRuleId, params)discountCodes(priceRuleId, id)get(priceRuleId, id)
- dispute
get(id)list([params])
- disputeEvidence
get(disputeId)update(disputeId, params)
- disputeFileUpload
create(disputeId, params)delete(disputeId, id)
- draftOrder
complete(id[, params])count()create(params)delete(id)get(id[, params])list([params])sendInvoice(id[, params])update(id, params)
- event
count([params])get(id[, params])list([params])
- fulfillment
cancel(orderId, id)cancelV2(id)complete(orderId, id)count(orderId[, params)create(orderId, params)createV2(params)get(orderId, id[, params])list(orderId[, params])open(orderId, id)update(orderId, id, params)updateTracking(id, params)
- fulfillmentEvent
create(orderId, fulfillmentId, params)delete(orderId, fulfillmentId, id)get(orderId, fulfillmentId, id)list(orderId, fulfillmentId[, params])update(orderId, fulfillmentId, id, params)
- fulfillmentOrder
cancel(id)close(id[, message])fulfillments(id)get(id)hold(id, params)list([params])locationsForMove(id)move(id, locationId)releaseHold(id)reschedule(id, deadline)setFulfillmentOrdersDeadline(params)
- fulfillmentRequest
accept(fulfillmentOrderId[, message])create(fulfillmentOrderId, params)reject(fulfillmentOrderId[, message])
- fulfillmentService
create(params)delete(id)get(id)list([params])update(id, params)
- giftCard
count([params])create(params)disable(id)get(id)list([params])search(params)update(id, params)
- giftCardAdjustment
create(giftCardId, params)get(giftCardId, id)list(giftCardId)
- inventoryItem
get(id)list(params)update(id, params)
- inventoryLevel
adjust(params)connect(params)delete(params)list(params)set(params)
- location
countget(id)inventoryLevels(id[, params])list()
- marketingEvent
count()create(params)delete(id)get(id)list([params])update(id, params)engagements(id, params)
- metafield
count([params])create(params)delete(id)get(id[, params])list([params])update(id, params)
- order
cancel(id[, params])close(id)count([params])create(params)delete(id)fulfillmentOrders(id)get(id[, params])list([params])open(id)update(id, params)
- orderRisk
create(orderId, params)delete(orderId, id)get(orderId, id)list(orderId)update(orderId, id, params)
- page
count([params])create(params)delete(id)get(id[, params])list([params])update(id, params)
- payment
count(checkoutToken)create(checkoutToken, params)get(checkoutToken, id)list(checkoutToken)
- payout
get(id)list([params])
- policy
list([params])
- priceRule
create(params)delete(id)get(id)list([params])update(id, params)
- product
count([params])create(params)delete(id)get(id[, params])list([params])update(id, params)
- productImage
count(productId[, params])create(productId, params)delete(productId, id)get(productId, id[, params])list(productId[, params])update(productId, id, params)
- productListing
count()create(productId[, params])delete(productId)get(productId)list([params])productIds([params])
- productResourceFeedback
create(productId[, params])list(productId)
- productVariant
count(productId)create(productId, params)delete(productId, id)get(id[, params])list(productId[, params])update(id, params)
- province
count(countryId[, params])get(countryId, id[, params])list(countryId[, params])update(countryId, id, params)
- recurringApplicationCharge
activate(id, params)create(params)delete(id)get(id[, params])list([params])customize(id, params)
- redirect
count([params])create(params)delete(id)get(id[, params])list([params])update(id, params)
- refund
calculate(orderId, params)create(orderId, params)get(orderId, id[, params])list(orderId[, params])
- report
create(params)delete(id)get(id[, params])list([params])update(id, params)
- resourceFeedback
create(params)list()
- scriptTag
count([params])create(params)delete(id)get(id[, params])list([params])update(id, params)
- shippingZone
list([params])
- shop
get([params])
- smartCollection
count([params])create(params)delete(id)get(id[, params])list([params])order(id, params)products(id[, params])update(id, params)
- storefrontAccessToken
create(params)delete(id)list()
- tenderTransaction
list([params])
- theme
create(params)delete(id)get(id[, params])list([params])update(id, params)
- transaction
count(orderId)create(orderId, params)get(orderId, id[, params])list(orderId[, params])
- usageCharge
create(recurringApplicationChargeId, params)get(recurringApplicationChargeId, id[, params])list(recurringApplicationChargeId[, params])
- user
current()get(id)list()
- webhook
count([params])create(params)delete(id)get(id[, params])list([params])update(id, params)
whereparams is a plain JavaScript object. See theRest Admin APIreference for parameters details.
Theshopify instance also allows to use the GraphQL API through thegraphqlmethod, which returns a promise that resolves with the result data:
constshopify=newShopify({shopName:'your-shop-name',accessToken:'your-oauth-token'});constquery=`{ customers(first: 5) { edges { node { displayName totalSpent } } }}`;shopify.graphql(query).then((customers)=>console.log(customers)).catch((err)=>console.error(err));
shopify-api-node supports being passed hooks which are called bygot (theunderlying HTTP library) during the request lifecycle.
For example, we can log every error that is encountered when using themaxRetries option:
constshopify=newShopify({shopName:'your-shop-name',accessToken:'your-oauth-token',maxRetries:3,// Pass the `beforeRetry` hook down to Got.hooks:{beforeRetry:[(options,error,retryCount)=>console.error(error)]}});
For more information on the availablegot hooks, see thegot v11 hooks documentation.
(add yours!)
About
Node Shopify connector sponsored by MONEI
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.