Open In App

Building your first GraphQL server with Apollo Server

Last Updated : 29 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

APIs are central in web development these days; there is REST, which has been the traditional way. Unfortunately, it causes problems of over-fetching and under-fetching views. GraphQL can solve this problem by allowing the client to request exactly what it wants through a single endpoint, making for faster and more flexible APIs.

Building-your-first--GraphQL--Server_
Building your first GraphQL server with Apollo Server

This guide will take us through building a GraphQL server with Apollo Server step-by-step. Starting with a basic setup, we will define a GraphQL schema, create queries and mutations, and test our API from the GraphQL Playground. This article is completely beginner-friendly to start a fresh journey in Apollo serves so let's begin!

Prerequisites

Before we start building our GraphQL server with Apollo, make sure you have the following:

Setting Up a Basic Apollo Server

Setting up an Apollo Server is simple. Let’s go step by step.

Step 1: Initialize a Node.js Project

First, create a new project folder and navigate into it:

mkdir apollo-server 
cd apollo-server

Now, initialize a Node.js project:

npm init -y

This creates a package.json file to manage dependencies.

Step 2: Install Required Packages

Apollo Server requires two main dependencies:

  • apollo-server – The GraphQL server package.
  • graphql – The core GraphQL library.

Run the following command to install them:

npm install apollo-server graphql
JavaScript
{
    "name": "apollo-server", "version": "1.0.0",
        "main": "index.js", "scripts": {
            "test":
                "echo \"Error: no test specified\" && exit 1"
        },
        "keywords": [], "author": "", "license": "ISC",
        "description": "", "dependencies": {
            "apollo-server": "^3.13.0",
            "graphql": "^16.10.0"
        }
}

Step 3: Create a Simple Apollo Server

Now, create an index.js file and add the following code:

JavaScript
const {ApolloServer, gql} = require("apollo-server");

// Define GraphQL schema
const typeDefs = gql`
    type Query {
        hello: String
    }
    `;

// Define resolvers
const resolvers = {
    Query : {
        hello : () => "Hello, GFG! Welcome to my server",
    },
};

// Create and start Apollo Server
const server = new ApolloServer({typeDefs, resolvers});

server.listen().then(
    ({url}) => { console.log(`Server ready at ${url}`); });

Step 4: Run the Server

Start the GraphQL server using:

node index.js

You should see an output like:

PS C:\Users\Desktop\apollo\apollo-server> node index.js
Server ready at http://localhost:4000/

Step 5: Test Your First Query

Open your browser and go to http://localhost:4000/.
Run this query in the GraphQL Playground:

query {
hello
}

You should get a response:

Screenshot-2025-03-25-180802

Expanding the GraphQL Schema

Now that we have a basic Apollo Server running, let’s expand the GraphQL schema to handle more complex data. Instead of just returning a "hello" string, we'll define a User type and fetch user data.

Step 1: Define a User Type

Modify your index.js file to include a User type:

JavaScript
const { ApolloServer, gql } = require('apollo-server');

// Define GraphQL schema
const typeDefs = gql`
  type User {
    id: ID!
    name: String!
    age: Int
  }

  type Query {
    users: [User]
  }
`;

// Sample data
const users = [
  { id: "1", name: "Geeks-1", age: 25 },
  { id: "2", name: "Geeks-2", age: 30 }
];

// Define resolvers
const resolvers = {
  Query: {
    users: () => users,
  },
};

// Create and start Apollo Server
const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

Step 2: Run the Server

Restart your server:

node index.js

Step 3: Test the New Query

In the GraphQL Playground (http://localhost:4000/), run:

query {
users {
id
name
age
}
}

You should get a response like this:

Screenshot-2025-03-25-162142

Adding Mutations

So far, we’ve only worked with queries, which fetch data. Now, let's add mutations, which allow us to modify data (e.g., adding new users).

Step 1: Define the Mutation

Update the typeDefs in index.js to include a mutation for adding a new user:

JavaScript
const { ApolloServer, gql } = require('apollo-server');

// Define GraphQL schema
const typeDefs = gql`
  type User {
    id: ID!
    name: String!
    age: Int
  }

  type Query {
    users: [User]
  }

  type Mutation {
    addUser(name: String!, age: Int!): User
  }
`;

// Sample data
const users = [
  { id: "1", name: "Geeks-1", age: 25 },
  { id: "2", name: "Geeks-2", age: 30 }
];

// Define resolvers
const resolvers = {
  Query: {
    users: () => users,
  },
  Mutation: {
    addUser: (_, { name, age }) => {
      const newUser = { id: String(users.length + 1), name, age };
      users.push(newUser);
      return newUser;
    }
  }
};

// Create and start Apollo Server
const server = new ApolloServer({ typeDefs, resolvers });

server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});

Step 2: Run the Server

Restart your server to apply changes:

node index.js

Step 3: Test the Mutation

In the GraphQL Playground (http://localhost:4000/), run this mutation:

mutation {
addUser(name: "Charlie", age: 28) {
id
name
age
}
}

Output

Screenshot-2025-03-25-162641
New User added

Conclusion

In this guide, we have built a GraphQL server using Apollo Server from scratch. We started with a simple setup, defined a GraphQL schema, and created queries to fetch data. Then, we expanded the schema by adding a User type and implemented mutations to modify data dynamically.

This is just the beginning! You can now explore database integration (MongoDB, PostgreSQL), authentication (JWT, OAuth), and real-time subscriptions to build more powerful GraphQL APIs. Keep experimenting and take your API development to the next level!

Must Read


Next Article
Article Tags :

Similar Reads