GraphQL Basics
Table of Contents
This tutorial will introduce what is GraphQL, where it will be used, a simple complete sample project, common usage code.
Introduction
GraphQL is a query language and runtime for APIs that enables clients to request only the data they need, supports real-time updates through subscriptions, and can be used in a variety of contexts including web and mobile development.
- GraphQL is a query language for APIs that was created by Facebook in 2012 and released as an open-source project in 2015.
- With GraphQL, clients can specify exactly what data they need and receive only that data in response, rather than receiving all available data and having to parse it on the client side.
- GraphQL operates over a single endpoint, unlike REST APIs which typically have multiple endpoints for different resources.
- GraphQL uses a type system to define the schema of the data, which helps to ensure that the data being requested and returned is valid and consistent.
- GraphQL supports real-time updates through subscriptions, allowing clients to receive updates as soon as they occur rather than polling the server for changes.
- GraphQL can be used with a variety of programming languages and frameworks, and there are many tools and libraries available to help with development.
Basic example project
- Create a new directory for your project and navigate into it:
mkdir graphql-demo
cd graphql-demo
- Initialize a new Node.js project using npm:
npm init -y
- Install the required packages (express, express-graphql, and graphql) using npm:
npm install express express-graphql graphql
- Create a new file called index.js in your project directory and copy the following code into it.
// Import required packages
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
// Define the GraphQL schema
const schema = buildSchema(`
type Query {
hello: String
}
`);
// Define the resolvers
const root = {
hello: () => 'Hello, world!'
};
// Create the express app and attach the GraphQL middleware
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true // enable GraphiQL UI for testing
}));
// Start the server
app.listen(3000, () => {
console.log('GraphQL server running at http://localhost:3000/graphql');
});
- Run the server by executing the index.js file using Node.js:
node index.js
This should start the server and output the following message:
GraphQL server running at http://localhost:3000/graphql
You can then open your web browser and navigate to http://localhost:3000/graphql to access the GraphiQL UI and test the server.
Common usage example code
- Query with arguments:
query {
user(id: 1) {
name
email
}
}
This query requests the name and email fields for the user with id equal to 1. The server would need to have a resolver that handles this query and retrieves the user data based on the provided id.
- Nested query:
query {
user(id: 1) {
name
posts {
title
body
}
}
}
This query requests the name field for the user with id equal to 1, as well as the title and body fields for all posts associated with that user. The server would need to have resolvers that handle both the user and post queries and resolve the nested relationship between them.
- Mutation:
mutation {
createUser(name: "Alice", email: "alice@example.com") {
id
name
email
}
}
This mutation creates a new user with the provided name and email fields and returns the id, name, and email fields for the created user. The server would need to have a resolver that handles this mutation and adds the new user data to the appropriate data source.
- Subscription:
subscription {
newPost {
id
title
body
}
}
This subscription requests real-time updates for new posts as they are added to the server. The server would need to have a resolver that handles this subscription and sends updates to any subscribed clients as new posts are created.