Basics of GraphQL: A Beginner’s Guide with Express

How to use GraphQL with Express.js? Basics of GraphQL

Sandeep Singh (Full Stack Dev.)
7 min readNov 5, 2023
Basics of GraphQL: A Beginner’s Guide with Express

GraphQL is a query language for your API and a runtime for executing those queries.

It was developed by Facebook and released as an open-source project. With GraphQL, clients request exactly the data they need, and nothing more, which makes it more efficient compared to traditional REST APIs.

GraphQL vs REST API requests

Understanding GraphQL

How Does GraphQL Differ from REST?

GraphQL differs from REST in several key ways:

  • Single Endpoint: In REST, you often have multiple endpoints for different resources. In GraphQL, there's a single endpoint for all data operations.
  • Client-Defined Queries: Clients define the shape and structure of the data they need. In REST, the server determines the structure of the response.
  • No Over-Fetching or Under-Fetching: Clients get only the data they request, eliminating over-fetching (getting more data than needed) and under-fetching (not getting enough data).
  • Versionless: No need for versioning, as clients ask for the specific fields they need.

When to Choose GraphQL

You should consider using GraphQL when:

  • Your application has complex data requirements.
  • You want to reduce the number of requests made by the client.
  • You need to support various devices and clients with different data needs.
  • You prefer a strongly typed API with introspection.

Anatomy of a GraphQL Query

A GraphQL query is the Schema through which you requested data is processed. It consists of fields, arguments, and types. Here’s a breakdown:

  • Types: In GraphQL, everything has a type. This includes the data you’re querying and the arguments you’re passing. Types are essential for defining the structure of your data and ensuring type safety.

Here’s a simple example of a GraphQL query that fetches a user’s name:

type Query {
hello: String
say(name: String): String
}

Resolvers: Bringing Your Data to Life

Resolvers are actual functions or business logic

GraphQL queries are only half of the story. To make these queries return actual data, we need resolvers.

Resolvers are functions that provide the values for the fields you requested in your query. They’re like the chefs in a restaurant who prepare your custom sandwich based on your order.

In the provided code example, we have two queries defined: hello and say. Let's dissect the say query and its resolver:

GraphQL Query

Here we have defined the schema in typedefs👇

`type Query {
hello: String
say(name: String): String
}`

Resolver

Here in Resolvers we have defines the actual business logic or function👇

resolvers: {
Query : {
hello: ()=> {
return "Hey I am a GraphQL server"
},

say:(_,{name}:{name:string})=> {
return `Hey ${name} I am a GraphQL server`
}

}

The say query takes an argument called name, and its resolver returns a personalized message. So, if you make the query say(name: "Alice"), the resolver will return the message "Hey Alice! I am a GraphQL server."

Mutations: Making Changes

While queries are used for fetching data, mutations are used for making changes to the data.

They’re like the actions you take in a restaurant, such as placing an order. In GraphQL, mutations allow you to create, update, or delete data. For example, you can create a mutation to add a new user to your system.

Setting Up a Basic GraphQL Server with Express

Now that we have a basic understanding of GraphQL, let’s set up a simple GraphQL server using Express. We’ll use the provided code example to get started.

How GraphQL flow works — Queries, resolvers, mutations

Step 1: Import Dependencies

import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import { expressMiddleware } from 'apollo-server-express4';

full source code is at the bottom👇

First, import the necessary dependencies. We’re using Express and Apollo Server to create our GraphQL server.

Step 2: Initialize the Server

const app = express();
const port = 3000;
app.use(express.json());

Next, initialize your Express app and set up the port for your server. We also need to enable JSON parsing for our app.

Step 3: Define the GraphQL Schema

const server = new ApolloServer({
typeDefs: `
type Query {
hello: String
say(name: String): String
}
`,
resolvers: {
Query : {
hello: ()=> {
return "Hey, I am a GraphQL server"
},

say:(_, {name})=> {
return `Hey ${name}! I am a GraphQL server`
}
}
}
})

full source code is at the bottom👇

Here, we define our GraphQL schema using the ApolloServer class. We specify the schema as a string with a Query type that includes the hello and say fields along with their resolvers.

Step 4: Start the Server

await server.start();

app.get('/', (req, res) => {
res.send('Server is up and running');
});
app.use('/graphql', expressMiddleware(server));
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Finally, we start the server and listen on the specified port (in this case, port 3000). We also set up a basic route at the root endpoint.

Full Source Code:

Github Repo Link: https://github.com/sandy088/Threads-backend-GraphQL

If you star the repo, it would make my day special😊

import express from 'express';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';

const app = express();
const port = 3000;
app.use(express.json());

const init = async () => {
//creating a GraphQL server
const server = new ApolloServer({
typeDefs: `
type Query {
hello: String
say(name: String): String
}
`, //schema as a string
resolvers: {
Query : {
hello: ()=> {
return "Hey I am a GraphQL server"
},

say:(_,{name}:{name:string})=> {
return `Hey ${name} I am a GraphQL server`
}



}
} // actual function which will be executed when a query is made
})

await server.start();

app.get('/', (req, res) => {
res.send('server is up and runnnigg');
});

app.use('/graphql', expressMiddleware(server))

app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
});
}

init()

Why Choose GraphQL?

So, why should you consider using GraphQL in your projects? The answer lies in its efficiency, flexibility, and ease of use.

GraphQL enables front-end developers to request precisely the data they need, reducing over-fetching and under-fetching.

It also simplifies versioning, as you can add new fields to your schema without breaking existing clients.

In summary, GraphQL provides a client-centric approach to data fetching, allowing for more efficient and dynamic interactions with your API. It’s a game-changer for modern web development.

How to Test?

go to your localhost:3000/graphql

you will see a GUI and you can test GraphQL queries

Video🎥 on this is coming within 2 days, where I have covered from basics to testing the GraphQL queries

Are You Looking to Host Your Node.js Servers? Discover the Perfect Solution!

Are you a beginner backend developer or a college student learning development? If so, I have something that could greatly benefit you. In my article on using Redis in Node.js server, I discovered the perfect hosting solution for your needs: Hostinger’s VPS Hosting Plan.

Hostinger’s VPS Hosting plan is super cheap, I really recommend it for beginners.

With Hostinger’s VPS hosting plan, you can supercharge your Node.js server’s performance and reliability. Enjoy lightning-fast load times, top-notch security features, and the ability to seamlessly scale your Redis-powered applications.

If you’re serious about taking your development skills to the next level, I highly recommend checking out Hostinger’s VPS hosting plan. It’s the perfect fit for beginners and students like you. Don’t miss out on this opportunity! Trust me, you won’t regret it.

Click here to check out Hostinger’s VPS hosting

Stay Connected for Quick Updates!

Thank you for exploring our guide on Node.js and Express.js. To stay updated with the latest developments, tutorials, and insightful content, be sure to follow us on LinkedIn and Twitter.

LinkedIn: Sandeep Singh

Twitter: sandeepdev_me

By following us on these platforms, you’ll be the first to know about new articles, tutorials, and valuable resources to enhance your skills as a developer. Don’t miss out on the opportunity to stay connected with our community!

Conclusion

In this beginner’s guide, we explored the fundamentals of GraphQL, dissecting queries, resolvers, and mutations. We also set up a basic GraphQL server using Express. As you delve deeper into GraphQL, you’ll discover its power in crafting efficient and flexible APIs. So, give it a try, and embrace the future of data interaction in your applications!

--

--

Sandeep Singh (Full Stack Dev.)

Fullstack Developer | MERN & Flutter | Passionate about Open Source | Engaged in Contributing & Collaborating for a Better Tech Community. 🚀