DEV Community

Cover image for A Beginner’s Guide to Building GraphQL APIs with Apollo Server
Ayush Kumar Vishwakarma
Ayush Kumar Vishwakarma

Posted on

A Beginner’s Guide to Building GraphQL APIs with Apollo Server

GraphQL is a query language for APIs and a runtime for executing queries against a type system you define for your data. Unlike REST, which uses multiple endpoints for different resources, GraphQL allows clients to request exactly the data they need, which makes it more efficient for both the client and server. Apollo Server is a popular open-source GraphQL server that makes it easy to set up a GraphQL API. In this guide, we’ll walk you through the steps to build a simple GraphQL API with Apollo Server.

What is Apollo Server?

Apollo Server is a library that helps you set up a GraphQL server. It supports many popular JavaScript frameworks, such as Express, Koa, and Hapi, and offers an easy way to get started with GraphQL. It provides out-of-the-box tools to help you connect to data sources, handle queries, and even handle authentication.

Setting Up the Apollo Server

To begin building a GraphQL API with Apollo Server, you need to install the necessary dependencies:

npm install apollo-server graphql
Enter fullscreen mode Exit fullscreen mode

1. Define the Schema: In GraphQL, the schema defines the types of data your API can serve. This is done using the GraphQL Schema Definition Language (SDL).

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

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

// Define the resolver for the query
const resolvers = {
  Query: {
    hello: () => 'Hello, World!',
  },
};

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

// Start the server
server.listen().then(({ url }) => {
  console.log(`Server ready at ${url}`);
});
Enter fullscreen mode Exit fullscreen mode

In this example, we defined a simple schema with one Query type and a single field called hello. The resolver function returns the string "Hello, World!" when the hello field is queried.

2. Running the Server: Once the schema and resolvers are defined, the Apollo Server instance is created and started. Running the server will make the GraphQL API available at a URL, such as http://localhost:4000.

Connecting to a Database

In real-world applications, GraphQL APIs often interact with a database. Here’s an example using Apollo Server to connect to a MongoDB database.

1. Install Dependencies:

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

2. Define the MongoDB Schema:

const mongoose = require('mongoose');

// Define a simple User schema
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
});

// Create a model based on the schema
const User = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

3. Modify the Resolver:

const resolvers = {
  Query: {
    users: async () => {
      return await User.find();
    },
  },
};
Enter fullscreen mode Exit fullscreen mode

4. Connecting Apollo Server with MongoDB:

mongoose.connect('mongodb://localhost/graphql-demo', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('MongoDB connected');
    server.listen().then(({ url }) => {
      console.log(`Server ready at ${url}`);
    });
  })
  .catch(err => {
    console.error('Database connection error', err);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, we connected Apollo Server with MongoDB and defined a users query that retrieves all users from the database.

Making Queries with Apollo Client

Once the server is running, you can query your GraphQL API using Apollo Client. Install the required dependencies:

npm install @apollo/client graphql
Enter fullscreen mode Exit fullscreen mode

1. Set Up Apollo Client:

import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'http://localhost:4000',
  cache: new InMemoryCache(),
});

client
  .query({
    query: gql`
      query GetUsers {
        users {
          name
          email
        }
      }
    `,
  })
  .then(response => console.log(response.data))
  .catch(error => console.error('Error fetching data', error));
Enter fullscreen mode Exit fullscreen mode

In this example, we set up Apollo Client to connect to the GraphQL API and send a query to fetch all users.

Conclusion
GraphQL, coupled with Apollo Server, is a powerful tool for building APIs that provide a flexible and efficient way to query and manipulate data. By connecting Apollo Server to a database, you can create a full-featured GraphQL API capable of interacting with data. Once the backend is set up, you can use Apollo Client to interact with the API from your React application.

Top comments (0)