我可以使用 Guzzle 来使用 GraphQL API 吗?

Can I use Guzzle for GraphQL API consumption?

google-verse 中没有很多关于在 PHP 中使用 GraphQL API 的信息。从我的角度来看,有几个包主要是关于创建您自己的 GraphQL API,但没有特定于消费的内容。有可能我把事情复杂化了,或者我的问题的解决方案很明显。我已经解决了我的问题并将 post 给出答案。

当我几乎不了解它们提供的内容时,我不想引入这些包,我只是想使用我在 REST 世界中习惯使用的相同工具来进行轻量级转换。答案是肯定的,您可以使用 Guzzle 来使用 GraphQL API.

可能有一些方法可以让它更漂亮,但就目前而言,这是行之有效的方法。您通过Authorization header 进行授权,并且Content-Type 必须设置为application/json。

构建查询时请注意引号、空格和换行符。我还没有想出一种方法来使代码更漂亮并仍然保持有效的查询。第一部分 {"query": "query { 是每个查询的要求。 object 名称必须用双引号括起来,查询 body "query { }" 也必须用双引号括起来。

$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
]);

只需从 guzzle 发出正常的 post 请求即可。添加表单参数作为查询和变量。将您的查询放在查询表单参数和变量中作为键值数组。

  $response = $this->client->post('https://grapqlEndPoint', [
        'form_params' => [
            'query' => '
                query($username: String!) {
                    users(username: $username) {
                        username               
                    }
                }',
            'variables' => [
                'username' => $username
            ]
        ]
    ]);

    echo $response->getBody()->getContents();

我想在 Vim Diesel 提到的作为对他的 post 的回答的基础上添加一些内容。

截至 2021 年,当我按照代码的格式设置时,我最终得到了格式错误的有效负载作为错误消息。为了纠正这个问题,我删除了查询正文 query { } 并使用了 '"query": "query queryName{ }"'

如果您确实需要为 GraphQL 查询包含变量,您可以按照以下操作(来自 GraphQL documentation):

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

您可以在 PHP 中使用单引号 ' 和句点 . 分隔查询,以避免硬编码变量和格式化。

下面是对我有用的完整示例代码。

use GuzzleHttp\Client;

$name = 'JohnDoe';
$graphQLquery = '{'.
    '"query": "query viewer {'.
                  'repositories(last: 100) {'.
                      'nodes {'.
                         'name'. 
                         'id'. 
                         'isPrivate'. 
                         'nameWithOwner'. 
                      '}'.
                  '}'. 
             '}",'.
    '"variables": { "name": "'.$name.'", "id": "1", "isPrivate ": "True", "nameWithOwner": "VimDiesel"}'.
 '}';'



$response = (new Client)->request('post', '{graphql-endpoint}', [
    'headers' => [
        'Authorization' => $token,
        'Content-Type' => 'application/json'
    ],
    'body' => $graphQLquery
]);

我能够使用以下代码发送带有 GuzzleHttp\Client 的突变:

$graphQLBody = [
    'query' => 'mutation ($name: String!) {
        create(
            input:{
                name: $name,
            }
        ) {
            user {
                id,
                name,
            }
            errors {
                messages
            }
        }
    }',
    'variables' => [
        'name' => $name,
    ]
];

$response = $this->client->request('post', $this->apiEndpoint, [
    'headers' => [
        'Authorization' => 'bearer ' . $token,
        'Content-Type' => 'application/json'
    ],
    'body' => json_encode($graphQLBody)
]);