I want to make a PHP POST request to “The Graph” API. I’ve been unable to find an example of this.
For instance, how would I convert the example query for Polymarket into a PHP POST request? https://thegraph.com/explorer/subgraph/tokenunion/polymarket-matic?selected=playground
{ globals(first: 5) { id numConditions numOpenConditions numClosedConditions } accounts(first: 5) { id creationTimestamp lastSeenTimestamp collateralVolume } }
So far I have
$sUrl="https://api.thegraph.com/subgraphs/name/tokenunion/polymarket-matic"; $query="query { globals(first: 5) { id numConditions numOpenConditions numClosedConditions } accounts(first: 5) { id creationTimestamp lastSeenTimestamp collateralVolume } }"; $aData=array('query' => $query); $options = array( 'https' => array( 'header' => "Content-type: application/x-www-form-urlencodedrn", 'method' => 'POST', 'content' => http_build_query($aData) ) ); $context = stream_context_create($options); $result = file_get_contents($sUrl, false, $context); var_dump($result);
And this just returns a GraphiQL example.
Answer
I’m not sure what I was doing wrong. Maybe a syntax issue? But I found another example and was able to modify it to work. So this works (returns a list of polymarket trades for a user, from 2020, with a limit of 1000):
$sUrl="https://api.thegraph.com/subgraphs/name/tokenunion/polymarket-matic"; $sStartdate='2020/01/01'; $sEnddate='2020/12/31'; $iStarttime=strtotime($sStartdate); $iEndtime=strtotime($sEnddate); $sUser="0xf449b747376a2036dd76ada1484e0a2389c8d43b"; $sGraph='{"query":"{transactions(where: {user:"'.$sUser.'" timestamp_gte: '.$iStarttime.' timestamp_lte: '.$iEndtime.'} orderBy: timestamp orderDirection: asc first:1000) {id, type, timestamp, market {id}, tradeAmount, feeAmount, outcomeIndex, outcomeTokensAmount}}"}'; $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, 1 ); curl_setopt($ch, CURLOPT_POSTFIELDS, $sGraph); curl_setopt($ch, CURLOPT_URL, $sUrl); $data = curl_exec($ch); curl_close($ch); $aData=json_decode($data); print_r ($aData);