Search code examples
phpgraphqlapolloapollo-server

How to construct a graphql mutation query request in php


I am having the hardest time figuring out how to properly format a graphql api mutation POST request in php.

If I hard code the string and use it as the data in my POST request it works like this: '{"query":"mutation{addPlay(input: {title: \"two\"}){ properties { title } } }"}'

But if I have a php array of the input values:

$test_data = array(
  'title' => 'two'
);

I can't seem to format it correctly. json_encode also puts double quotes around the keys which graphql is rejecting with the error Syntax Error GraphQL request (1:26) Expected Name, found String.

I ultimately need a solution that will convert a larger more complex array to something usable.


Solution

  • Reformatting the query allowed me to use JSON directly.

    So my new query looks like this:

    $test_data = array(
      'title' => 'two'
    );
    
    $request_data = array(
      'query' => 'mutation ($input: PlayInput) { addPlay(input: $input) { properties { title } }}',
      'variables' => array(
        'input' => $test_data,
      ),
    );
    
    $request_data_json = json_encode($request_data);
    

    Then the $request_data_json is used in a POST http request.