Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// This is a simple example how you can get data from the GraphQL endpoint of
// your Shopify store.
// For the explanatory article please visit:
package main
import (
"bytes"
"io/ioutil"
"fmt"
"log"
"net/http"
"strconv"
"time"
"os"
"github.com/valyala/fastjson"
)
// Please make sure that the following environment variables
// SHOPIFY_TOKEN & SHOPIFY_GRAPHQL_ENDPOINT are set
//
// to do this in bash:
// export SHOPIFY_TOKEN=YourSuperSecretToken
// export SHOPIFY_GRAPHQL_ENDPOINT=https://YOUR-STOTE.myshopify.com/admin/api/graphql.json
//
// to do this in fish:
// set -x SHOPIFY_TOKEN YourSuperSecretToken
// set -x SHOPIFY_GRAPHQL_ENDPOINT https://YOUR-STOTE.myshopify.com/admin/api/graphql.json
var token = os.Getenv("SHOPIFY_TOKEN")
var endpoint = os.Getenv("SHOPIFY_GRAPHQL_ENDPOINT")
func startRequest(body []byte) (*http.Response, error) {
client := http.Client{
Timeout: time.Second * 120,
}
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(body))
if err != nil {
return nil, fmt.Errorf( "error building request: %s", err)
}
req.Header.Add("X-Shopify-Access-Token",token)
req.Header.Add("Content-Type", "application/graphql")
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf( "error executing request: %s", err)
}
return resp, nil
}
func getItemPrice(sku string) (float32, error) {
query := `{
inventoryItems(first:1, query:"sku:` + sku + `") {
edges{
node{
sku
variant {
price
}
}
}
}
}`
resp, err := startRequest([]byte(query))
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, fmt.Errorf( "error reading response body: %s", err)
}
p := fastjson.GetString(body, "data", "inventoryItems", "edges", "0", "node", "variant", "price")
if fastjson.Exists(body, "error") {
return 0, fmt.Errorf("shopify responded with an error: %s", fastjson.GetString(body, "error"))
}
if fastjson.Exists(body, "data", "inventoryItems", "edges", "0", "node", "variant", "price") == false {
return 0, fmt.Errorf("item could not be found in shopify: %s", sku)
}
price, err:= strconv.ParseFloat(p, 32)
if err != nil {
return 0, fmt.Errorf( "error reading response body: %s", err)
}
return float32(price), nil
}
func main() {
price, err := getItemPrice("your_SKU") // The SKU you are looking for
if err != nil {
log.Fatalf("could not get price from shopify: %s", err)
}
fmt.Println("Price:", price)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.