我可以使用Guzzle来使用GraphQL API吗? [英] Can I use Guzzle for GraphQL API consumption?

查看:83
本文介绍了我可以使用Guzzle来使用GraphQL API吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在google-verse中,关于在PHP中使用GraphQL API的信息并不多.从我的角度来看,有几个软件包主要与创建自己的GraphQL API有关,而与使用无关.我可能使事情复杂化了,或者问题的解决方案很明显.我已经解决了我的问题,并将发布答案.

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.

推荐答案

当我几乎不了解它们提供的内容并且只想使用与REST相同的工具时,我不想将它们打包轻量级过渡的世界.答案是肯定的,您可以使用Guzzle来使用GraphQL API.

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.

可能有一些方法可以使这种外观更漂亮,但是目前,这是有效的.您通过Authorization标头传递授权,并且Content-Type必须设置为application/json.

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.

构造查询时,请小心引号,空格和换行符.我还没有找到使代码更漂亮并仍然保持有效查询的方法.第一部分 {"query":查询{是每个查询的要求.对象名称必须用双引号引起来,并且查询主体" query {}"也必须用双引号引起来.

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

这篇关于我可以使用Guzzle来使用GraphQL API吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆