繁体   English   中英

如何使用 curl post 请求在 php 中运行 graphql api

[英]How to run graphql api in php using curl post request

这是一个可以发送或检索数据的 cURL 函数。 它应该适用于任何支持 OAuth 的 PHP 应用程序:

function jwt_request($url,$token, $post) {
    header('Content-Type: application/json'); // Specify the type of data
    $ch = curl_init($url); // Initialise cURL
    $post = json_encode($post);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1); // Specify the request method as POS
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post); // Set the posted fields
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
    $result = curl_exec($ch); // Execute the cURL statement
    curl_close($ch); // Close the cURL connection
    return ($result); // Return the received data
}
// I am running in localhost
$url = "http://localhost:3000/graphql";
// This is what query i am running
$post = '{"query": "query { login(username:"abbas@gmail.com",password: "abbas") { userID token } }" }';
// This is the function i am using in above
$json = jwt_request($url,$token, $post);
echo "<pre>"; 
print_r($json); // here printing

在花了这么多时间和方式之后,我遇到了这个问题的最佳解决方案是在 composer 的帮助下使用这个 git 存储库,它工作得很棒,但是你必须对 composer 以及如何安装和使用有一些了解借助自动加载有用文件的库。

这是存储库的链接。 他们也已经给出了使用 OAuth2 提供程序的适当示例。

GraphQL-客户端

希望能帮助到你。

这是示例代码:

<?php
$client = \Softonic\GraphQL\ClientBuilder::build('https://catalog.swarm.pub.softonic.one/graphql');

$query = <<<'QUERY'
query GetFooBar($idFoo: String, $idBar: String) {
  foo(id: $idFoo) {
    id_foo
    bar (id: $idBar) {
      id_bar
    }
  }
}
QUERY;

$variables = [
    'idFoo' => 'foo',
    'idBar' => 'bar',
];
$response = $client->query($query, $variables);
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM