Search code examples
phpgraphqlphp-curlgraphiqlgraphql-php

Getting started in Webonyx/Graphql-php: How get the response of the API in cURL without echoes from the API implementation?


I'm new to GraphQL and wanted to build a simple API to get started. After reading the docs and trying out the examples, finally the API can working fine... but !!!

The php implementation of the API ends with an "echo" (and this working fine for Graphiql client!), but when i try to get the response in cURL, this echo appear in my page source...

Please guys, how to avoid this echo and get the result in cURL? I turn to the immense collective wisdom to get some help in this.

Here are the resources i use:

This is the implementation webonyx/graphql-php:

use GraphQL\GraphQL;
use GraphQL\Type\Schema;

require('types.php');
require('querys.php');
require('mutations.php');

$schema = new Schema([
    'description' => 'Available querys and mutations',
    'query' => $rootQuery,
    'mutation' => $rootMutation
]);

try
{
    $rawInput = file_get_contents('php://input');
    $input = json_decode($rawInput, true);
    $query = $input['query'];
    $result = GraphQL::executeQuery($schema, $query);

    $output = $result->toArray();
}
catch (\Exception $e){
    $output = [
      'error' => [
          'message' => $e->getMessage()
      ]
    ];
}

header('Content-Type: application/json');

echo json_encode($output); //<-- This echo appear when i try to get the response in cURL

Here the query in GraphiQL:

mutation{
  addUser(name:"user name",email:"user email",password:"some pass"){
    id
  }
}

Here the result in GraphQL (all is working fine!):

{
  "data": {
    "addUser": {
      "id": 97
    }
  }
}

Here the function in cURL to get the response:

    function addUser($name,$email,$password){
        $query = <<<'JSON'
                mutation{
                    addUser(name:"*name", email:"*email", password:"*password"){
                    id
                    name
                }}
        JSON;

        $trans = array(
            "*name" => $name,
            "*email" => $email,
            "*password" => $password
        );

        $query = strtr($query, $trans);

        $variables = "";

        $json = json_encode(['query' => $query, 'variables' => $variables]);

        $chObj = curl_init();

        curl_setopt($chObj, CURLOPT_URL, $this->endpoint);
        curl_setopt($chObj, CURLOPT_RETURNTRANSFER, false);
        curl_setopt($chObj, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($chObj, CURLOPT_VERBOSE, true);
        curl_setopt($chObj, CURLOPT_POSTFIELDS, $json);

        $result = curl_exec($chObj);

        return $result;
    }

And this is the source code in my pages when using the function:

{"data":{"addUser":{"id":98,"name":"user name"}}}[1]
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.87.0">
    <title>Dashboard Template · Bootstrap v5.1</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/dashboard/">

The string: {"data":{"addUser":{"id":98,"name":"user name"}}} come from the API implementation echo json_encode($output);

I try to use get_file_content instead of cURL but cant achieve good results, please any help will be appreciated!


Solution

  • Set CURLOPT_RETURNTRANSFER to true to return the transfer as a string of the return value of curl_exec() instead of outputting it directly.

    curl_setopt($chObj, CURLOPT_RETURNTRANSFER, true);