[英]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 提供程序的適當示例。
希望能幫助到你。
這是示例代碼:
<?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.