【问题标题】:Graphql API Call /w Query using PHPGraphql API Call /w 使用 PHP 查询
【发布时间】:2022-01-22 15:53:50
【问题描述】:

努力弄清楚如何使用 PHP 进行 graphql api 调用。我正在尝试使用 tezos 域 API 将 .tez 域转换为地址。我的查询在他们的“操场”中运行良好,只是无法将其翻译成 php。

尝试 1:

$apiUrl = 'https://api.tezos.domains/graphql';
$query = '{
           domains(where: { name: { in: "' . $wallet . '" } }) {
            items {
              address
            }
          }
        }';
$data = @file_get_contents($apiUrl, false, stream_context_create([
 'http' => [
  'method' => 'POST',
  'content' => json_encode(['query' => $query]),
 ]
]));
$results = json_decode($data, true);
echo $results;
$wallet = $results['data'];

尝试 2:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.tezos.domains/graphql" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"query":"{domains(where: {name: { in:"elli0t.tez"}}) {items {address}}}"}'); 
curl_setopt($ch, CURLOPT_HTTPHEADER, 
    array(
        'Accept-Encoding: gzip, deflate, br',
        'Content-Type: application/json', 
        'Accept: application/json',
        'Connection: keep-alive',
        'DNT: 1',
        'Origin: https://api.tezos.domains' )
    ); 

$result = curl_exec($ch);
print_r($result);

$info = curl_getinfo($ch);

print_r($info);

尝试 2 至少给我返回了一些东西。它说我错过了一个查询。有什么想法吗?

这是从 api 的 Playground 生成的 curl 命令,似乎可以正常工作。我只是无法将其转换为 PHP:

curl 'https://api.tezos.domains/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: https://api.tezos.domains' --data-binary '{"query":"{\n   domains(where: { name: { in: \"elli0t.tez\" } }) {\n    items {\n      address\n    }\n  }\n}"}' --compressed

【问题讨论】:

    标签: php api curl graphql


    【解决方案1】:

    从 GraphQL Docs 我发现了这个:带参数的基本查询:

        {
      human(id: "1000") {
        name
        height
      }
    }
    

    而您的域查询如下所示:

    {
           domains(where: { name: { in: "' . $wallet . '" } }) {
            items {
              address
            }
          }
        }
    

    令我印象深刻的是语法错误,因为您在 GraphQL 文档中的任何地方都找不到类似以下结构的示例:

    {
        domains(where: { ... })
    }
    

    我不知道 GraphQL,但我会在参数内的冒号上指出它。我唯一能找到允许这样做的地方是使用变量来创建突变:

       mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!)
    {
      createReview(episode: $ep, review: $review) {
        stars
        commentary
      }
    }
    

    所以我猜测域查询中断可能会发生什么,或者您将查询链接在一起。

    希望对你有所帮助。

    【讨论】:

    • 嗯,好的,谢谢您的回复。我在api的“playground”中使用graphql explorer来生成查询字符串,它返回正确的响应,所以我认为我的查询是正确的。它还生成它在操场上使用的 curl 命令,我已将其添加到我的原始帖子中。我看到我添加了一些缺失的标头(我也在原始帖子中更新了我的代码),但现在我没有得到任何回应。
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 2018-04-22
    • 2021-08-27
    • 1970-01-01
    相关资源
    最近更新 更多