![]() |
GraphQL is an application layer for querying and mutating data in APIs built on the concept of a type system that you define for the data with which your application is built. GraphQL API differs from the traditional REST API as it makes client’s queries efficient and flexible allowing them to ask for the exact data they need. In this article, we will learn Execution in GraphQL with their working in details. Execution in GraphQL
Prerequisites
How Execution Works in GraphQL
Step-by-Step ExecutionStep 1: Set Up the Environment1.1 Install Node.js and NPMEnsure we have Node.js and NPM installed. we can download and install them from the official Node.js website. Verify the installation by running: node -v 1.2 Create a Project DirectoryCreate a new directory for your project and navigate into it: mkdir graphql-demo 1.3 Initialize a Node.js ProjectInitialize a new Node.js project with default settings: npm init -y
Output: ![]() 1.4 Install Dependencies Install the necessary dependencies, including Apollo Server and GraphQL: npm install apollo-server graphql
Step 2: Define the SchemaCreate a file named schema.js to define our GraphQL schema. schema.js:const { gql } = require('apollo-server'); Step 3: Write ResolversCreate a file named resolvers.js to define our resolvers. resolvers.js:const users = [ Step 4: Set Up the ServerCreate a file named index.js to set up and start our Apollo Server. index.js:const { ApolloServer } = require('apollo-server'); Step 5: Run the ServerStart GraphQL server, using the following command: node index.js
We should see a message indicating that your server is running: ![]() Step 6: Execute Queries6.1 Access GraphQL PlaygroundOpen a web browser and navigate to http://localhost:4000/. This will open the Apollo Server’s GraphQL Playground, where you can write and execute queries and mutations. ![]() 6.2 Execute a QueryIn the GraphQL Playground, enter the following query to fetch all users: query { Output![]() 6.3 Execute a MutationTo create a new user, enter the following mutation in the GraphQL Playground: mutation { Output: ![]() ConclusionOverall, Execution in GraphQL involves parsing the query string into an Abstract Syntax Tree (AST), validating it against the schema, and executing it by resolving each field with its corresponding resolver function. Resolver functions fetch the data for their fields, populating a result object that mirrors the query structure. |
Reffered: https://www.geeksforgeeks.org
GraphQL |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 16 |