GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. It provides an efficient, powerful, and flexible alternative to RESTful APIs. In this tutorial, we'll explore how to implement GraphQL in PHP using the popular library webonyx/graphql-php.
GraphQL is a query language that allows clients to request exactly what they need from the server, making it more efficient than traditional REST APIs. It also provides a single endpoint for all data requests and supports real-time updates.
First, you need to install the webonyx/graphql-php library. You can do this using Composer:
composer require webonyx/graphql-php
The schema is the foundation of a GraphQL API. It defines the types and queries that are available.
<?php
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
// Define your query type
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'hello' => [
'type' => Type::string(),
'resolve' => function() {
return 'Hello, world!';
}
]
]
]);
// Create the schema
$schema = new Schema([
'query' => $queryType,
]);
Create a simple server to handle incoming requests.
<?php
use GraphQL\GraphQL;
use GraphQL\Error\FormattedError;
require_once __DIR__ . '/vendor/autoload.php';
// Load your schema
$schema = require_once 'schema.php';
// Get the query from the request
$query = $_POST['query'] ?? null;
try {
$result = GraphQL::executeQuery($schema, $query);
$output = $result->toArray();
} catch (\Exception $e) {
$output = [
'errors' => [FormattedError::createFromException($e)]
];
}
header('Content-Type: application/json');
echo json_encode($output);
You can test your server using a tool like Postman or GraphiQL. Send a POST request with the following JSON body:
{
"query": "{ hello }"
}
You should receive a response:
{
"data": {
"hello": "Hello, world!"
}
}
Mutations are used to modify data on the server. Let's add a mutation to our schema.
<?php
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
// Define your query type
$queryType = new ObjectType([
'name' => 'Query',
'fields' => [
'hello' => [
'type' => Type::string(),
'resolve' => function() {
return 'Hello, world!';
}
]
]
]);
// Define your mutation type
$mutationType = new ObjectType([
'name' => 'Mutation',
'fields' => [
'greet' => [
'type' => Type::string(),
'args' => [
'name' => ['type' => Type::nonNull(Type::string())]
],
'resolve' => function($root, $args) {
return "Hello, {$args['name']}!";
}
]
]
]);
// Create the schema
$schema = new Schema([
'query' => $queryType,
'mutation' => $mutationType,
]);
Subscriptions allow clients to receive real-time updates. This requires a server that supports WebSockets, such as Apollo Server or Absinthe.
<?php
use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Schema;
// Define your subscription type
$subscriptionType = new ObjectType([
'name' => 'Subscription',
'fields' => [
'newMessage' => [
'type' => Type::string(),
'resolve' => function() {
// Simulate a real-time event
return "New message received!";
}
]
]
]);
// Create the schema
$schema = new Schema([
'query' => $queryType,
'mutation' => $mutationType,
'subscription' => $subscriptionType,
]);
GraphQL provides a powerful way to build flexible and efficient APIs in PHP. By following the steps outlined in this tutorial, you can set up a basic GraphQL server and extend it with mutations and subscriptions. Remember to keep your schema well-defined and secure your API to ensure a robust implementation.