9951 explained code solutions for 126 technologies


php-guzzleHow to use GraphQL with PHP Guzzle?


GraphQL can be used with PHP Guzzle to make HTTP requests to a GraphQL endpoint.

Example code

$client = new \GuzzleHttp\Client();
$response = $client->post('http://example.com/graphql', [
    'json' => [
        'query' => '{ hello }'
    ]
]);

Output example

{
    "data": {
        "hello": "world"
    }
}

Code explanation

  • $client = new \GuzzleHttp\Client(); - creates a new Guzzle client
  • $response = $client->post('http://example.com/graphql', [ - makes a POST request to the GraphQL endpoint
  • 'json' => [ - sets the request body to JSON
  • 'query' => '{ hello }' - sets the GraphQL query

Helpful links

Edit this code on GitHub