Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use Guzzle for GraphQL API consumption?

There isn't a lot of information in the google-verse about consuming GraphQL API's in PHP. There are several packages that from my perspective, are mostly about creating your own GraphQL API, but nothing specific to consuming. It's possible that I'm over complicating things or that the solution to my question is obvious. I've solved my problem and will post the answer.

like image 363
Vim Diesel Avatar asked Jun 07 '19 12:06

Vim Diesel


Video Answer


1 Answers

I didn't want to pull these packages in when I barely understood what they provided and I just wanted to use the same tools I was used to in the REST world for a lightweight transition. The answer is Yes, you can use Guzzle for consuming a GraphQL API.

There are probably ways to make this prettier, but for now, this is what's working. You pass authorization through the Authorization header and Content-Type must be set to application/json.

When constructing your query be wary of quotes, spacing, and line breaks. I haven't yet figured out a way to make the code prettier and still maintain a valid query. The first portion {"query": "query { is a requirement for every query. The object name must be wrapped in double quotes and the query body "query { }" must be wrapped in double quotes as well.

$graphQLquery = '{"query": "query { viewer { repositories(last: 100) { nodes { name id isPrivate nameWithOwner } } } } "}';

use GuzzleHttp\Client;

$response = (new Client)->request('post', '{graphql-endpoint}', [
    'headers' => [
        'Authorization' => 'bearer ' . $token,
        'Content-Type' => 'application/json'
    ],
    'body' => $graphQLquery
]);
like image 65
Vim Diesel Avatar answered Sep 30 '22 04:09

Vim Diesel