Get All Products with Shopify API

 
import uvicorn
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import requests
import os

app = FastAPI()

# CORS configuration
origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class Data(BaseModel):
    store_url: str

# Endpoint to get all products in JSON format.

About this template

The Shopify Get All Products Downloader is a FastAPI application that connects to a Shopify store using the provided store URL and Shopify API credentials. It retrieves all products from the Shopify store and returns them in JSON format. The app also includes frontend JavaScript code that calls the backend API and downloads the products (all or from a specific collection) which can be used for your storefront. You need to provide SHOPIFY_API_KEY and SHOPIFY_ADMIN_API_TOKEN.

Introduction to the Shopify API Get All Products Template

Welcome to the Shopify API Get All Products template! This template is designed to help you connect to a Shopify store, retrieve all products, and return them in JSON format. It's a FastAPI application that simplifies the process of interacting with the Shopify API. Additionally, it includes frontend JavaScript code to call the backend API and download the products. This guide will walk you through the steps to set up and use this template on the Lazy platform.

Getting Started

To begin using this template, click on "Start with this Template" on the Lazy platform. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy, paste, or delete any code manually.

Initial Setup: Adding Environment Secrets

Before you can use the template, you'll need to set up some environment secrets. These are necessary for the app to authenticate with the Shopify API. Here's how to set them up:

  • Log in to your Shopify admin dashboard.
  • Go to the "Apps" section and create a new private app to obtain the API key and password.
  • Once you have your Shopify API key and password, go to the Environment Secrets tab within the Lazy Builder.
  • Add two new secrets: SHOPIFY_API_KEY and SHOPIFY_ADMIN_API_TOKEN.
  • Enter the values you obtained from your Shopify admin dashboard for these secrets.

Test: Pressing the Test Button

With the environment secrets set up, you're ready to test the app. Press the "Test" button on the Lazy platform. This will deploy the app and launch the Lazy CLI. If the app requires any user input, you will be prompted to provide it through the Lazy CLI.

Using the App

Once the app is deployed, Lazy will provide you with a dedicated server link to use the API. You can interact with the app using this link. Additionally, if you're using FastAPI, Lazy will also provide a docs link where you can see the available endpoints and their specifications.

To use the backend API, you'll need to make a POST request to the /products endpoint with the store URL in the request body. Here's a sample request:


POST /products HTTP/1.1
Host: [BACKEND_URL_GENERATED_BY_LAZY]
Content-Type: application/json

{
  "store_url": "YOUR_STORE_URL"
}

And here's what a sample response might look like:


[
  {
    "id": 123456789,
    "title": "Example Product",
    "body_html": "<strong>Great product!</strong>",
    "vendor": "Example Vendor",
    "product_type": "Widgets",
    "created_at": "2023-01-01T12:00:00-05:00",
    // More product fields...
  }
  // More products...
]

Integrating the App

If you want to integrate the backend API with your frontend application, you can use the provided JavaScript code. Replace YOUR_STORE_URL with the actual URL of your store and BACKEND_URL_GENERATED_BY_LAZY with the backend URL provided by Lazy after deploying the app. This script will call the backend API and download the products as a JSON file when executed in your frontend application.

Here's the JavaScript code you can use in your frontend:


async function downloadProducts() {
  // Define the store URL.
  const storeUrl = 'YOUR_STORE_URL';
  // Define the API endpoint.
  const apiEndpoint = 'BACKEND_URL_GENERATED_BY_LAZY/products';
  // Define the request body.
  const requestBody = {
      store_url: storeUrl
  };

  try {
      // Make the API call.
      const response = await fetch(apiEndpoint, {
          method: 'POST',
          body: JSON.stringify(requestBody),
          headers: {
              'Content-Type': 'application/json'
          }
      });

      // Get the products from the response.
      const products = await response.json();
      // Convert the products to a JSON string.
      const productsJson = JSON.stringify(products, null, 2);
      // Download the products as a JSON file.
      const blob = new Blob([productsJson], {type: 'application/json'});
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'products.json';
      link.click();

  } catch (error) {
      console.error('Error:', error);
  }
}

Follow these steps, and you'll be able to retrieve and download all products from your Shopify store using the Lazy platform. Happy building!

Category
Last published
June 15, 2024

More templates like this

PDF Data Extraction and Excel Transfer

An app for extracting name, phone number, and email data from PDF files and transferring it to Excel.

PDF
Python

GPT-4 Exam Generator

This app uses GPT-4 to generate a PDF of a new exam based on an uploaded PDF of a past exam.

PDF
OpenAI
Python

Job Search Website

A customisable one-page job search website with a search bar and a search button that displays UI cards of matching jobs. You need to have a (free) account on https://rapidapi.com/ to get the API key required for this to work.

React JS
Python
Flask
HTML
CSS
Home
/
Get All Products with Shopify API