Home > Software engineering >  using variables GraphQL PHP
using variables GraphQL PHP

Time:01-12

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 in to 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'
));

CodePudding user response:

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;
  • Related