GraphQL : The Basics

GraphQL : The Basics

ยท

4 min read

Origin :

GraphQL was created by Facebook in 2012 as a way to simplify data management in their mobile applications. At the time, Facebook was struggling with the increasing complexity of its mobile apps, which were built using a REST API architecture.

REST APIs required developers to create multiple endpoints for different types of data, making it difficult to maintain and update the application. GraphQL solved this problem by providing a single endpoint that allowed developers to request only the data they needed.

In 2015, Facebook publicly released GraphQL as an open-source project, allowing developers around the world to use and contribute to the language. Since then, GraphQL has become increasingly popular in the web development community, with many companies adopting it as a way to simplify their data management and improve the performance of their applications. Today, GraphQL continues to evolve and improve, driven by a vibrant community of developers and contributors.

Apollo Server is a popular implementation of GraphQL for Node.js. It is a fully-featured GraphQL server that allows you to build high-performance APIs with GraphQL.

In this tutorial, we will cover how to use Apollo Server with an Express server.

Prerequisites

To follow this tutorial, you will need:

  • Node.js is installed on your machine.

  • A basic understanding of Node.js and Express.

Setup

  1. Create a new directory for your project and navigate into it:

     mkdir apollo-express
     cd apollo-express
    
  2. Initialize a new Node.js project with npm init. Accept the default options by pressing enter for each prompt:

     npm init
    
  3. Install the required dependencies:

     npm install apollo-server-express express graphql
    

Setting up the Express Server

  1. Create a new file called server.js in the root of your project.

  2. Require the necessary dependencies:

     const express = require('express');
     const { ApolloServer, gql } = require('apollo-server-express');
    
  3. Create an instance of the express server:

     const app = express();
    
  4. Define a GraphQL schema using the gql tag function:

     const typeDefs = gql`
       type Query {
         hello: String
       }
     `;
    

    In this example, we define a Query type with a single field called hello that returns a string.

  5. Create a resolver for the hello field:

     const resolvers = {
       Query: {
         hello: () => 'Hello, world!',
       },
     };
    

    The resolver maps the hello field to a function that returns the string 'Hello, world!'.

  6. Create a new instance of the ApolloServer and pass in the typeDefs and resolvers:

     const server = new ApolloServer({ typeDefs, resolvers });
    
  7. Start the express server:

     async function startServer() {
       await server.start();  
     // Connect the ApolloServer to the express app:
     // This will set up the ApolloServer with the express server and make the GraphQL endpoint available at /graphql.
       server.applyMiddleware({ app });
       app.listen({ port: 4000 }, () =>
         console.log(`๐Ÿš€ Server ready at http://localhost:4000${server.graphqlPath}`)
       );
     }
    
     startServer();
    

    This will start the express server on port 4000 and log a message to the console with the URL of the GraphQL endpoint.

Testing the GraphQL Endpoint

  1. Start the server by running:

     node server.js
    
  2. Open your browser and navigate to http://localhost:4000/graphql. This will open the GraphQL Playground, which is a user interface for testing GraphQL queries.

  3. In the left panel of the Playground, enter the following query:

     query {
       hello
     }
    
  4. Click the play button or press Ctrl + Enter to execute the query.

  5. You should see the following result in the right panel of the Playground:

     {
       "data": {
         "hello": "Hello, world!"
       }
     }
    

    This confirms that the GraphQL endpoint is working correctly.

Conclusion

In this tutorial, we covered how to set up an Apollo Server with an Express server. We created a simple GraphQL schema and resolver and connected them to the Express server using Apollo Server middleware.

We also tested the GraphQL endpoint using GraphQL Playground and confirmed that it was working correctly.

Using Apollo Server with Express allows us to build powerful and efficient GraphQL APIs with minimal setup and configuration. With its ease of use and flexibility, Apollo Server is a great choice for building modern web applications that require a robust API.

We hope this tutorial has given you a good understanding of how to use Apollo Server with Express to build GraphQL APIs. Happy coding!

Did you find this article valuable?

Support Architecting-Systems by becoming a sponsor. Any amount is appreciated!

ย