[variables] => expected String to be a Hash

Solved
Highlighted
Tourist
5 2 1

Can someone please explain this to me.

 

Using PHP and GraphQL, My Query works fine.
But when i pass the Variables accross i keep getting an error expected String to be a Hash??

Why expecting a Hash? And how do i pass this accross as a Hash?

Postman does not appeat to pass this over as a Hash?

Query Runs fine, i cannot relate this to a PHP issue.

Snippet of code:

$variables = <<<'JSON'
{
"sku": "100560"
}
JSON;

$json = json_encode(['query' => $query, 'variables' => $variables]);

 

0 Likes
Highlighted
Tourist
5 2 1

This is an accepted solution.

Not sure why its returning String to be a Hash?

 

Either way the variables need creating in an array.

example of a the full code:

       $oxSKU = ""; // Fetched form another source, just here for example

        $query = <<<'JSON'
query ($first: Int, $sku: String)
{ productVariants(first: $first, query: $sku) {
    edges {
      node {
        title
        id
        sku
        price
        product {
          title
        }
        inventoryItem {
          id
          inventoryLevels(first: 3) {
            edges {
              node {
                id
                available
                location {
                  id
                  name
                  address {
                    city
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
JSON;

        $variables = array(
            "first" => 4,
            "sku" => "'$oxSKU'"
        );

        $json = json_encode(['query' => $query, 'variables' => $variables]);

// Then do your CURL Call 

 $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => "XXXXXXXXXXXXXXX.myshopify.com/admin/api/2020-04/graphql.json",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $json,
            CURLOPT_HTTPHEADER => array(
                "content-type: application/json"
            ),
        ));

        $response = curl_exec($curl);
        $responseDecode = json_decode($response, true);
        $err = curl_error($curl);
        curl_close($curl);

        if ($err) {
            echo "cURL Error #:" . $err;
        } else {
            echo "Call Successful <br>";
        }

This should be enought to get you started using PHP and Variables for GraphQL
Dont hesitate to get in touch if you need assitance

0 Likes