Menu Close
    Start a Project Request quote Reading list Switch to dark mode

    How to use GraphQL in php

    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 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

    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 .

    let’s see once 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.

    Note : GraphQL is a root Class.

    Step 2 : Define the Schema for your Query.

    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,

    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.

    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 :

    Step 6 :Now Final step how Query is processed :

    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.

    . . .

    Comments (8)

    Add Your Comment

  • 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
      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_URL => ‘’,
      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 {
        permanent {

        $postArray= array(
        “query” => “query categories {
        archiveCategories(vatnumber: \”0994500932\”) {
        various {
        permanent {
        ) ;
        $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
          $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}}}}”}
          $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
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again