GraphQL InstallationLet's start with GraphQL.js installation. You must have the following things before going to start.
There are two ways to execute GraphQL queries:
Execute GraphQL query with a command-line toolHere, we are not using any language features that require transpilation, but we will use some ES6 features like Promises, classes, and fat arrow functions, etc.
How to write the code?There are three important components for GraphQL application. i.e. schema, query, and resolver. When we write a query for the GraphQL server, then to handle GraphQL queries, we need a schema. The schema is used to define the Query type. We also require an API root with a function called a "resolver" for each API endpoint. Let's make an API to simple return "Hello World". Create a server.js file in the current folder where node.js is installed and write the following code: Now, run this using the following command: Here, you can see the GraphQL response printed as This is a simple GraphQL query that you executed on command prompt without using a server. Run an Express GraphQL Server to execute queryThe easiest way to run a GraphQL API server is to use Express. Express is a popular web application framework for Node.js. If you have not installed Express yet, first install Express by using the following command See this link for more information: https://www.javatpoint.com/install-expressjs You have to install two additional dependencies by using the following command: How to write the code?Modify the "server.js" file with the following code to make an API server rather than a script that runs a single query. Here, we use the 'express' module to run a webserver, and instead of executing a query directly with the graphql function, we can use the express-graphql library to mount a GraphQL API server on the "/graphql" HTTP endpoint Now, run the GraphQL server by using the following command: The GraphQL API server is running now. Open http://localhost:4000/graphql on a web browser. Here, you can see that how to run a GraphQL server and how to use the GraphiQL interface to issue queries.
Next TopicGraphQL Architecture
|