Have you heard about GraphQL?
GraphQL is a modern query language for the API. In another word, we can say it is a modern application layer query language.
With the help of GraphQL, we can fetch data from the API calls and it works on the HTTP as REST. It provides the powerful option to the client so that they ask what they exactly need and it helps in the API growth or evaluation.
Benefits of GraphQL
- It provides only limited data that we actually need. It will never fetch any extra data or less data that you do not need.
- It is a powerful open source system.
- It gives an option to do the efficient coding. For example, suppose a table 40 column and sometimes we need the data of only 10 column or sometimes 20 etc. To solve this problem we have two option in normal API, either fetch all data in every API call and use any we want or we have to write the number of APIs for the same table so that we can call the efficient API as per requirement. But in GraphQL, we have to write only one API. So line code also gets reduced.
- GraphQL API’s are structured in terms of Types and Fields.
GraphQL has for supports various languages like
- C#
- .NET
- Clojure
- Elixir
- Erlang
- Go
- Groovy
- Java
- JavaScript
- PHP
- Python
- Scala
- Ruby
In this blog, we will learn about the GraphQL in PHP.
Firstly we should know, in any language to use GraphQL we have to import their library.
In PHP, we can use this library file: webonyx/graphql-php.
Installation
Using composer, simply run:
composer require webonyx/graphql-php
How GraphQL Fetch Data with Queries?
In the REST, API returns data in a defined structure. While writing the API in REST we have to define the structure of data what it will return but GraphQL has no defined structure it will return. It can change their structure as per client need.
The client has to send some more information to the server in order to declare their requirements and this information is called the Query.
In the Query, we have to define the Root Fields in the other word we say the same as payload for the service.
Resolver
In the real world application like e-commerce application i.e. PrestaShop, OpenCart, Magneto etc. we need to fetch the customer data from the database by customerId and have to return the same. Our point is we don’t have to return the arrays, we have to return the values and graphql-php will pass it untouched to nested resolvers.
The resolver is basically a call back function for each field. There is always a default resolver for all fields. When we define our own resolve function for a field we simply override the default resolver.
How to define Schema for Query?
$schema_obj = new Schema { “query” => $queryType, “mutation” => $mutationType, “subscription” => $subscriptionType }
Example
As this is a blog for the beginners or fresher let’s do a simple example.
Let’s create a type system that will be to process following simple query:
query { echo(message: "Hi Knowband, this is my first GraphQL program") }
Note: We need an object type with field echo to do so.
<?php use GraphQL\Type\Definition\ObjectType; use GraphQL\Type\Definition\Type; $queryType = new ObjectType([ 'name' => 'Query', 'fields' => [ 'echo' => [ 'type' => Type::string(), 'args' => [ 'message' => Type::nonNull(Type::string()), ], 'resolve' => function ($root, $args) { return $root['prefix'] . $args['message']; } ], ], ]);
The resolve option is very important option of field definition. It is one which is responsible to for returning the value of our field. Values of the scalar fields will be directly get included in response while the values of the composite fields will be passed down to the nested field resolvers. Composite fields are interfaces, unions, objects etc.
Now after our type become ready, let’s write the GraphQL endpoint file for it graphql_program_1.php.
<?php use GraphQL\GraphQL; use GraphQL\Type\Schema; try { $schema_obj = new Schema([ 'query' => $queryType ]); $Input = file_get_contents('php://input'); $input_data = json_decode($Input, true); $query_data = $input_data['query']; $variable_values = isset($input_data['variables']) ? $input_data['variables'] : null; $value = ['prefix' => 'Output: ']; $resultant = GraphQL::executeQuery($schema_obj, $query_data, $value, null, $variable_values); $output_value = $resultant->toArray(); } catch (\Exception $e) { $output_value = [ 'errors' => [ [ 'message' => $e->getMessage() ] ] ]; } header('Content-Type: application/json'); echo json_encode($output_value); ?>
How can we run the code?
We can run the code by:
php -S localhost:8080 graphql_program_1.php curl https://localhost:8080 -d '{"query": "query { echo(message: \" Hi Knowband, this is my first GraphQL program \") }" }'
For any queries, please feel free to reach us at support@knowband.com. Knowband is providing the best in class modules for Prestashop, Opencart, Magento and Magento 2.
Take a look at one of our most popular for Prestashop called One page supercheckout: