cpcdev
cpcdev

Reputation: 1222

How to Set GraphQL Variables in PHP

I'm using the FXHash API to access listings with this query:

query Listings($sort: ListingsSortInput) {
  listings(sort: $sort) {
    amount
    createdAt
    price
    issuer {
      name
    }
    objkt {
      name
    }
  }
}
$options = '{
  "sort": {
    "createdAt": "DESC"
  }
}';

I'd like to use the query above in PHP with the sort by createdAt options. How can I fit this query into my cURL with the sort options? I don't understand how to add the $options variable into the query. Thanks for the help!

$url = 'https://api.fxhash.xyz/graphql';    

$curl = curl_init();
$queryData = array();
$data = array();

$queryData = '{
  listings {
    amount
    createdat
    price
    issuer {
        name
    }
    objkt {
      name
    }
  }
}';

$data["query"] = $queryData;

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
  'Content-Type: application/json'
));

Upvotes: 1

Views: 272

Answers (1)

ThisaruG
ThisaruG

Reputation: 3412

You must add the POST request variables as a JSON map.

Try something like this:

$queryData = 'query Listings($sort: ListingsSortInput) {
  listings(sort: $sort) {
    amount
    createdAt
    price
    issuer {
      name
    }
    objkt {
      name
    }
  }
}';
$options = '{
  "sort": {
    "createdAt": "DESC"
  }
}';
$data["query"] = $queryData;
$data["variables"] = $options;

Upvotes: 2

Related Questions