What is GraphQL?

GraphQL is, a core query language developed for optimal access to application information layer through APIs.
The powerful yet future-proof way for FrontEnd applications to interact with their BackEnd is to provide an easy scalable.

GraphQL has for supports various languages like

  • JavaScript
  • PHP
  • Python
  • Scala
  • Ruby
  • C#
  • .NET
  • Clojure
  • Elixir
  • Erlang
  • Go
  • Groovy
  • Java
  • 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.

    What’s Wrong With RESTful:

    In a way, GraphQL was born as a reaction to RESTful’s shortcomings. Let’s examine the main ones.

    An All-Or-Nothing Approach to Data Retrieval

    The whole premise of REST is to exchange resources, which are considered indivisible units of information.

    In many cases though, when asking for a particular resource, the requestor is not interested in each and every piece of data related to it but only a subset of it.

    For instance, if you are looking for information about a user in your system, you’d issue a request to an endpoint such as https://yourdomain.com/api/v1/user/aa32fd to get back something like:

    Nothing wrong with that but… what if all you needed was the name of the user?

    I know, I know, it’s just a few extra bytes in a string, right? Unless of course, the actual URL was something more like https://yourdomain.com/api/v1/user.

    In that case, the few extra bytes become a whole lot of extra bytes!

    One Query Per Object

    In the above example, if you wanted to know which country I live in you’d have to issue a second request.

    That’s not necessarily a problem but it certainly can make the application rather inefficient in certain scenarios for many PHP developers out there..

    Schema Rigidity

    What if you needed to stop supporting the storage of the gender field all of a sudden?

    Once your API has been implemented by many different clients there’d be no escape to changing your endpoints from https://yourdomain.com/api/v1 to https://yourdomain.com/api/v2 with all the implied hassle and associated costs of keeping two versions alive at the same time.

    Loose Semantics

    This is probably the point where REST and GraphQL differ the most.

    In REST all the information exchanged is text, there’s no type checking built-in. GraphQL, in turn, is strongly typed.

    Also, If you need to allow clients to do some filtering or pagination on the data they want, you need to resort to hacks such as extraneous custom HTTP headers.

    GraphQL has these capabilities as part of its core.

    In summary, REST is a lower-level protocol than GraphQL.

    Quick Introduction to GraphQL

    A GraphQL application, unlike a RESTful one, exposes a single endpoint, which mainly consists of the query parser and response generator.
    Probably the easiest way to think about a GraphQL API is as if it were a database server where there is a dedicated process listening to a specific port through which every possible query comes and, internally, there’s a component responsible for interpreting what is being requested.
    A GraphQL API is built on top of a basic definition, the schema. This definition will serve two purposes:

      1. Allow the query parser to validate the requests and produce the desired output.
      2. Act as a specification for the client to know what can be obtained from the API and how to query it.

    The main concepts you need to have clarity about in order to create a valid GraphQL schema are:

    • Type
    • Query
    • Resolvers

    How to Create a GraphQL Server With PHP

    As you can see, in order to expose a GraphQL API you need a fairly complex parser. Of course, there’s nothing stopping you from putting one together from scratch but, why would you?
    By now you’re probably thinking there must be nice open-source libraries to deal with all this hassle, right? Yes, there are. In fact, there are many of them.
    In this post, I’ll be discussing GraphQL-PHP for it is one of the most popular.

    Creating the Project

    Let’s start by creating a new directory for the project:

    mkdir gql-test && cd gql-test 
    			

    Then, let’s initialize it as a composer project:

    composer init
    			

    Fill the project details with the default values, and answer yes when asked. 

    Would you like to define your dependencies (require) interactively [yes]?
    			

    And then search for the package webonyx/graphql-php

    Keep accepting the defaults until you see a question such as:

    Add PSR-4 autoload mapping? Maps namespace "Mauro\GqlTest" to the entered relative path. [src/, n to skip]
    			

    If everything went well you should see something like:

    {
    		"name": "mauro/gql-test",
    		"require": {
    			"webonyx/graphql-php": "^14.11"
    		},
    		"authors": [
    			{
    				"name": "Mauro Chojrin",
    				"email": "mauro.chojrin@leewayweb.com"
    			}
    		]
    	  }
    	Do you confirm generation [yes]?
    		

    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.

    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.

    		
    	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);
    		 
    		
     Deep Vyas 9 months ago

    Each account has a limit on the number of API requests it can make.

    Leave a Reply

    *
    *
    *
    *