Integrating External APIs in the Subscription Manager
This guide provides an approach for extending the functionality of the Subscription Manager by integrating external APIs. By following the steps outlined, you can dynamically pull in additional data and render it within your application.
Note
The example code is abbreviated for ease of reading; please add appropriate error handling.
Basic Usage
Step One — Add Function to script.js for API Request
First, add an asynchronous function to script.js that uses the Fetch API to request data from an external API. In this example, we’ll use a URL of a cat image.
Step Two — Add Function to script.js to Render Dynamic Content
Next, add a function that returns a template literal with a value from the API response. Utilize the html function from lit-html to interpret and render the template literal efficiently.
Step Three — Call the Render Function from a Liquid Partial
Finally, call the function from the desired location in the liquid template. Chain a call to until to ensure placeholder content is rendered until the asynchronous function resolves.
Additional Usage
Pass Arguments to Functions
Static Argument
Dynamic Argument from Partial Scope
In the example below, we assume order is in scope.
Set API Response as Variable in a Liquid Partial
Call API on Button Click
Update Application State on API Response
To gracefully update the application state upon receiving an API response, call one of the og.smi API methods to refresh the page state. The example below dispatches an action to request all processing and upcoming orders and updates the application state accordingly.
Call an API Outside the Context of Partials
To make an API call independent of partials — such as a single call during application initialization — invoke the API request function directly from script.js. If the function relies on the presence of the SMI element, call the function from the bootstrap function. The example below fetches a cat URL and appends an image to the SMI element.