Execution in GraphQL
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
- Execution in GraphQL involves taking a query string, parsing it into an Abstract Syntax Tree (AST) and validating it against the schema and then 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.
Prerequisites
- GraphQL Schema: GraphQL Schema Describes the shape of the data, types, queries, mutations, and subscriptions are all outlined here.
- GraphQL Query Language: GraphQL Query Language Fundamentals of using GraphQL with an emphasis on creating queries and mutations.
- JavaScript/TypeScript: You should have a basic understanding of programming in JavaScript or TypeScript since many GraphQL servers are written in JavaScript and some in TypeScript.
- Node. js: Familiarity with Node. js as it is standard for constructing GraphQL servers.
- Apollo Server: An open-source free GraphQL server that will allow you to run GraphQL queries.
How Execution Works in GraphQL
- Parsing: The query string is then represented by an abstract syntax trees (AST).
- Validation: The query constructed in the AST is checked and validated against the schema to make sure that it is in the proper format.
- Execution: The validated query is then used to send back to the resolvers in order to request the desired information.
Step-by-Step Execution
Step 1: Set Up the Environment
1.1 Install Node.js and NPM
Ensure 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
npm -v
1.2 Create a Project Directory
Create a new directory for your project and navigate into it:
mkdir graphql-demo
cd graphql-demo
1.3 Initialize a Node.js Project
Initialize 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 Schema
Create a file named schema.js to define our GraphQL schema.
schema.js:
const { gql } = require('apollo-server');
const typeDefs = gql`
type Query {
hello: String
user(id: ID!): User
users: [User]
}
type Mutation {
createUser(name: String!, age: Int!): User
}
type User {
id: ID!
name: String
age: Int
}
`;
module.exports = typeDefs;
Step 3: Write Resolvers
Create a file named resolvers.js to define our resolvers.
resolvers.js:
const users = [
{ id: '1', name: 'John Doe', age: 25 },
{ id: '2', name: 'Jane Doe', age: 28 },
];
const resolvers = {
Query: {
hello: () => 'Hello, world!',
user: (parent, args) => users.find(user => user.id === args.id),
users: () => users,
},
Mutation: {
createUser: (parent, args) => {
const newUser = { id: String(users.length + 1), ...args };
users.push(newUser);
return newUser;
},
},
};
module.exports = resolvers;
Step 4: Set Up the Server
Create a file named index.js to set up and start our Apollo Server.
index.js:
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(`? Server ready at ${url}`);
});
Step 5: Run the Server
Start GraphQL server, using the following command:
node index.js
We should see a message indicating that your server is running:
Step 6: Execute Queries
6.1 Access GraphQL Playground
Open 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 Query
In the GraphQL Playground, enter the following query to fetch all users:
query {
users {
id
name
age
}
}
Output
6.3 Execute a Mutation
To create a new user, enter the following mutation in the GraphQL Playground:
mutation {
createUser(name: "Alice", age: 30) {
id
name
age
}
}
Output:
Conclusion
Overall, 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.