GraphQL – Schema ”; Previous Next A GraphQL schema is at the core of any GraphQL server implementation. It describes the functionality available to the client applications that connect to it. We can use any programming language to create a GraphQL schema and build an interface around it. The GraphQL runtime defines a generic graph-based schema to publish the capabilities of the data service it represents. Client applications can query the schema within its capabilities. This approach decouples clients from servers and allows both to evolve and scale independently. In this chapter, we use Apollo server to execute GraphQL queries. The makeExecutableSchema function in graphql-tools helps you to bind schema and resolvers. makeExecutableSchema Function Syntax The makeExecutableSchema function takes a single argument {} of Object type. The syntax for using this function is given below − import { makeExecutableSchema } from ”graphql-tools”; const jsSchema = makeExecutableSchema({ typeDefs, resolvers, // optional logger, // optional allowUndefinedInResolve = false, // optional resolverValidationOptions = {}, // optional directiveResolvers = null, // optional schemaDirectives = null, // optional parseOptions = {}, // optional inheritResolversFromInterfaces = false // optional }); Sr.No. Parameter & Description 1 typeDefs This is a required argument. It represents a GraphQL query as a UTF-8 string. 2 Resolvers This is an optional argument (empty object by default). This has functions that handle the query. 3 logger This is an optional argument and can be used to print errors to the server console. 4 parseOptions This is an optional argument and allows customization of parse when specifying typeDefs as a string. 5 allowUndefinedInResolve This is true by default. When set to false, causes your resolve functions to throw errors if they return undefined. 6 resolverValidationOptions This is an optional argument and accepts an object with Boolean properties. 7 inheritResolversFromInterfaces This is an optional argument and accepts a Boolean argument to check resolvers object inheritance. Illustration Let us create a simple application to understand this schema. This will create a schema for querying list of students from the server. The student data will be stored in a flat file and we will use a node module called notarealdb to fake a database and read from the flat file. Step 1 − Download and Install Required Dependencies for the Project Create a folder named schema-app. Change your directory to schema-app from the terminal. Then, follow steps 3 to 5 explained in the Environment Setup chapter to complete the download and the installation process. Step 2 − Create a Schema Add schema.graphql file in the project folder, schema-app and add the following code − type Query { greeting:String students:[Student] } type Student { id:ID! firstName:String lastName:String password:String collegeId:String } The root of the schema will be Query type. The query has two fields − greeting and Students that returns String and a list of students respectively. Student is declared as an Object type since it contains multiple fields. The ID field is declared as non-nullable. Step 3 − Create Resolver Create a file resolvers.js in the project folder and add the following code − const db = require(”./db”) const Query = { greeting:() => { return “hello from TutorialsPoint !!!” }, students:() => db.students.list() } module.exports = {Query} Here greeting and students are the resolvers that handle the query. students resolver function returns a list of students from the data access layer. To access resolver functions outside the module, Query object has to be exported using module.exports. Step 4 − Run the Application Create a server.js file and refer step 8 in the Environment Setup Chapter. The next step is to execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open browser and type the URL, http://localhost:9000/graphiql. Type the following query in the editor − { greeting students { id firstName lastName } } The query will display the output as shown below − Note − We can replace the students.json with a RESTful API call to retrieve student data or even a real database like MySQL or MongoDB. GraphQL becomes a thin wrapper around your original application layer to improve performance. Print Page Previous Next Advertisements ”;
Category: graphql
GraphQL – JQuery Integration
GraphQL – JQuery Integration ”; Previous Next Web applications send and retrieve data asynchronously (in the background). AJAX allows websites to load content onto the screen without refreshing the page. jQuery provides several methods for AJAX functionality thus making it easier to use AJAX. In this chapter, we shall learn how we can integrate GraphQL with jQuery. Consider an application using client server architecture. We can build a front end webpage that requests data from a GraphQL server. The webpage will make AJAX calls using jQuery to the GraphQL server. To integrate GraphQL with JQuery, let us inspect the GraphiQL request headers and understand the request parameters. Start the hello-world app (refer to chapter 6 for the relevant illustration). Type the graphql query {greeting} in the GraphiQL window. Right-click and inspect or press (ctrl + shift + I) on chrome to go to the network tab as shown below − From the simple hello-world example, we can understand that http method used is POST. Now in the browser, scroll down to the header section to view the request payload. Once you click on view code, you will see the following in the request payload section of chrome. {“query”:”{n greetingn}”,”variables”:null,”operationName”:null} Also note the request URL, http://localhost:9000/graphql that should be called from client application. Illustration Let us understand how to integrate GraphQL with JQuery using a step-wise process. Setting up the Server We will learn to set up the server using the following steps − Step 1 − Download and Install Required Dependencies for the Project Create a folder named jquery-server-app. Change your directory to jquery-server-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter. Step 2 − Create a Schema Add schema.graphql file in the project folder jquery-server-app and add the following code − type Query { greeting: String sayHello(name:String!):String } The file has defined two queries greeting and sayHello. The sayHello query accepts a string parameter and returns another string. The parameter to the sayHello() function is not null. Step 3 − Create Resolvers Create a file resolvers.js in the project folder and add the following code − const Query = { greeting: () => ”Hello GraphQL From TutorialsPoint !!” , sayHello:(root,args,context,info) => `Hi ${args.name} GraphQL server says Hello to you!!` } module.exports = {Query} Here, greeting and sayHello are two resolvers. In sayHello resolver, the value passed to the name parameter can be accessed through args. To access resolver functions outside the module, Query object has to be exported using module.exports. Step 4 − Run the Application Create a server.js file. Refer to step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor − { greeting, sayHello(name:”Mohtashim”) } The response from the server is as given below − { “data”: { “greeting”: “Hello GraphQL From TutorialsPoint !!”, “sayHello”: “Hi Mohtashim GraphQL server says Hello to you!!” } } Setting up the Client Since, we have already set up the server, now we will learn how to set up the client. Step 1 − Create a new folder jquery-client-app outside the current project folder First, we will create a folder named jquery-client-app outside the project folder. Step 2 − Create a HTML Page index.html for jQuery Integration We will create a client application in jquery and invoke both the methods. Following is the code for index.html file. The index.html page sends requests to the server when the buttons – Greet and SayHello are clicked. We will make asynchronous request using $.ajax() function. <!DOCTYPE html> <html> <head> <script src = “https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script> <script> $(document).ready(function() { $(“#btnSayhello”).click(function() { const name = $(“#txtName”).val(); console.log(name); $(“#SayhelloDiv”).html(”loading….”); $.ajax({url: “http://localhost:9000/graphql”, contentType: “application/json”,type:”POST”, data: JSON.stringify({ query:`{ sayHello(name:”${name}”)}` }), success: function(result) { console.log(JSON.stringify(result)) $(“#SayhelloDiv”).html(“<h1>”+result.data.sayHello +”</h1>”); } }); }); $(“#btnGreet”).click(function() { $(“#greetingDiv”).html(”loading….”); //https://kannan-first-graphql-app.herokuapp.com/graphql $.ajax({url: “http://localhost:9000/graphql”, contentType: “application/json”, type:”POST”, data: JSON.stringify({ query:`{greeting}` }), success: function(result) { $(“#greetingDiv”).html(“<h1>”+result.data.greeting+”</h1>”); } }); }); }); </script> </head> <body> <h1>Jquery Client </h1> <hr/> <section> <button id = “btnGreet”>Greet</button> <br/> <br/> <div id = “greetingDiv”> </div> </section> <br/> <br/> <br/> <hr/> <section> Enter a name:<input id = “txtName” type = “text” value = “kannan”/> <button id = “btnSayhello”>SayHello</button> <div id = “SayhelloDiv”> </div> </section> </body> </html> Open this file in the browser and click on the button to see the response. The output will be as given below − Print Page Previous Next Advertisements ”;
GraphQL – Query
GraphQL – Query ”; Previous Next A GraphQL operation can either be a read or a write operation. A GraphQL query is used to read or fetch values while a mutation is used to write or post values. In either case, the operation is a simple string that a GraphQL server can parse and respond to with data in a specific format. The popular response format that is usually used for mobile and web applications is JSON. The syntax to define a query is as follows − //syntax 1 query query_name{ someField } //syntax 2 { someField } Following is an example of a query − //query with name myQuery query myQuery{ greeting } // query without any name { greeting } It is clear from the above example that the query keyword is optional. GraphQL queries help to reduce over fetching of data. Unlike a Restful API, GraphQL allows a user to restrict fields that should be fetched from the server. This means smaller queries and lesser traffic over the network; which in turn reduces the response time. Illustration 1 – Query Student Model with a Custom Field In this example, we have a set of students stored in a json file. Each student model has fields like firstName, lastName and id but no fullName. Here, we will discuss how to make a query to retrieve fullName of all students. For this, we need to create fullName field in both schema resolver. Let us see how to do this illustration using the below steps − Step 1 − Download and Install Required Dependencies for the Project Create a folder named query-app. Change your directory to query-app from the terminal. Later, follow steps 3 to 5 explained in the Environment Setup chapter. Step 2 − Create a Schema Add schema.graphql file in the project folder query-app and add the following code − type Query { greeting:String students:[Student] studentById(id:ID!):Student } type Student { id:ID! firstName:String lastName:String fullName:String } Note that there is no fullName field in the students.json file. However, we need to fetch the fullname of the student via a query. The fullName, in this case will be a custom field that isn”t available with the data source. Step 3 − Create Resolver Create a file resolvers.js in the project folder and add the following code − const db = require(”./db”) const Query = { //resolver function for greeting greeting:() => { return “hello from TutorialsPoint !!!” }, //resolver function for students returns list students:() => db.students.list(), //resolver function for studentbyId studentById:(root,args,context,info) => { //args will contain parameter passed in query return db.students.get(args.id); } } //for each single student object returned,resolver is invoked const Student = { fullName:(root,args,context,info) => { return root.firstName+”:”+root.lastName } } module.exports = {Query,Student} Step 4 − Run the Application Create a server.js file. Refer step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor − { students{ id fullName } } The response for the query is given below − { “data”: { “students”: [ { “id”: “S1001”, “fullName”: “Mohtashim:Mohammad” }, { “id”: “S1002”, “fullName”: “Kannan:Sudhakaran” }, { “id”: “S1003”, “fullName”: “Kiran:Panigrahi” } ] } } Create a server.js and add the following code − const bodyParser = require(”body-parser”); const cors = require(”cors”); const express = require(”express”); const db = require(”./db”); const port = 9000; const app = express(); //loading type definitions from schema file const fs = require(”fs”) const typeDefs = fs.readFileSync(”./schema.graphql”,{encoding:”utf-8”}) //loading resolvers const resolvers = require(”./resolvers”) //binding schema and resolver const {makeExecutableSchema} = require(”graphql-tools”) const schema = makeExecutableSchema({typeDefs, resolvers}) //enabling cross domain calls and form post app.use(cors(), bodyParser.json()); //enabling routes const {graphiqlExpress,graphqlExpress} = require(”apollo-server-express”) app.use(”/graphql”,graphqlExpress({schema})) app.use(”/graphiql”,graphiqlExpress({endpointURL:”/graphql”})) //registering port app.listen(port, () => console.info(`Server started on port ${port}`)); Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open the browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor − { students{ id fullName } } The response for the query is given below − { “data”: { “students”: [ { “id”: “S1001”, “fullName”: “Mohtashim:Mohammad” }, { “id”: “S1002”, “fullName”: “Kannan:Sudhakaran” }, { “id”: “S1003”, “fullName”: “Kiran:Panigrahi” } ] } } Illustration 2 – Nested Query Let us create a nested query for fetching the student details and their college details. We will work with the same project folder. Step 1 − Edit the Schema The schema file already has the student field. Let us add a field college and define its type. type College { id:ID! name:String location:String rating:Float } type Student { id:ID! firstName:String lastName:String fullName:String college:College } Step 2 − Modify the resolver.js We need to add a college resolver function as below. The college resolver function will be executed for each student object returned. The root parameter of resolver in this case will contain student. const Student = { fullName:(root,args,context,info) => { return root.firstName+”:”+root.lastName }, college:(root) => { return db.colleges.get(root.collegeId); } } module.exports = {Query,Student} The resolver returns college of each student by calling the get method of college collection and passing the collegeId. We have association relationship between Student and College through the collegeId. Step 3 − Test the Application Open the terminal window and navigate to the project folder. Type the command -npm start. Launch the browser and enter the URL http://localhost:9000/graphiql. Enter the following query in the GraphiQL window − { students{ id firstName college { id name location rating } } } The response for the query is as given below − { “data”: { “students”: [ { “id”: “S1001”, “firstName”: “Mohtashim”, “college”: { “id”: “col-102”, “name”: “CUSAT”, “location”: “Kerala”, “rating”: 4.5 } }, { “id”: “S1002”, “firstName”: “Kannan”, “college”: { “id”: “col-101”, “name”: “AMU”, “location”: “Uttar Pradesh”, “rating”: 5 } },
GraphQL – Mutation
GraphQL – Mutation ”; Previous Next In this chapter, we will learn mutation queries in GraphQL. Mutation queries modify data in the data store and returns a value. It can be used to insert, update, or delete data. Mutations are defined as a part of the schema. The syntax of a mutation query is given below − mutation{ someEditOperation(dataField:”valueOfField”):returnType } Illustration Let us understand how to add new student record into the datastore using a mutation query. Step 1 − Download and Install Required Dependencies for the Project Create a project folder by the name mutation-app. Change your directory to mutation-app from the terminal. Follow steps 3 to 5 explained in the Environment Setup chapter. Step 2 − Create a schema.graphql File Add schema.graphql file in the project folder mutation-app and add the following code − type Query { greeting:String } type Mutation { createStudent(collegeId:ID,firstName:String,lastName:String):String } Note that the function createStudent returns a String type. This is a unique identifier (ID) which is generated after creating a student. Step 3 − Create a resolver.js File Create a file resolvers.js in the project folder and add the following code − const db = require(”./db”) const Mutation = { createStudent:(root,args,context,info) => { return db.students.create({collegeId:args.collegeId, firstName:args.firstName, lastName:args.lastName}) } } const Query = { greeting:() => “hello” } module.exports = {Query,Mutation} The mutation function points to students collection in the datastore. To add a new student, invoke the create method in students collection. The args object will contain the parameters which are passed in the query. The create method of students collection will return the id of a newly created student object. Step 4 − Run the Application Create a server.js file. Refer to step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Next step is to open browser and type the URL http://localhost:9000/graphiql. Type the following query in the editor − //college Id should be matched with data from colleges.json for easy retrieval mutation { createStudent(collegeId:”col-2″,firstName:”Tim”,lastName:”George”) } The above query will create a student object in student.json file. The query will return a unique identifier. The response of the query is as shown below − { “data”: { “createStudent”: “SkQtxYBUm” } } To verify if the student object is created, we can use the studentById query. You can also open the students.json file from data folder to verify the id. To use studentById query, edit the schema.graphql as given below − type Query { studentById(id:ID!):Student } type Student { id:ID! firstName:String lastName:String collegeId:String } Edit the resolver.js file as given below − const db = require(”./db”) const Query = { studentById:(root,args,context,info) => { return db.students.get(args.id); } } const Mutation = { createStudent:(root,args,context,info) => { return db.students.create({collegeId:args.collegeId, firstName:args.firstName, lastName:args.lastName}) } } module.exports = {Query,Mutation} Given below is the query to get student by unique id returned from the mutation query − { studentById(id:”SkQtxYBUm”) { id firstName lastName } } The response from the server is as follows − { “data”: { “studentById”: { “id”: “SkQtxYBUm”, “firstName”: “Tim”, “lastName”:”George” } } } Returning an Object in Mutation It is best practice to return an object in mutation. For example, the client application wants to fetch student and college details. In this case, rather than making two different requests, we can create a query that returns an object containing students and their college details. Step 1 − Edit Schema File Add a new method named addStudent which returns object in mutation type of schema.graphql. Let us learn how to access the college details through student details. Add college type in the schema file. type Mutation { addStudent_returns_object(collegeId:ID,firstName:String,lastName:String):Student createStudent(collegeId:ID,firstName:String,lastName:String):String } type College { id:ID! name:String location:String rating:Float } type Student { id:ID! firstName:String lastName:String college:College } Step 2 − Update the resolvers.js File Update a file resolvers.js in the project folder and add the following code − const Mutation = { createStudent:(root,args,context,info) => { return db.students.create({ collegeId:args.collegeId, firstName:args.firstName, lastName:args.lastName }) }, // new resolver function addStudent_returns_object:(root,args,context,info) => { const id = db.students.create({ collegeId:args.collegeId, firstName:args.firstName, lastName:args.lastName }) return db.students.get(id) } } //for each single student object returned,resolver is invoked const Student = { college:(root) => { return db.colleges.get(root.collegeId); } } module.exports = {Query,Student,Mutation} Step 3 − Start the Server and Type the Request Query in GraphiQL Next, we shall start the server and request query in GraphiQL with the following code − mutation { addStudent_returns_object(collegeId:”col-101″,firstName:”Susan”,lastName:”George”) { id firstName college{ id name } } } The above query adds a new student and retrieves the student object along with college object. This saves round trips to the server. The response is as given below − { “data”: { “addStudent_returns_object”: { “id”: “rklUl08IX”, “firstName”: “Susan”, “college”: { “id”: “col-101”, “name”: “AMU” } } } } Print Page Previous Next Advertisements ”;
GraphQL – Resolver
GraphQL – Resolver ”; Previous Next Resolver is a collection of functions that generate response for a GraphQL query. In simple terms, a resolver acts as a GraphQL query handler. Every resolver function in a GraphQL schema accepts four positional arguments as given below − fieldName:(root, args, context, info) => { result } An example of resolver functions is shown below − //resolver function with no parameters and returning string greeting:() => { return “hello from TutorialsPoint !!!” } //resolver function with no parameters and returning list students:() => db.students.list() //resolver function with arguments and returning object studentById:(root,args,context,info) => { return db.students.get(args.id); } Given below are the positional arguments and their description − Sr.No. Arguments & Description 1 root The object that contains the result returned from the resolver on the parent field. 2 args An object with the arguments passed into the field in the query. 3 context This is an object shared by all resolvers in a particular query. 4 info It contains information about the execution state of the query, including the field name, path to the field from the root. Resolver Result Format Resolvers in GraphQL can return different types of values as given below − Sr.No. Arguments and Description 1 null or undefined this indicates the object could not be found 2 array this is only valid if the schema indicates that the result of a field should be a list 3 promise resolvers often do asynchronous actions like fetching from a database or backend API, so they can return promises 4 scalar or object a resolver can also return other values Illustration Let us create a simple application to understand resolver. This will create schema for querying a student by id from the server. The student data will be stored in a flat file and we will use a node module called notarealdb to fake a database and read from flat file. The following is a step-wise process to create a simple application − Step 1 − Download and Install Required Dependencies for the Project Create a folder named resolver-app. Change your directory to resolver-app from the terminal. Later, follow steps 3 to 5 in the Environment Setup chapter. Step 2 − Create a Schema Add schema.graphql file in the project folder resolver-app and add the following code − type Query { greeting:String students:[Student] studentById(id:ID!):Student } type Student { id:ID! firstName:String lastName:String password:String collegeId:String } The schema file shows that user can query for greeting, students and studentById. To retrieve students with specific id, we use data type ID! which shows a non nullable unique identifier field. The students field returns an array of students, and greeting returns a simple string value. Step 3 − Create Resolver Create a file resolvers.js in the project folder and add the following code − const db = require(”./db”) const Query = { //resolver function for greeting greeting:() => { return “hello from TutorialsPoint !!!” }, //resolver function for students returns list students:() => db.students.list(), //resolver function for studentbyId studentById:(root,args,context,info) => { //args will contain parameter passed in query return db.students.get(args.id); } } module.exports = {Query} Here, studentById takes in three parameters. As discussed in this chapter, the studentId can be retrieved from args; root will contain the Query object itself. To return a specific student, we need to call get method with id parameter in the students collection. Here greeting, students, studentById are the resolvers that handle the query. students resolver function returns a list of students from the data access layer. To access resolver functions outside the module, Query object has to be exported using module.exports. Step 4 − Run the Application Create a server.js file. Refer step 8 in the Environment Setup Chapter. Execute the command npm start in the terminal. The server will be up and running on 9000 port. Here, we use GraphiQL as a client to test the application. Open the browser and enter the url, http://localhost:9000/graphiql. Type the following query in the editor − { studentById(id:”S1001″) { id firstName lastName } } The output for the above query is as shown below − { “data”: { “studentById”: { “id”: “S1001”, “firstName”: “Mohtashim”, “lastName”: “Mohammad” } } } Print Page Previous Next Advertisements ”;
GraphQL – Type System
GraphQL – Type System ”; Previous Next GraphQL is a strongly typed language. Type System defines various data types that can be used in a GraphQL application. The type system helps to define the schema, which is a contract between client and server. The commonly used GraphQL data types are as follows − Sr.No. Types & Description 1 Scalar Stores a single value 2 Object Shows what kind of object can be fetched 3 Query Entry point type to other specific types 4 Mutation Entry point for data manipulation 5 Enum Useful in a situation where you need the user to pick from a prescribed list of options Scalar Type Scalar types are primitive data types that can store only a single value. The default scalar types that GraphQL offers are − Int − Signed 32-bit Integer Float − Signed double precision floating point value String − UTF – 8-character sequence Boolean − True or false ID − A unique identifier, often used as a unique identifier to fetch an object or as the key for a cache. The syntax for defining a scalar type is as follows − field: data_type The snippet given below defines a field named greeting which returns String value. greeting: String Object Type The object type is the most common type used in a schema and represents a group of fields. Each field inside an object type maps to another type, thereby allowing nested types. In other words, an object type is composed of multiple scalar types or object types. The syntax for defining an object type is given below − type object_type_name { field1: data_type field2:data_type …. fieldn:data_type } You can consider the following code snippet − –Define an object type– type Student { stud_id:ID firstname: String age: Int score:Float } –Defining a GraphQL schema– type Query { stud_details:[Student] } The example given above defines an object data-type Student. The stud_details field in the root Query schema will return a list of Student objects. Query Type A GraphQL query is used to fetch data. It is like requesting a resource in REST-based APIs. To keep it simple, the Query type is the request sent from a client application to the GraphQL server. GraphQL uses the Schema Definition Language (SDL) to define a Query. Query type is one of the many root-level types in GraphQL. The syntax for defining a Query is as given below − type Query { field1: data_type field2:data_type field2(param1:data_type,param2:data_type,…paramN:data_type):data_type } An example of defining a Query − type Query { greeting: String } Mutation Type Mutations are operations sent to the server to create, update or delete data. These are analogous to the PUT, POST, PATCH and DELETE verbs to call REST-based APIs. Mutation is one of the root-level data-types in GraphQL. The Query type defines the entry-points for data-fetching operations whereas the Mutation type specifies the entry points for data-manipulation operations. The syntax for defining a Mutation type is given below − type Mutation { field1: data_type field2(param1:data_type,param2:data_type,…paramN:data_type):data_type } For example, we can define a mutation type to add a new Student as below − type Mutation { addStudent(firstName: String, lastName: String): Student } Enum Type An Enum is similar to a scalar type. Enums are useful in a situation where the value for a field must be from a prescribed list of options. The syntax for defining an Enum type is − type enum_name{ value1 value2 } Following snippet illustrates how an enum type can be defined − type Days_of_Week{ SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY } List Type Lists can be used to represent an array of values of specific type. Lists are defined with a type modifier [] that wraps object types, scalars, and enums. The following syntax can be used to define a list type − field:[data_type] The below example defines a list type todos − type Query { todos: [String] } Non-Nullable Type By default, each of the core scalar types can be set to null. In other words, these types can either return a value of the specified type or they can have no value. To override this default and specify that a field must be defined, an exclamation mark (!) can be appended to a type. This ensures the presence of value in results returned by the query. The following syntax can be used to define a non-nullable field − field:data_type! In the below example, stud_id is declared as a mandatory field. type Student { stud_id:ID! firstName:String lastName:String fullName:String college:College } Print Page Previous Next Advertisements ”;
GraphQL – Environment Setup
GraphQL – Environment Setup ”; Previous Next In this chapter, we will learn about the environmental setup for GraphQL. To execute the examples in this tutorial you will need the following − A computer running Linux, macOS, or Windows. A web browser, preferably the latest version of Google Chrome. A recent version of Node.js installed. The latest LTS version is recommended. Visual Studio Code with extension GraphQL for VSCode installed or any code editor of your choice. How to Build a GraphQL server with Nodejs We will go through a detailed step-wise approach to build GraphQL server with Nodejs as shown below − Step 1 − Verify Node and Npm Versions After installing NodeJs, verify the version of node and npm using following commands on the terminal − C:UsersAdmin>node -v v8.11.3 C:UsersAdmin>npm -v 5.6.0 Step 2 − Create a Project Folder and Open in VSCode The root folder of project can be named as test-app. Open the folder using visual studio code editor by using the instructions below − C:UsersAdmin>mkdir test-app C:UsersAdmin>cd test-app C:UsersAdmintest-app>code. Step 3 − Create package.json and Install the Dependencies Create a package.json file which will contain all the dependencies of the GraphQL server application. { “name”: “hello-world-server”, “private”: true, “scripts”: { “start”: “nodemon –ignore data/ server.js” }, “dependencies”: { “apollo-server-express”: “^1.4.0”, “body-parser”: “^1.18.3”, “cors”: “^2.8.4”, “express”: “^4.16.3”, “graphql”: “^0.13.2”, “graphql-tools”: “^3.1.1” }, “devDependencies”: { “nodemon”: “1.17.1” } } Install the dependencies by using the command as given below − C:UsersAdmintest-app>npm install Step 4 − Create Flat File Database in Data Folder In this step, we use flat files to store and retrieve data. Create a folder data and add two files students.json and colleges.json. Following is the colleges.json file − [ { “id”: “col-101”, “name”: “AMU”, “location”: “Uttar Pradesh”, “rating”:5.0 }, { “id”: “col-102”, “name”: “CUSAT”, “location”: “Kerala”, “rating”:4.5 } ] Following is the students.json file − [ { “id”: “S1001”, “firstName”:”Mohtashim”, “lastName”:”Mohammad”, “email”: “[email protected]”, “password”: “pass123”, “collegeId”: “col-102” }, { “id”: “S1002”, “email”: “[email protected]”, “firstName”:”Kannan”, “lastName”:”Sudhakaran”, “password”: “pass123”, “collegeId”: “col-101” }, { “id”: “S1003”, “email”: “[email protected]”, “firstName”:”Kiran”, “lastName”:”Panigrahi”, “password”: “pass123”, “collegeId”: “col-101″ } ] Step 5 − Create a Data Access Layer We need to create a datastore that loads the data folder contents. In this case, we need collection variables, students and colleges. Whenever the application needs data, it makes use of these collection variables. Create file db.js with in the project folder as follows − const { DataStore } = require(”notarealdb”); const store = new DataStore(”./data”); module.exports = { students:store.collection(”students”), colleges:store.collection(”colleges”) }; Step 6 − Create Schema File, schema.graphql Create a schema file in the current project folder and add the following contents − type Query { test: String } Step 7 − Create Resolver File, resolvers.js Create a resolver file in the current project folder and add the following contents − const Query = { test: () => ”Test Success, GraphQL server is up & running !!” } module.exports = {Query} Step 8 − Create Server.js and Configure GraphQL Create a server file and configure GraphQL as follows − const bodyParser = require(”body-parser”); const cors = require(”cors”); const express = require(”express”); const db = require(”./db”); const port = process.env.PORT || 9000; const app = express(); const fs = require(”fs”) const typeDefs = fs.readFileSync(”./schema.graphql”,{encoding:”utf-8”}) const resolvers = require(”./resolvers”) const {makeExecutableSchema} = require(”graphql-tools”) const schema = makeExecutableSchema({typeDefs, resolvers}) app.use(cors(), bodyParser.json()); const {graphiqlExpress,graphqlExpress} = require(”apollo-server-express”) app.use(”/graphql”,graphqlExpress({schema})) app.use(”/graphiql”,graphiqlExpress({endpointURL:”/graphql”})) app.listen( port, () => console.info( `Server started on port ${port}` ) ); Step 9 − Run the Application and Test with GraphiQL Verify the folder structure of project test-app as follows − test-app / –>package.json –>db.js –>data students.json colleges.json –>resolvers.js –>schema.graphql –>server.js Run the command npm start as given below − C:UsersAdmintest-app>npm start The server is running in 9000 port, so we can test the application using GraphiQL tool. Open the browser and enter the URL http://localhost:9000/graphiql. Type the following query in the editor − { Test } The response from the server is given below − { “data”: { “test”: “Test Success, GraphQL server is running !!” } } Print Page Previous Next Advertisements ”;
GraphQL – Architecture
GraphQL – Architecture ”; Previous Next GraphQL is a specification that describes the behavior of a GraphQL server. It is a set of guidelines on how requests and responses should be handled like supported protocols, format of the data that can be accepted by the server, format of the response returned by the server, etc. The request made by a client to the GraphQL server is called a Query. Another important concept of GraphQL is its transport layer agnostics. It can be used with any available network protocol like TCP, websocket or any other transport layer protocol. It is also neutral to databases, so you can use it with relational or NoSQL databases. GraphQL Server can be deployed by using any of the three methods listed below − GraphQL server with connected database GraphQL server that integrates existing systems Hybrid approach GraphQL Server with Connected Database This architecture has a GraphQL Server with an integrated database and can often be used with new projects. On the receipt of a Query, the server reads the request payload and fetches data from the database. This is called resolving the query. The response returned to the client adheres to the format specified in the official GraphQL specification. In the above diagram, GraphQL server and the database are integrated on a single node. The client (desktop/mobile) communicates with GraphQL server over HTTP. The server processes the request, fetches data from the database and returns it to the client. GraphQL Server Integrating Existing Systems This approach is helpful for companies which have legacy infrastructure and different APIs. GraphQL can be used to unify microservices, legacy infrastructure and third-party APIs in the existing system. In the above diagram, a GraphQL API acts as an interface between the client and the existing systems. Client applications communicate with the GraphQL server which in turn resolves the query. Hybrid Approach Finally, we can combine the above two approaches and build a GraphQL server. In this architecture, the GraphQL server will resolve any request that is received. It will either retrieve data from connected database or from the integrated API’s. This is represented in the below figure − Print Page Previous Next Advertisements ”;
GraphQL – Home
GraphQL Tutorial PDF Version Quick Guide Resources Job Search Discussion GraphQL is an open source server-side technology which was developed by Facebook to optimize RESTful API calls. It is an execution engine and a data query language. This tutorial will introduce you to the fundamental concepts of GraphQL including − Implement GraphQL API using Apollo server Test GraphQL API using GraphiQL Build ReactJS (with Apollo Client library) and jQuery client applications to consume the API Audience This tutorial is created for developers who have worked on JavaScript applications based on Client-Server architecture. After completing this tutorial, you will be able to build moderately complex GraphQL APIs for mobile and web applications. Prerequisites This course is based on NodeJs and Express. So, if you have a basic understanding of NodeJS, it will be easy to learn GraphQL. For frontend integration of GraphQL, we will be using ReactJs and Jquery. Since, illustrations in this tutorial uses EcmaScript 6 (ES6) syntax, knowledge in these areas can be helpful. Print Page Previous Next Advertisements ”;
GraphQL – Introduction
GraphQL – Introduction ”; Previous Next GraphQL is an open source server-side technology which was developed by Facebook to optimize RESTful API calls. It is an execution engine and a data query language. In this chapter, we discuss about the advantages of using GraphQL. Why GraphQL RESTful APIs follow clear and well-structured resource-oriented approach. However, when the data gets more complex, the routes get longer. Sometimes it is not possible to fetch data with a single request. This is where GraphQL comes handy. GraphQL structures data in the form of a graph with its powerful query syntax for traversing, retrieving, and modifying data. The following are advantages of using GraphQL query Language − Ask for what you want − and get it Send a GraphQL query to your API and get exactly what you need. GraphQL queries always return predictable results. Applications using GraphQL are fast and stable. Unlike Restful services, these applications can restrict data that should be fetched from the server. The following example will help you understand this better − Let us consider a business object Student with the attributes id, firstName, lastName and collegeName. Suppose a mobile application needs to fetch only the firstName and id. If we design a REST endpoint like /api/v1/students, it will end up fetching data for all the fields for a student object. This means, data is over fetched by the RESTful service. This problem can be solved by using GraphQL. Consider the GraphQL query given below − { students { id firstName } } This will return values only for the id and firstname fields. The query will not fetch values for other attributes of the student object. The response of the query illustrated above is as shown below − { “data”: { “students”: [ { “id”: “S1001”, “firstName”: “Mohtashim” }, { “id”: “S1002”, “firstName”: “Kannan” } ] } } Get many resources in a single request GraphQL queries help to smoothly retrieve associated business objects, while typical REST APIs require loading from multiple URLs. GraphQL APIs fetch all the data your application need in a single request. Applications using GraphQL can be quick even on slow mobile network connections. Let us consider one more business object, College which has the attributes: name and location. The Student business object has an association relationship with the College object. If we were to use a REST API in order to fetch the details of students and their college, we will end up making two requests to the server like /api/v1/students and /api/v1/colleges. This will lead to under fetching of data with each request. So mobile applications are forced to make multiple calls to the server to get the desired data. However, the mobile application can fetch details for both Student and College objects in a single request by using GraphQL. The following is a GraphQL query to fetch data − { students{ id firstName lastName college{ name location } } } The output of the above query contains exactly those fields we have requested for as shown below − { “data”: { “students”: [ { “id”: “S1001”, “firstName”: “Mohtashim”, “lastName”: “Mohammad”, “college”: { “name”: “CUSAT”, “location”: “Kerala” } }, { “id”: “S1002”, “firstName”: “Kannan”, “lastName”: “Sudhakaran”, “college”: { “name”: “AMU”, “location”: “Uttar Pradesh” } }, { “id”: “S1003”, “firstName”: “Kiran”, “lastName”: “Panigrahi”, “college”: { “name”: “AMU”, “location”: “Uttar Pradesh” } } ] } } Describe what’s possible with a type system GraphQL is strongly typed and the queries are based on fields and their associated data types. If there is type mismatch in a GraphQL query, server applications return clear and helpful error messages. This helps in smooth debugging and easy detection of bugs by client applications. GraphQL also provides client side libraries that can help in reducing explicit data conversion and parsing. An example of the Student and College data types is given below − type Query { students:[Student] } type Student { id:ID! firstName:String lastName:String fullName:String college:College } type College { id:ID! name:String location:String rating:Float students:[Student] } Move faster with powerful developer tools GraphQL provides rich developer tools for documentation and testing queries. GraphiQL is an excellent tool which generates documentation of the query and its schema. It also gives a query editor to test GraphQL APIs and intelligent code completion capability while building queries. Print Page Previous Next Advertisements ”;