How to Set GraphQL Variables in PHP

How to Set GraphQL Variables in PHP


1

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

Share
Improve this question

1 Answer
1

Reset to default


2

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;

Share
Improve this answer

2

  • thanks! what would the whole $queryData string look like?

    – devManMan

    Jan 11 at 6:35

  • You can use the schema you've provided in the question. Updated the answer

    – ThisaruG

    Jan 11 at 7:02




Not the answer you're looking for? Browse other questions tagged

or ask your own question.

Leave a Reply

Your email address will not be published. Required fields are marked *