Back to Top

How to use GraphQL in php

Updated 24 April 2024

GraphQL is a Query Language for Application programming interface (API’s) or we can say GraphQL is an application layer query language.
In short GraphQL  is a modern way to fetch data from API calls.
I called it a new or a modern way of consuming APIs , because it works on HTTP as REST works. It gives power to client to ask What exactly they need, that will help in API Evolution.

Key points :

  • It solves the over-fetching or under-fetching of data
  • It has strongly typed  system (schema)
  • More resource in single request
  • Powerful open source system etc.

Note : GraphQL API’s are structured in  terms of Type and Field.

Fetching Data with Queries :

When loading data in REST , we have different end point with defined structure of information it will return, but In GraphQL we have a single end point that has no defined structure it will return.

It is completely Flexible. client decide what they need and ask for the same.
So client need to send more information to the server to express its need and this information is called a Query .

Searching for an experienced
Magento 2 Company ?
Find out More

In Query we need to define a Root Field that we can say is a payload for the service.

Queries with Arguments :

In Graph, each field can have zero or more arguments if that’s specified in the schema.

Data with Mutations : Query is used to fetch data but there could be a need where a person need to make changes in backend data. So to achieve this in GraphQL we use Mutations.
Mutation Operations :
– creating new data
– updating existing data
– deleting existing data

Subscriptions : Subscription is used for real time connection to the server to inform about the event that occurred.

GraphQL supported languages :
GraphQL has support for almost all languages, you just need to include the library for that.
In my case I have used this php library : webonyx/graphql-php .

$ composer require webonyx/graphql-php

let’s see one basic example that may help you understand how GraphQL Works but before that let’s understand what resolver is ?,  Resolver is basically a Function or we can say call back function for each field.

Step 1 : After requiring the GraphQL Package , include following Classes in your project.

use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\Type;
use GraphQL\GraphQL;
use GraphQL\Type\Schema;

Note : GraphQL is a root Class.

Step 2 : Define the Schema for your Query.

$schema = new Schema([
    "query" => $queryType
]);

As this example will walk you around QueryType, that’s why I have defined only Query in schema parameter.
similarly we can define mutations as well.
Example :
new Schema {
“query” => <Query>,
“mutation” => <Mutation>,
“subscription” => <Subscription>
}
Step 3 : Now we need to define the Query Type Object.

$queryType = new ObjectType([
    'name' => 'Query',
    'fields' => [
        'customer' => [
            'type' => $userType,
            'args' => [
                'id' => Type::int(),
            ],
            'resolve' => function ($root, $args) {
                $returnArray = [];
                foreach($root as $key => $customer) {
                    if ($customer["id"] == $args["id"])
                        $returnArray = $customer;
                }
                return $returnArray;
            }
        ],
    ],
]);

You must have observer that Object Type has a Field named as Customer with backed resolver function,
which has two parameter one is $root i.e. Root Value  and another is $args which is used when we can specific customer data via ID.

Step 4 : As Query Type Object’s Field customer have relation with other Object Type  called User type, So we need to define this object as well. Similarly we can have other nesting object connections as well. As in below code.

$street = new ObjectType([
    'name' => 'Street',
    'description' => 'Customer Address from json object',
    'fields' => [
        'street1' => Type::string(),
        'street2' => Type::string(),
    ]
]);

$address = new ObjectType([
    'name' => 'Address',
    'description' => 'Customer Address from json object',
    'fields' => [
        'addressId' => Type::int(),
        'state' => Type::string(),
        'city' => Type::string(),
        'street' => [
            "type" => $street,
            'resolve' => function($root, $args, $context) {
                return $root['street']   ;
            }
        ],
        'country' => Type::string()
    ]
  ]);

$userType = new ObjectType([
    'name' => 'Customer',
    'description' => 'Customer from json object',
    'fields' => [
        'id' => Type::int(),
        'firstname' => Type::string(),
        'lastname' => Type::string(),
        'age' => Type::int(),
        'address' => [
            "type" => $address,
            'resolve' => function($root, $args, $context) {
                return $root['address']   ;
            }
        ]
    ]
]);

Step 5 : Now it time to define the Root Value , you can have the values dynamically, as this is to give you a basic understanding how GraphQL works , I have set the static $rootValue as below :

$customer = [
    [
        "id"=>1,
        "firstname"=>"John",
        "lastname"=>"Doe",
         "age"=>14,
         "address" => 
           [
            "addressId"=> 1,
             "street"=>["street1" => "167","street2" => "XX Floor"],
             "city"=>"New York",
             "state"=>"NY",
             "country" => "USA"
         ]
    ],
    [
        "id"=>2,
        "firstname" => "chris",
        "lastname" => "Martin",
        "age"=>29,
        "address" => [
            "addressId"=> 2,
             "street"=>["street1" => "167","street2" => "XX Floor"],
             "city"=>"New York",
             "state"=>"NY",
             "country" => "USA"
        ]
    ],
    [
        "id"=>3,
        "firstname" => "Jenny",
        "lastname" => "Ketty",
        "age"=>32,
        "address" => [
            "addressId"=> 3,
             "street"=>["street1" => "167","street2" => "XX Floor"],
             "city"=>"New York",
             "state"=>"NY",
             "country" => "USA"
        ]
    ],
    [
        "id"=>4,
        "firstname" => "Jennifer",
        "lastname" => "Tim",
        "age"=>31,
        "address" => [
             "addressId"=> 4,
             "street"=>["street1" => "167","street2" => "XX Floor"],
             "city"=>"New York",
             "state"=>"NY",
             "country" => "USA"
        ]
    ]
];

Step 6 :Now Final step how Query is processed :

try{
    $rawInput = file_get_contents('php://input');
    $input = json_decode($rawInput, true);
    $query = $input['query'];

    $variableValues = isset($input['variables']) ? $input['variables'] : null;
    $variableValues=[];
    $rootValue = $customer;
    $result = GraphQL::executeQuery($schema, $query, $rootValue, null, $variableValues);

    $output = $result->toArray();
} catch (\Exception $e) {
    $output = [
        'error' => [
            'message' => $e->getMessage()
        ]
    ];
}

header('Content-Type: application/json');
echo json_encode($output);

GraphQL class’s executeQuery function is used to process the Requested Query as you can see above.
The process is we need to get the demand of the user which is called Query and need to forward to the ExecuteQuery function along with root Value then GraphQL will return the Data as per defined type, field and resolver functions.

Note : GraphQL has Tool Called GraphiQL for Introspection.
GraphiQL – An in-browser IDE for exploring GraphQL
ChromeiQL or GraphiQL Feen – GraphiQL as Google Chrome extension

In GraphiQL Tool We need to set the GraphQL End point.
Please check the below Screen shot of GraphiQL Tool with the above Example :

GraphQl

In Next Blog I will Explain few more Points with Example.

Mean while Please try the above example and If you have any Query then please feel free to put it in comment section.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


8 comments

  • Feyyaz YILMAZ
    • Prabhat Rawat (Moderator)
  • Ratikanta
  • jenni
    • Prabhat Rawat (Moderator)
      • jenni
        • Prabhat Rawat (Moderator)
          • Amazing
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home