GraphQL API with JavaScript: Step-by-Step Practical Tutorial

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Introduction to GraphQL API with JavaScript

GraphQL is a query language for APIs developed by Facebook. Unlike REST, where each endpoint returns a fixed data structure, GraphQL allows the client to request only the fields it needs. This reduces the amount of data transferred and simplifies the development of complex applications.

In this tutorial, we will create a full-fledged GraphQL API on Node.js using Apollo Server. You will learn how to define schemas, write resolvers, execute queries, and mutations. All code examples are ready to run and have been tested in practice.

To get started, you will need Node.js version 14 or higher and a basic knowledge of JavaScript. If you are familiar with Express.js, Apollo Server will feel very similar — it also uses middleware and works with HTTP.



Project Setup and Configuration

Create a new directory and initialize the project:

mkdir graphql-tutorialcd graphql-tutorialnpm init -y

Install the necessary dependencies:

npm install @apollo/server graphqlnpm install nodemon --save-dev

Create a file index.js — this will be the entry point for our application.

The basic project structure will look like this:

graphql-tutorial/├── node_modules/├── index.js├── package.json└── package-lock.json


Creating Your First GraphQL Server

Let's start with a minimal server that returns a simple message. Open index.js and add the following code:

import { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';

// Define the GraphQL schemaconst typeDefs = `#graphql type Query { hello: String }`;

// Resolver for the hello queryconst resolvers = { Query: { hello: () => 'Hello, world! This is the first GraphQL query!', },};

// Create the server instanceconst server = new ApolloServer({ typeDefs, resolvers,});

// Start the serverconst { url } = await startStandaloneServer(server, { listen: { port: 4000 },});

console.log(`🚀 Server running at: ${url}`);

Run the server with the command node index.js. Open your browser and go to http://localhost:4000. You will see the Apollo Sandbox interface where you can execute queries.

Enter the following in the left panel:

query {  hello}

And click the "Run" button. In response, you will get:

{  "data": {    "hello": "Hello, world! This is the first GraphQL query!"  }}


Working with Data Types and Complex Queries

GraphQL allows you to define custom data types. Let's create a user and book model for our API.

Update the index.js file:

import { ApolloServer } from '@apollo/server';import { startStandaloneServer } from '@apollo/server/standalone';

// Define typesconst typeDefs = `#graphql type Book { id: ID! title: String! author: String! publishedYear: Int }

type User { id: ID! name: String! email: String! books: [Book] }

type Query { books: [Book] book(id: ID!): Book users: [User] user(id: ID!): User }`;

// Test dataconst books = [ { id: '1', title: 'Harry Potter', author: 'J.K. Rowling', publishedYear: 1997 }, { id: '2', title: 'The Lord of the Rings', author: 'J.R.R. Tolkien', publishedYear: 1954 }, { id: '3', title: '1984', author: 'George Orwell', publishedYear: 1949 },];

const users = [ { id: '1', name: 'Ivan Ivanov', email: 'ivan@example.com', bookIds: ['1', '2'] }, { id: '2', name: 'Anna Petrova', email: 'anna@example.com', bookIds: ['3'] },];

// Resolversconst resolvers = { Query: { books: () => books, book: (_, { id }) => books.find(book => book.id === id), users: () => users, user: (_, { i

Blogs

Book Recommendations