Categories
Development

CURL request into Curl PHP code

Recently I needed to transform the CURL request into the PHP Curl code, binary data and compressed option having been involved. See the query itself:

curl 'https://terraswap-graph.terra.dev/graphql' 
-H 'Accept-Encoding: gzip, deflate, br' 
-H 'Content-Type: application/json' 
-H 'Accept: application/json' 
-H 'Connection: keep-alive' 
-H 'DNT: 1' 
-H 'Origin: https://terraswap-graph.terra.dev' 
--data-binary '{"query":"{\n  pairs {\n    pairAddress\n    latestLiquidityUST\n    token0 {\n      tokenAddress\n      symbol\n    }\n    token1 {\n      tokenAddress\n      symbol\n    }\n    commissionAPR\n    volume24h {\n      volumeUST\n    }\n  }\n}\n"}' 
--compressed

--binary-data has been implemented as data put in the POST fields, see the following:

curl_setopt($ch_upload, CURLOPT_POSTFIELDS, $post);

--compressed has been implemented as the following:
curl_setopt($ch_upload, CURLOPT_ENCODING , "");

See the whole code that works:

$url = "https://terraswap-graph.terra.dev/graphql";

// headers
$headers = ['Content-Type: application/json' 
 , 'Accept-Encoding: gzip, deflate, br' 
 , 'Accept: application/json' 
 , 'Connection: keep-alive' 
 , 'DNT: 1' 
 , 'Origin: https://terraswap-graph.terra.dev' ];

// POST payload
$post = '{"query":"{  pairs {    pairAddress    latestLiquidityUST    token0 {      tokenAddress      symbol    }    token1 {      tokenAddress      symbol    }    commissionAPR    volume24h {      volumeUST    }  }}"}'; 

$timeout = 30;
$ch_upload = curl_init(); 
curl_setopt($ch_upload, CURLOPT_URL, $url);
curl_setopt($ch_upload, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch_upload, CURLOPT_POST, true);
curl_setopt($ch_upload, CURLOPT_ENCODING , ""); // --compressed
curl_setopt($ch_upload, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch_upload, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_upload, CURLOPT_CONNECTTIMEOUT, $timeout);
$response  = curl_exec($ch_upload);
if (curl_errno($ch_upload)) {
    echo 'Curl Error: ' . curl_error($ch);
}
curl_close($ch_upload); 

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.

This site uses Akismet to reduce spam. Learn how your comment data is processed.