Getting started with the Ajax API

The basics of Ajax API requests

The Ajax API provides a suite of lightweight REST API endpoints for every Shopify store. Requests to the Ajax API are unauthenticated, so they require no access tokens or API keys to use. All endpoints return JSON-formatted data.

For instance, to fetch the current contents of the cart, send a client-side request to the store’s /cart.js endpoint.

https://{shop_id}.myshopify.com/cart.js

The response is a JSON object containing information about the cart contents for the current browser session. You can then use JavaScript to update HTML elements on the page with that data.

Consult the Ajax API reference for the complete list of available resources, as well as examples of data you will receive in response.

Types of API calls available

The Ajax API accepts two types of HTTP requests:

  • GET requests to read cart and some product data
  • POST requests to update the cart for the current session

The Ajax API can’t be used to read any customer or order data, or update any store data. It can only read and write the state of the current browser session’s cart. If you need more extensive access, check the Admin API.

A simple example using jQuery

This simplified code snippet illustrates how you could update an HTML element with the current number of items in the cart. Note that you don’t have to use jQuery at all. Instead, you could use modern native web APIs such as fetch or your preferred browser HTTP client library.

var cartItemCounter = document.querySelector('span.cart-item-count');
jQuery.ajax('https://{shop}.myshopify.com/cart.js').done(function(data){
  var newCount = data.item_count;
  cartItemCounter.innerHTML = newCount;
})

Consult the Ajax API reference for more examples of the available types of requests and the responses they produce.

Using Shopify’s jQuery wrapper library

You can use Shopify's jQuery wrapper library to work with the Ajax API. This library allows you to access convenience functions in your scripts through a Shopify variable attached to the browser's window object. For example, Shopify.clear() will clear the contents of the shopping cart.

To enable the wrapper library in your online store, include these Liquid tags in your theme to render the required <script> elements:

{{ '//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js' | script_tag }}
{{ 'api.jquery.js' | shopify_asset_url | script_tag }}