简体   繁体   中英

PHP curl - preparing graphql query string with variables

I have this graphql request string:

$data_string = '{"query":"query {\n  search(input: {\n    projectId: \"'.$project_id.'\",\n    search: \"'
           .$expr.'\",\n    limit: '.$page_size.',\n    offset: '.$offset.'\n  }) {\n    total\n    result\n  }\n}"}';

And I'd like to to next thing:

$data_string = '{"query":"query {
  search(input: {
    projectId: \"'.$project_id.'\",
    search: \"'.$expr.'\",
    limit: '.$page_size.',
    offset: '.$offset.'
  }) {
    total
    result
  }
}"}';

But, for some reason, it doesn't work.

Here's how I make request:

        $ch = curl_init($search_api_url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-Type: application/json',
          'Content-Length: ' . strlen($data_string))
        );

        $result = curl_exec($ch);

PS I'm new in PHP

Thanks to https://stackoverflow.com/users/6124657/xadm

Here's probably the best way to make a GraphQL request without additional library and good readibility

My code looks now like this:

$data_string = json_encode([
            "query" => "query SEARCH(\$input: SearchInput!) {
                search(input: \$input) {
                    total
                    result
                  }
                }",
            "variables" => [
                "input" => [
                    "projectId" => $project_id,
                    "search" => $expr,
                    "limit" => $page_size,
                    "offset" => $offset
                ]
            ]
        ]);
        $ch = curl_init($search_api_url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
          'Content-Type: application/json',
          'Content-Length: ' . strlen($data_string))
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM