GraphQL – Discussion

Discuss GraphQL ”; 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. 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 Print Page Previous Next Advertisements ”;

GraphQL – Useful Resources

GraphQL – Useful Resources ”; Previous Next The following resources contain additional information on GraphQL. Please use them to get more in-depth knowledge on this. Useful Video Courses NestJs Course: Modern ways to build APIs with Typescript and NestJs Most Popular 42 Lectures 7 hours Haider Malik More Detail Creating GraphQL APIs with ASP.Net Core for Beginners 44 Lectures 3 hours Nilay Mehta More Detail GraphQL Course with .Net Core For Absolute Beginners 54 Lectures 3 hours Asfend Yar More Detail The GraphQL Apollo (with ReactJS and MongoDB) 17 Lectures 2 hours Mohd Raqif Warsi More Detail Adobe Experience Manager Developer Course – AEM 6.5.11 51 Lectures 5 hours Nikunj Jariwala More Detail Postman Rest API Testing- Complete Guide 25 Lectures 2 hours Anuja Jain More Detail Print Page Previous Next Advertisements ”;

GraphQL – Caching

GraphQL – Caching ”; Previous Next Caching is the process of storing data in a temporary storage area called cache. When you return to a page you”ve recently visited, the browser can get those files from the cache rather than the original server. This saves your time, and network from the burden of additional traffic. Client applications interacting with GraphQL are responsible for caching data at their end. One possible pattern for this is reserving a field, like id, to be a globally unique identifier. InMemory Cache InMemoryCache is a normalized data store commonly used in GraphQL client applications without use of other library like Redux. The sample code to use InMemoryCache with ApolloClient is given below − import {ApolloClient, HttpLink, InMemoryCache} from ”apollo-boost” const cache = new InMemoryCache(); const client = new ApolloClient({ link: new HttpLink(), cache }); The InMemoryCache constructor takes an optional config object with properties to customize your cache. Sr.No. Parameter & Description 1 addTypename A boolean to determine whether to add __typename to the document (default: true) 2 dataIdFromObject A function that takes a data object and returns a unique identifier to be used when normalizing the data in the store 3 fragmentMatcher By default, the InMemoryCache uses a heuristic fragment matcher 4 cacheRedirects A map of functions to redirect a query to another entry in the cache before a request takes place. Illustration We will create a single page application in ReactJS with two tabs – one for the home tab and another for students. The students tab will load data from a GraphQL server API. The application will query for students data when the user navigates from the home tab to the students tab. The resulting data will be cached by the application. We will also query the server time using getTime field to verify if the page is cached. If data is returned from the cache, the page will display the time of very first request sent to the server. If the data is a result of a fresh request made to the sever, it will always show the latest time from server. Setting up the Server Following are the steps for setting up the server − Step 1 − Download and Install Required Dependencies for the Project Create a folder cache-server-app. Change your directory to cache-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 cache-server-app and add the following code − type Query { students:[Student] getTime:String } type Student { id:ID! firstName:String lastName:String fullName:String } Step 3 − Add Resolvers Create a file resolvers.js in the project folder, and add the following code − const db = require(”./db”) const Query = { students:() => db.students.list(), getTime:() => { const today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); return `${h}:${m}:${s}`; } } module.exports = {Query} 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 will use GraphiQL as a client to test the application. Open browser and enter the URL http://localhost:9000/graphiql. Type the following query in the editor − { getTime students { id firstName } } The sample response shows the students names and the server time. { “data”: { “getTime”: “22:18:42”, “students”: [ { “id”: “S1001”, “firstName”: “Mohtashim” }, { “id”: “S1002”, “firstName”: “Kannan” }, { “id”: “S1003”, “firstName”: “Kiran” } ] } } Setting up the ReactJS Client Open a new terminal for client. The server terminal should be kept running before executing the client application. React application will be running on port number 3000 and server application on port number 9000. Step 1 − Create a React Application In the client terminal, type the following command − npx create-react-app hello-world-client This will install everything needed for a typical react application. The npx utility and create-react-app tools create a project with name hello-world-client. Once the installation is completed, open the project in VSCode. Install router modules for react using following command – npm install react-router-dom. Step 2 − Start hello-world-client Change the current folder path in the terminal to hello-world-client. Type npm start to launch the project. This will run a development server at port 3000 and will automatically open the browser and load the index page. This is shown in the screenshot given below − Step 3 − Install Apollo Client Libraries To install an Apollo Client, open a new terminal and be in current project folder path. Type the following command − npm install apollo-boost graphql This will download the graphql libraries for client side and also the Apollo Boost package. We can cross verify this by typing npm view apollo-boost dependencies. This will have many dependencies as shown below − { ”apollo-cache”: ”^1.1.15”, ”apollo-cache-inmemory”: ”^1.2.8”, ”apollo-client”: ”^2.4.0”, ”apollo-link”: ”^1.0.6”, ”apollo-link-error”: ”^1.0.3”, ”apollo-link-http”: ”^1.3.1”, ”apollo-link-state”: ”^0.4.0”, ”graphql-tag”: ”^2.4.2” } We can clearly see that apollo-client library is installed. Step 4 − Modify the App Component in index.js File For a simple react application, you only need to keep the index.js in src folder and index.html in public folder; all other files that are auto generated can be removed. The directory structure is given below − hello-world-client / –>node_modules –>public index.html –>src index.js students.js –>package.json Add an additional file students.js which will contain Students Component. Student details are fetched through the Student Component. In the App Component, we are using a HashRouter. Following is the index.js in react application − import React, {Component} from ”react”; import ReactDOM from ”react-dom”; import {HashRouter, Route, Link} from ”react-router-dom” //components import Students from ”./students” class App extends Component { render() { return( <div><h1>Home !!</h1> <h2>Welcome to React Application !! </h2> </div> ) } } function getTime() { var d = new Date(); return d.getHours()+”:”+d.getMinutes()+”:”+d.getSeconds() } const routes = <HashRouter> <div> <h4>Time from react app:{getTime()}</h4> <header> <h1> <Link to=”/”>Home</Link>  <Link to = “/students”>Students</Link>  </h1> </header>

GraphQL – Example

GraphQL – Example ”; Previous Next In this chapter, we will create a simple API that returns a greeting message, HelloWorld, and access it using GraphiQL. Example This example is based on NodeJS, Express and Apollo server. We will learn to put all the concepts together with the following steps − Step 1 − Setting up Express ExpressJS is a web application framework that helps to build websites and web applications. In this example, we will build a GraphQL API on top of the Express framework. Next step is to create a folder hello-world-server and navigate to the same folder from the terminal. Add package.json, and give a name to the package. Since this package is only used internally, we can declare it private. { “name”:”hello-world-server”, “private”:true } Install the dependencies for Express server as shown below − C:UsersAdminhello-world-server>npm install express body-parser cors body-parser is a middleware package which helps Express to handle HTTP Post requests efficiently. cors is another middleware package that handles cross-origin resource sharing. Create a server.js file within the project folder and type the following in it − const bodyParser = require(”body-parser”) const cors = require(”cors”) const express = require(”express”) const port = process.env.PORT|| 9000 const app = express() //register middleware app.use(bodyParser.json() , cors()) app.listen(port, () => console.log(`server is up and running at ${port}`) To verify if the Express server is up and running, execute the following code in the terminal window − C:UsersAdminhello-world-server>node server.js The following output is displayed in the server console. This shows that the express server is running on port 9000. server is up and running at 9000 If you open the browser and type http://localhost:9000, you will get the following screen − To stop the server, press Ctrl + C. Step 2 − Install GraphQL and Apollo Server Now that Express is configured, the next step is to download the following GraphQL dependencies − graphql graphql-tools apollo-server-express@1 We shall use Apollo server v1.0 as it is a stable release. Type the following commands to install these dependencies − C:UsersAdminhello-world-server>npm install graphql graphql-tools apollo-server-express@1 We can verify if these dependencies are installed successfully by checking the package.json file that we created previously. { “name”: “hello-world-server”, “private”: true, “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″ } } Step 3 − Define the Schema A GraphQL schema defines what kind of object can be fetched from a service, and what fields it has. The schema can be defined using GraphQL Schema Definition Language. Now, add the following code snippet in the server.js file − // Adding Type Definitions const typeDefinition = ` type Query { greeting: String } Here, the query contains a greeting attribute that returns a string value. Step 4 − Create a Resolver The first step in creating a resolver is to add some code to process the request for greeting field. This is specified in a resolver. The structure of the resolver function must match the schema. Add the following code snippet in the server.js file. // Adding resolver const resolverObject = { Query : { greeting: () => ”Hello GraphQL From TutorialsPoint !!” } } The second step is to bind the schema and resolver using makeExecutableSchema. This function is pre-defined in the graphql-tools module. Add the following code snippet in the server.js file. const {makeExecutableSchema} = require(”graphql-tools”) const schema = makeExecutableSchema({typeDefs:typeDefinition, resolvers:resolverObject}) Step 5 − Define Routes to Fetch Data from ReactJS/GraphiQL Application Add the following code snippet in the server.js file − const {graphqlExpress, graphiqlExpress} = require(”apollo-server-express”) //create routes for graphql and graphiql app.use(”/graphql”,graphqlExpress({schema})) app.use(”/graphiql”,graphiqlExpress({endpointURL:”/graphql”})) The graphqlExpress function helps to register the route http://localhost:9000/graphql. The ReactJS application can use this endpoint to query data. Similarly, the graphqliExpress function helps to register the route http://localhost:9000/graphiql. This will be used by the GraphiQL browser client to test the API. The complete server.js code is as given below − const bodyParser = require(”body-parser”) const cors = require(”cors”) const express = require(”express”) const port = process.env.PORT||9000 const app = express() app.use(bodyParser.json() , cors()) const typeDefinition = ` type Query { greeting: String }` const resolverObject = { Query : { greeting: () => ”Hello GraphQL From TutorialsPoint !!” } } const {makeExecutableSchema} = require(”graphql-tools”) const schema = makeExecutableSchema({typeDefs:typeDefinition, resolvers:resolverObject}) const {graphqlExpress,graphiqlExpress} = require(”apollo-server-express”) app.use(”/graphql”,graphqlExpress({schema})) app.use(”/graphiql”,graphiqlExpress({endpointURL:”/graphql”})) app.listen(port, () => console.log(`server is up and running ${port}`)) Step 6 − Start the Application Execute server.js using Node.js as follows − C:UsersAdminhello-world-server>node server.js Step 7 − Test the GraphQL API Open the browser and type http://localhost:9000/graphiql. In the query tab of GraphiQL, enter the following − { greeting } The response from the server is given below − { “data”: { “greeting”: “Hello GraphQL From TutorialsPoint !!” } } The following image illustrates the response − Note − Please ensure that Apollo Server Version 1.0 is used. Print Page Previous Next Advertisements ”;

GraphQL – Apollo Client

GraphQL – Apollo Client ”; Previous Next We have used Apollo Server to build graphql specification on server side. It is quick and easy to build production ready GraphQL server. Now let us understand the client side. Apollo Client is the best way to use GraphQL to build client applications. The client is designed to help developer quickly build a UI that fetches data with GraphQL and can be used with any JavaScript front-end. Apollo Client supports the following platforms − Sr.No. Platform & Framework 1 Javascript React,Angular,Vue,Meteor,Ember 2 WebComponents Polymer, lit-apollo 3 Native Mobile Native Android with Java, Native iOS with Swift Caching is one of the major features of Apollo Client. apollo-boost is a convenience package which brings in a bunch of other dependencies. Illustration Let us see how to use Apollo Client to build client applications using the following steps − Setting up Server We have to follow the below steps for setting up a server − Step 1 − Download and Install Required Dependencies for the Project Create a folder apollo-server-app. Change your directory to apollo-server-app from the terminal. Then, follow steps 3 to 5 explained in the Environment Setup chapter. Step 2 − Create a Schema Add schema.graphql file in the project folder apollo-server-app and add the following code − type Query { students:[Student] } type Student { id:ID! firstName:String lastName:String college:College } type College { id:ID! name:String location:String rating:Float } Step 3 − Add Resolvers Create a file resolvers.js in the project folder and add the following code − const db = require(”./db”) const Query = { //resolver function for students returns list students:() => db.students.list(), } const Student = { college:(root) => { return db.colleges.get(root.collegeId); } } 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 will 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 firstName college{ name } } } The response for the query is as given below − { “data”: { “students”: [ { “id”: “S1001”, “firstName”: “Mohtashim”, “college”: { “name”: “CUSAT” } }, { “id”: “S1002”, “firstName”: “Kannan”, “college”: { “name”: “AMU” } }, { “id”: “S1003”, “firstName”: “Kiran”, “college”: { “name”: “AMU” } } ] } } Setting up the Client Open a new terminal for client. The server terminal should be kept running before executing the client application. React application will be running on port number 3000 and server application on port number 9000. Step 1 − Create a React Application In the client terminal, type the following command − npx create-react-app hello-world-client This will install everything needed for a typical react application. The npx utility and create-react-app tool create a project with name hello-world-client. Once the installation is completed, open the project in VSCode. Step 2 − Start hello-world-client Change the current folder path in the terminal to hello-world-client. Type npm start to launch the project. This will run a development server at port 3000 and will automatically open the browser and load the index page. This is shown in the screenshot given below − Step 3 − Install Apollo Client Libraries To install an Apollo Client, open a new terminal and be in current project folder path. Type the following command − npm install apollo-boost graphql This will download the graphql libraries for client side and also the Apollo Boost package. We can cross check this by typing npm view in apollo-boost dependencies. This will have many dependencies as shown below − { ”apollo-cache”: ”^1.1.15”, ”apollo-cache-inmemory”: ”^1.2.8”, ”apollo-client”: ”^2.4.0”, ”apollo-link”: ”^1.0.6”, ”apollo-link-error”: ”^1.0.3”, ”apollo-link-http”: ”^1.3.1”, ”apollo-link-state”: ”^0.4.0”, ”graphql-tag”: ”^2.4.2” } We can clearly see that Apollo-Client library is installed. Step 4 − Modify the App Component in index.js File With Apollo Client, we can directly call server without the use of fetch API. Also, the queries and mutations should not be embedded in a string made with back tick notation. This is because, the gql function directly parses the queries. This means, a programmer can directly write queries in the same way when writing queries in GraphiQL tool. gql is a tag function which will parse the template string written in back tick notation to graphql query object. The Apollo Client query method returns a promise. Following code snippet shows how to import Apollo Client − import {ApolloClient, HttpLink, InMemoryCache} from ”apollo-boost” const endPointUrl = ”http://localhost:9000/graphql” const client = new ApolloClient({ link: new HttpLink({uri:endPointUrl}), cache:new InMemoryCache() }); In the previous chapter, we discussed how to use fetch API for HTTP requests. The following code shows how to use gql function. The loadStudentsAsync function uses graphql client to query the server. async function loadStudentsAsync() { const query = gql` { students{ id firstName lastName college{ name } } }` const {data} = await client.query({query}) ; return data.students; } You only need to keep the index.js in src folder and index.html in public folder; all other files that are auto generated can be removed. The directory structure is given below − hello-world-client / –>node_modules –>public index.html –>src index.js –>package.json Following is the index.js in react application − import React, {Component} from ”react”; import ReactDOM from ”react-dom”; // apollo client import {ApolloClient, HttpLink, InMemoryCache} from ”apollo-boost” import gql from ”graphql-tag” const endPointUrl = ”http://localhost:9000/graphql” const client = new ApolloClient({ link: new HttpLink({uri:endPointUrl}), cache:new InMemoryCache() }); async function loadStudentsAsync() { const query = gql` { students{ id firstName lastName college{ name } } } ` const {data} = await client.query({query}) ; return data.students; } class App extends Component { constructor(props) { super(props); this.state = { students:[] } this.studentTemplate = []; } async loadStudents() { const studentData = await loadStudentsAsync(); this.setState({ students: studentData }) console.log(“loadStudents”) } render() { return( <div> <input type = “button” value = “loadStudents” onClick = {this.loadStudents.bind(this)}/> <div> <br/> <hr/> <table border = “3”> <thead> <tr> <td>First Name</td> <td>Last Name</td> <td>college Name</td> </tr> </thead> <tbody> { this.state.students.map(s => { return ( <tr key =

GraphQL – Authenticating Client

GraphQL – Authenticating Client ”; Previous Next Authentication is the process or action of verifying the identity of a user or a process. It is important that an application authenticates a user to ensure that the data is not available to an anonymous user. In this section, we will learn how to authenticate a GraphQL client. Express JWT In this example, we will use jQuery to create a client application. To authenticate requests, we will use express-jwt module on the server-side. The express-jwt module is a middleware that lets you authenticate HTTP requests using JWT tokens. JSON Web Token (JWT) is a long string that identifies the logged in user. Once the user logs in successfully, the server generates a JWT token. This token distinctly identifies a log. In other words, the token is a representation of user”s identity. So next time, when the client comes to the server, it has to present this token to get the required resources. The client can be either a mobile application or a web application. Illustration We will follow a step-wise procedure to understand this illustration. Setting up the Server Following are the steps for setting up the server − Step 1 − Download and Install Required Dependencies for the Project Create a folder auth-server-app. Change your directory to auth-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 auth-server-app and add the following code − type Query { greetingWithAuth:String } Step 3 − Add Resolvers Create a file resolvers.js in the project folder and add the following code − The resolver will verify if an authenticated user object is available in the context object of GraphQL. It will raise an exception if an authenticated user is not available. const db = require(”./db”) const Query = { greetingWithAuth:(root,args,context,info) => { //check if the context.user is null if (!context.user) { throw new Error(”Unauthorized”); } return “Hello from TutorialsPoint, welcome back : “+context.user.firstName; } } module.exports = {Query} Step 4 − Create Server.js File The authentication middleware authenticates callers using a JSON Web Token. The URL for authentication is http://localhost:9000/login. This is a post operation. The user has to submit his email and password which will be validated from the backend. If a valid token is generated using jwt.sign method, the client will have to send this in header for subsequent requests. If the token is valid, req.user will be set with the JSON object decoded to be used by later middleware for authorization and access control. The following code uses two modules − jsonwebtoken and express-jwt to authenticate requests − When the user clicks on the greet button, a request for the /graphql route is issued. If the user is not authenticated, he will be prompted to authenticate himself. The user is presented with a form that accepts email id and password. In our example, the /login route is responsible for authenticating the user. The /login route verifies if a match is found in the database for credentials provided by the user. If the credentials are invalid, a HTTP 401 exception is returned to the user. If the credentials are valid, a token is generated by the server. This token is sent as a part of response to the user. This is done by the jwt.sign function. const expressJwt = require(”express-jwt”); const jwt = require(”jsonwebtoken”); //private key const jwtSecret = Buffer.from(”Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt”, ”base64”); app.post(”/login”, (req, res) => { const {email, password} = req.body; //check database const user = db.students.list().find((user) => user.email === email); if (!(user && user.password === password)) { res.sendStatus(401); return; } //generate a token based on private key, token doesn”t have an expiry const token = jwt.sign({sub: user.id}, jwtSecret); res.send({token}); }); For every request, the app.use() function will be called. This in turn will invoke the expressJWT middleware. This middleware will decode the JSON Web Token. The user id stored in the token will be retrieved and stored as a property user in the request object. //decodes the JWT and stores in request object app.use(expressJwt({ secret: jwtSecret, credentialsRequired: false })); To make available the user property within GraphQL context, this property is assigned to the context object as shown below − //Make req.user available to GraphQL context app.use(”/graphql”, graphqlExpress((req) => ({ schema, context: {user: req.user &&apm; db.students.get(req.user.sub)} }))); Create server.js in current folder path. The complete server.js file is as follows − const bodyParser = require(”body-parser”); const cors = require(”cors”); const express = require(”express”); const expressJwt = require(”express-jwt”); //auth const jwt = require(”jsonwebtoken”); //auth const db = require(”./db”); var port = process.env.PORT || 9000 const jwtSecret = Buffer.from(”Zn8Q5tyZ/G1MHltc4F/gTkVJMlrbKiZt”, ”base64”); 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(), expressJwt({ secret: jwtSecret, credentialsRequired: false })); const {graphiqlExpress,graphqlExpress} = require(”apollo-server-express”) app.use(”/graphql”, graphqlExpress((req) => ({ schema, context: {user: req.user && db.students.get(req.user.sub)} }))); app.use(”/graphiql”,graphiqlExpress({endpointURL:”/graphql”})) //authenticate students app.post(”/login”, (req, res) => { const email = req.body.email; const password = req.body.password; const user = db.students.list().find((user) => user.email === email); if (!(user && user.password === password)) { res.sendStatus(401); return; } const token = jwt.sign({sub: user.id}, jwtSecret); res.send({token}); }); app.listen(port, () => console.info(`Server started on port ${port}`)); Step 5 − Run the Application 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 − { greetingWithAuth } In the below response, we got an error as we are not authenticated user. { “data”: { “greetingWithAuth”: null }, “errors”: [ { “message”: “Unauthorized”, “locations”: [ { “line”: 2, “column”: 3 } ], “path”: [ “greetingWithAuth” ] } ] } In the next section, let us create a client application to authenticate. Setting up the JQuery Client In the client application, a greet button is provided which will invoke the schema greetingWithAuth. If you click the button without login, it will give you the error message as below − Once you log in with a user available in database, the

GraphQL – Quick Guide

GraphQL – Quick Guide ”; Previous Next GraphQL – Introduction 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. GraphQL – Environment Setup 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

GraphQL – React Integration

GraphQL – React Integration ”; Previous Next React is a Javascript library for building user interfaces. This chapter explains how one can integrate GraphQL with a React application. Illustration The quickest way to set up a react project is by using the Create React App tool. In the subsequent sections, we will learn how to set up both the Server and the Client. Setting up the Server For setting up the Server, follow the below steps − Step 1 − Download and Install Required Dependencies for the Project Create a folder react-server-app. Change your directory to react-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 react-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 the 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 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 given below − { “data”: { “greeting”: “Hello GraphQL From TutorialsPoint !!”, “sayHello”: “Hi Mohtashim GraphQL server says Hello to you!!” } } Setting up the Client Open a new terminal for client. The server terminal should be kept running before executing the client application. React application will be running on port number 3000 and server application on port number 9000. Step 1 − Create a React Project hello-world-client In the client terminal, type the following command − npx create-react-app hello-world-client This will install everything needed for a typical react application. The npx utility and create-react-app tool create a project with name hello-world-client. Once the installation is completed, open the project in VSCode. Step 2 − Start hello-world-client Change the current folder path in the terminal to hello-world-client. Type npm start to launch the project. This will run a development server at port 3000 and will automatically open the browser and load the index page. This is shown in the screenshot given below − Step 3 − Modify the App Component In the App.js inside src folder, add two functions, one to load greeting and another to load sayHello messages. Following is the loadGreeting function which sends GraphQL query for greeting. async function loadGreeting() { const response = await fetch(”http://localhost:9000/graphql”, { method:”POST”, headers:{”content-type”:”application/json”}, body:JSON.stringify({query:”{greeting}”}) }) const rsponseBody = await response.json(); return rsponseBody.data.greeting; console.log(“end of function”) } Following is the loadSayhello function which sends GraphQL query for sayHello − async function loadSayhello(name) { const response = await fetch(”http://localhost:9000/graphql”, { method:”POST”, headers:{”content-type”:”application/json”}, body:JSON.stringify({query:`{sayHello(name:”${name}”)}`}) }) } The complete App.js file is shown below − import React, { Component } from ”react”; import logo from ”./logo.svg”; import ”./App.css”; async function loadGreeting() { const response = await fetch(”http://localhost:9000/graphql”, { method:”POST”, headers:{”content-type”:”application/json”}, body:JSON.stringify({query:”{greeting}”}) }) const rsponseBody = await response.json(); return rsponseBody.data.greeting; console.log(“end of function”) } async function loadSayhello(name) { const response = await fetch(”http://localhost:9000/graphql”, { method:”POST”, headers:{”content-type”:”application/json”}, body:JSON.stringify({query:`{sayHello(name:”${name}”)}`}) }) const rsponseBody = await response.json(); return rsponseBody.data.sayHello; } class App extends Component { constructor(props) { super(props); this.state = {greetingMessage:””,sayHelloMessage:””,userName:””} this.updateName = this.updateName.bind(this); this.showSayHelloMessage = this.showSayHelloMessage.bind(this); this.showGreeting = this.showGreeting.bind(this); } showGreeting() { loadGreeting().then(g => this.setState({greetingMessage:g+” :-)”})) } showSayHelloMessage() { const name = this.state.userName; console.log(name) loadSayhello(name).then(m => this.setState({sayHelloMessage:m})) } updateName(event) { this.setState({userName:event.target.value}) } render() { return ( <div className = “App”> <header className = “App-header”> <img src = {logo} className = “App-logo” alt = “logo” /> <h1 className = “App-title”>Welcome to React</h1> </header> <br/><br/> <section> <button id = “btnGreet” onClick = {this.showGreeting}>Greet</button> <br/> <br/> <div id = “greetingDiv”> <h1>{this.state.greetingMessage}</h1> </div> </section> <hr/> <section> Enter a name:<input id = “txtName” type = “text” onChange = {this.updateName} value = {this.state.userName}/> <button id = “btnSayhello” onClick = {this.showSayHelloMessage}>SayHello</button> <br/> user name is:{this.state.userName} <br/> <div id = “SayhelloDiv”> <h1>{this.state.sayHelloMessage}</h1> </div> </section> </div> ); } } export default App; Once both the applications are running, click on the greet button. Next, enter a name in the textbox and click on sayHello button. The output will be as given below − Print Page Previous Next Advertisements ”;

GraphQL – Validation

GraphQL – Validation ”; Previous Next While adding or modifying data, it is important to validate the user input. For example, we may need to ensure that the value of a field is always not null. We can use ! (non-nullable) type marker in GraphQL to perform such validation. The syntax for using the ! type marker is as given below − type TypeName { field1:String!, field2:String!, field3:Int! } The above syntax ensures that all the fields are not null. If we want to implement additional rules like checking a string”s length or checking if a number is within a given range, we can define custom validators. The custom validation logic will be a part of the resolver function. Let us understand this with the help of an example. Illustration – Implementing Custom Validators Let us create a signup form with basic validation. The form will have email, firstname and password fields. Step 1 − Download and Install Required Dependencies for the Project Create a folder named validation-app. Change the directory to validation-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 validation-app and add the following code − type Query { greeting:String } type Mutation { signUp(input:SignUpInput):String } input SignUpInput { email:String!, password:String!, firstName:String! } Note − We can use the input type SignUpInput to reduce the number of parameters in signUp function. So, signUp function takes only one parameter of type SignUpInput. Step 3 − Create Resolvers Create a file resolvers.js in the project folder and add the following code − const Query = { greeting:() => “Hello” } const Mutation ={ signUp:(root,args,context,info) => { const {email,firstName,password} = args.input; const emailExpression = /^(([^<>()[]\.,;:s@”]+(.[^<>()[]\.,;:s@”]+)*)|(“.+”))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/; const isValidEmail = emailExpression.test(String(email).toLowerCase()) if(!isValidEmail) throw new Error(“email not in proper format”) if(firstName.length > 15) throw new Error(“firstName should be less than 15 characters”) if(password.length < 8 ) throw new Error(“password should be minimum 8 characters”) return “success”; } } module.exports = {Query,Mutation} The resolver function, signUp accepts parameters email, password and firstName. These will be passed through input variable so that it can be accessed through args.input. 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 will 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 − mutation doSignUp($input:SignUpInput) { signUp(input:$input) } Since input to signup function is a complex type, we need to use query variables in graphiql. For this, we need to first give a name to the query and call it doSignUp, the $input is a query variable. The following query variable must be entered in query variables tab of graphiql − { “input”:{ “email”: “abc@abc”, “firstName”: “kannan”, “password”: “pass@1234” } } The errors array contains the details of validation errors as shown below − { “data”: { “signUp”: null }, “errors”: [ { “message”: “email not in proper format”, “locations”: [ { “line”: 2, “column”: 4 } ], “path”: [ “signUp” ] } ] } We have to enter a proper input for each field as given below − { “input”:{ “email”: “[email protected]”, “firstName”: “kannan”, “password”: “pass@1234” } } The response is as follows − { “data”: { “signUp”: “success” } } Here, in the below query, we are not assigning any password. { “input”:{ “email”: “[email protected]”, “firstName”: “kannan” } } If a required field is not provided, then qraphql server will display the following error − { “errors”: [ { “message”: “Variable “$input” got invalid value {“email”:”[email protected]”,”firstName”:”kannan”}; Field value.password of required type String! was not provided.”, “locations”: [ { “line”: 1, “column”: 19 } ] } ] } Print Page Previous Next Advertisements ”;

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