A Beginner’s Guide to GraphQL
👋 In this article, you’re going to learn how GraphQL works. I’m going to show you how to create a very well-designed, efficient, powerful API using GraphQL.
You’ve probably already heard about GraphQL, as a lot of people and companies are using it. Since GraphQL is open-source, its community has grown huge.
Now, it’s time for you to start to learn in practice how GraphQL works and all about its magic.
Introduction to GraphQL
- What is GraphQL?
GraphQL is a query language for APIs that was developed by Facebook. It allows clients to define the structure of the data they require, and the server will respond with exactly that data. It provides a more efficient, powerful and flexible alternative to REST APIs.
- How does it differ from REST?
GraphQL differs from REST because it allows clients to define the structure of the data they require, and the server will respond with exactly that data. This provides a more efficient, powerful, and flexible alternative to REST APIs, which often require multiple requests to different endpoints to retrieve all the necessary data.
- Advantages of using GraphQL
- Provides a more efficient, powerful, and flexible alternative to REST APIs
- Allows clients to define the structure of the data they require, and the server will respond with exactly that data
- Reduces the amount of data transferred over the network by only returning the fields requested by the client
- Simplifies client-side code by reducing the number of API requests needed
- Enables faster development by allowing changes to the API schema without impacting existing clients
Setting up a GraphQL Server
-
Creating a new project folder
- Create a new folder named
graphql-course
- Change directory to newly created folder
graphql-course
- create
package.json
file by runningnpm init -y
- Create a new folder named
-
Install the following dependencies using npm:
graphql
@apollo/server
-
Install the following dev dependencies to automatically restart the server when changes are made:
-
nodemon
-
npm install @apollo/server graphql
npm install nodemon -D
- Update package.json file with the following code.
{
"name": "graphql-course",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"express-graphql": "^0.12.0"
},
"devDependencies": {
"@apollo/server": "^4.7.5",
"graphql": "^16.7.1",
"nodemon": "^2.0.22"
}
}
Scripts are used to run the server. The start
script runs the server using the node
command, and the dev
script runs the server using the nodemon
command. The nodemon
package is a development dependency that will automatically restart the server when changes are made.
- Creating a GraphQL Server
Now we will create index.js file and add the following code to it.
//index.js
import { ApolloServer } from "@apollo/server"
import { startStandaloneServer } from "@apollo/server/standalone"
import { typeDefs } from "./typeDefs.js"
import { resolvers } from "./resolver.js"
const server = new ApolloServer({
typeDefs,
resolvers,
})
const { url } = await startStandaloneServer(server)
console.log(`🚀 Server ready at ${url}`)
We have imported two files typeDefs.js
and resolver.js
which we will create in the next step.
-
Creating a GraphQL schema
- Create a new file called
typeDefs.js
and add the following code to it:
export const typeDefs = `#graphql type Book { id: ID! title: String! } type Query { books: [Book] book(id: ID!): Book } type Mutation { addBook(title: String!): Book deleteBook(id: ID!): Book updateBook(id: ID!, title: String!): Book } `;
We have created a simple schema for CRUD operation on the books array. The schema defines the types of data that can be queried and the operations that can be performed on that data. The schema is written in the GraphQL Schema Definition Language (SDL), which is a human-readable syntax for defining GraphQL schemas.
We have created two queries and three mutations. Thebooks
query returns an array of books, and thebook
query returns a single book by its ID. TheaddBook
mutation adds a new book to the array, thedeleteBook
mutation deletes a book from the array, and theupdateBook
mutation updates the title of a book. - Create a new file called
-
Creating resolvers for GraphQL schema.
- Create a new file called
resolver.js
and add the following code to it:
let books = [ { id: "1", title: "Harry Potter and the Sorcerer's stone" }, { id: "2", title: 'Jurassic Park' }, { id: "3", title: 'The Lord of the Rings' }, { id: "4", title: 'The Hobbit' }, { id: "5", title: 'The Hunger Games' }, { id: "6", title: 'The Da Vinci Code' } ]; export const resolvers = { Query: { books: () => books, book: (parent, args) => { return books.find(book => book.id === args.id); } }, Mutation: { addBook: (parent, args) => { const book = { id: books.length + 1, title: args.title }; books.push(book); return book; }, deleteBook: (parent, args) => { const book = books.find(book => book.id === args.id); books = books.filter(book => book.id !== args.id); return book; }, updateBook: (parent, args) => { const book = books.find(book => book.id === args.id); book.title = args.title; return book; } } };
The resolvers are functions that resolve the queries and mutations defined in the schema. The
books
query resolver returns thebooks
array, and thebook
query resolver returns a single book from the array by its ID. TheaddBook
mutation resolver adds a new book to the array, thedeleteBook
mutation resolver deletes a book from the array, and theupdateBook
mutation resolver updates the title of a book. - Create a new file called
In this example implementation, we define the GraphQL schema using the #graphql
function. We define a Book
type with fields for id
, and title
, and a Query
type including fields for getting all books and getting a specific book by its id
, as well as a Mutation
type including fields for creating, editing, and deleting books.
We then define a books
array as a data source and resolver function for each field in the schema. These resolver functions return the appropriate data from the books
array based on the query or mutation arguments.
🌟 🌟 We have successfully created a GraphQL server using the Apollo Server library.
run npm start
to start the server.
🌟 Finally, we start the server on port 4000 and log a message to the console indicating that the server is running.
The source code for this tutorial is available on GitHub.
apollo-server-tutorial
In part 2 of this tutorial, we will create a React application that uses the Apollo Client library to query the GraphQL server.
In part 3 of this tutorial, we will add authentication to the GraphQL server using the Apollo Server library and how to use it with React.
Top comments (0)