Reading list Switch to dark mode

    How to use GraphQL in php

    Updated 5 January 2023

    GraphQL is a Query Language for the 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 .
    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

    Searching for an experienced
    Magento 2 Company ?
    Read More

    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 :

    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.

    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    8 comments

  • Feyyaz YILMAZ
    Can you send me source code. Specially this part
    $rawInput = file_get_contents(‘php://input’);
    $input = json_decode($rawInput, true);
    $query = $input[‘query’];
    what include this file?

    $variableValues = isset($input[‘variables’]) ? $input[‘variables’] : null;

  • Ratikanta
    I am not able to run it correctly. Could you please share the complete code?
  • jenni
    I am new in graphQL. I need to get data from a server which is using graphQL and I need to use PHP curl for passing the inputs.
    Is this a right query to pass to curl for getting data?
    $query = << $query ]);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $json );

    I am getting the following message , but I couldn’t findout any issue
    “message”:”mismatched input ‘\”query\”‘ expecting {‘…’, ‘fragment’, ‘query’, ‘mutation’, ‘subscription’, ‘schema’, ‘scalar’, ‘go_type’, ‘interface’, ‘implements’, ‘enum’, ‘union’, ‘input’, ‘extend’, ‘directive’, NAME}”}]}
    I am getting the result when I am running the query in grapghql playground. But with PHP curl its not getting.can you please help?

    • Prabhat Rawat (Moderator)
      Thank you for contacting us,
      as I can see you have used curl to get the response.

      As I do not have the idea how you have created schema and query and resolver,

      so I can suggest you to check how you are reading the query requesting the values.

      Example : As per the blog, the curl request code will be with post values :

      Solution 1 :
      CURLOPT_POSTFIELDS => ‘{“query”:”query { customer(id : 3) { address { addressId state city } }}”,”variables”:null}’

      Solution 2 :
      ->
      curl_setopt_array($curl, array(
      CURLOPT_RETURNTRANSFER => 1,
      CURLOPT_URL => ‘http://example.com’,
      CURLOPT_USERAGENT => ‘Sample cURL Request’,
      CURLOPT_POST => 1,
      CURLOPT_POSTFIELDS => array(
      ‘query’ => ‘query { customer(id : 3) { address { addressId state city } }}’
      )
      ));

      -> you need to change the 6th Step : so that it accept the post values :
      Some thing like this, $query = $_POST[‘query’];

      Both are tested and working you can use either one among them.

      • jenni
        Thankyou very much for your reply. I tried with your two solutons but I am not able to get my result.

        Here is my query

        query categories {
        archiveCategories(vatnumber: \”0994500932\”) {
        various {
        id,
        name
        },
        permanent {
        id,
        name
        }
        }
        }
        ————————

        $postArray= array(
        “query” => “query categories {
        archiveCategories(vatnumber: \”0994500932\”) {
        various {
        id,
        name
        },
        permanent {
        id,
        name
        }
        }
        }”
        ) ;
        $json = json_encode($postArray); // tried without encode also

        curl_setopt($ch, CURLOPT_URL, “https://api.cmyurl/graphql”);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json );
        curl_setopt($ch, CURLOPT_POST, 1);

        I am getting the error like this
        {“errors”:[{“locations”:[{“column”:2,”line”:1}],”message”:”mismatched input ‘\”query\”‘ expecting {‘…’, ‘fragment’, ‘query’, ‘mutation’, ‘subscription’, ‘schema’, ‘scalar’, ‘go_type’, ‘interface’, ‘implements’, ‘enum’, ‘union’, ‘input’, ‘extend’, ‘directive’, NAME}”}]}

        • Prabhat Rawat (Moderator)
          $json = json_encode($postArray); // tried without encode also
          :-> yes do try without encode but before using curl please print once the params is right or not.

          Error in your query is \”0994500932\” : please remove double quotes and then try.

          your array should look like this :
          {“query”:”query { categories {archiveCategories(vatnumber: 0994500932) {various {id}}}}”}
          decode
          $input = json_decode(‘{“query”:”query { categories {archiveCategories(vatnumber: 0994500932) {various {id}}}}”}’,true);
          output :
          Array ( [query] => query categories { archiveCategories(vatnumber: 0994500932) {various {id}}}} )
          Note : if you are able to get this array then it will work.

          Suggestion : please try small query first example : ‘{“query”:”query {categories(id : 3){name} } }”}’ .

          hope this will help.

          use demo query :
          $json = array (“query” => “query { categories(id : 3){name} }}”);

          curl_setopt($ch, CURLOPT_POSTFIELDS, $json );

          if still you do not get the desired result then please use my blog’s content completely and, exact query from my previous reply and you will surely get the desired result.

          • Amazing
            Nice Idea
  • Back to Top

    Message Sent!

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

    Back to Home