Back to all functions

Shopify: Search Product

Search for a product from a Shopify store. Takes no API key, since it's searching public entries. Gets the first closest match.

Created By
Luuk de Block
Community
download-icon
INPUT VARIABLES
{
shopDomain
}
The Shopify store domain (e.g., `your-development-store.myshopify.com`).
{
productTitle
}
Product Title to search for
{
}
{
}
{
}
{
}
share-icon
OUTPUT VARIABLES
{
productPrice
}
{
productUrl
}
{
productTitle
}
{
productImageUrl
}
{
Productresponse
}
{
}
paths-icon
PATHS
{
success
}
{
error
}
{
}
{
}
{
}
{
}

Function Walkthrough

Function Code Snippet

 
export default async function main(args) {
    const logs = [];

    // Extract input variables from args

    const { shopDomain, productTitle } = args.inputVars;
    const query = productTitle;

    logs.push(`Extracted inputs - query: ${query}, shopDomain: ${shopDomain}`);

    // Validate that the required input variables are provided
    if (!shopDomain || !query) {
        logs.push("Error: Missing required input variables: shopDomain or query");
        return {
            next: { path: 'error' },
            trace: [{ type: "debug", payload: { message: logs.join(", ") } }]
        };
    }

    // Define the endpoint URL

    const encodedQuery = encodeURIComponent(query);
    const url = `https://${shopDomain}/search/suggest.json?q=${encodedQuery}&resources[type]=product`;
    logs.push(`URL: ${url}`);

    // Configure the fetch request
    const config = {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        },
    };

    try {
        // Make the API call
        logs.push(`Making API call to URL: ${url}`);
        const response = await fetch(url, config);

        // Check if the response status is OK
        if (!response.ok) {
            const errorMsg = await response.text();
            logs.push(`HTTP error! status: ${response.status}, message: ${errorMsg}`);
            throw new Error(`HTTP error! status: ${response.status}, message: ${errorMsg}`);
        }

        // Extract the JSON body from the response
        logs.push("Extracting JSON from the response");
        const responseBody = await response.json;

        // Validate the responseBody structure as expected
        if (!responseBody || !responseBody.resources || !responseBody.resources.results || !Array.isArray(responseBody.resources.results.products)) {
            throw new Error("Invalid or missing response body from the API");
        }

        // Fetch the first product from the search results
        const products = responseBody.resources.results.products;
        if (products.length === 0) {
            throw new Error("No products found for the given query");
        }

        const firstProduct = products[0];

        // Extract required product details
        const productTitle = firstProduct.title;
        const productImageUrl = firstProduct.image;
        const productPrice = firstProduct.price; // Assuming 'price' is the correct field for product price
        const productUrl = firstProduct.url;

        logs.push(`Product found: Title - ${productTitle}, Image URL - ${productImageUrl}, Price - ${productPrice}, URL - ${productUrl}`);

        // Create the success return object with extracted data
        return {
            outputVars: {
                Productresponse: JSON.stringify(responseBody),
                productTitle,
                productImageUrl,
                productPrice,
                productUrl
            },
            next: { path: 'success' },
        };

    } catch (error) {
        logs.push(`Error: ${error.message}`);
        return {
            next: { path: 'error' },
        };
    }
}
copy-icon

Have something to share?

Share your creation with over 250,000 other global Voiceflow users.

ghraphic
No items found.