Building API-driven Applications with GraphQL and JavaScript


GraphQL has gained significant popularity in recent years as a powerful alternative to traditional RESTful APIs. Its ability to efficiently retrieve data and provide a flexible querying mechanism has made it a favourite choice among developers building API-driven applications. In this article, we will explore the fundamentals of GraphQL and learn how to build API-driven applications using JavaScript.

What is GraphQL?

GraphQL is an open-source query language and runtime for APIs. It was developed by Facebook and released publicly in 2015. Unlike RESTful APIs, where multiple endpoints are required to retrieve specific data, GraphQL allows clients to request exactly what they need in a single query. It provides a strongly typed schema that describes the available data and allows clients to specify the shape of the response they require.

GraphQL is designed to improve efficiency by reducing over-fetching and under-fetching of data. Over-fetching refers to retrieving more data than necessary, while under-fetching refers to the need for multiple requests to gather all the required data. With GraphQL, clients can fetch only the required data in a single request, resulting in faster and more efficient data retrieval.

Setting up a GraphQL Server

To begin building GraphQL applications with JavaScript, we need to set up a GraphQL server. There are several libraries available for this purpose, but for this article, we will be using Apollo Server, a popular choice for building GraphQL servers in JavaScript.

First, let's install the required dependencies −

npm install apollo-server graphql

Once the installation is complete, we can start building our GraphQL server. Create a new JavaScript file, server.js, and add the following code −

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

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

// Define resolvers to handle the query
const resolvers = {
   Query: {
      hello: () => 'Hello, GraphQL!'
   }
};

// Create an instance of ApolloServer
const server = new ApolloServer({ typeDefs, resolvers });

// Start the server
server.listen().then(({ url }) => {
   console.log(`Server running at ${url}`);
});

Explanation

In the code snippet above, we define a simple GraphQL schema with a single query called hello that returns a string. We also define a resolver function for the hello query that returns the string "Hello, GraphQL!". Finally, we create an instance of ApolloServer and start the server.

To run the server, execute the following command in your terminal −

node server.js

If everything is set up correctly, you should see the message "Server running at http://localhost:4000" in the terminal.

Executing GraphQL Queries

Now that our GraphQL server is up and running, we can execute queries against it. GraphQL queries are structured JSON-like objects that define the data we want to retrieve.

Let's modify our schema to include a more complex data type and query. Update the typeDefs constant in server.js as follows:

// server.js
const typeDefs = gql`
   type Book {
      title: String
      author: String
   }

   type Query {
      books: [Book]
   }
`;

Explanation

In the updated schema, we define a new Book type with title and author fields. We also modify the Query type to include a books field that returns an array of Book objects.

Next, update the resolvers constant in server.js to provide a resolver function for the books field:

// server.js
const resolvers = {
   Query: {
      books: () => [
         { title: 'Harry Potter and the Philosopher's Stone', author: 'J.K. Rowling' },
         { title: 'To Kill a Mockingbird', author: 'Harper Lee' },
         { title: '1984', author: 'George Orwell' }
      ]
   }
};

In the resolver function for books, we return an array of books with their respective titles and authors.

Restart the server, and let's test our new query using the GraphQL Playground. Open your browser and navigate to http://localhost:4000 to access the playground.

In the left panel of the GraphQL Playground, enter the following query:

{
   books {
      title
      author
   }
}

Hit the play button or press Ctrl + Enter to execute the query. You should see the following output in the right panel:

{
   "data": {
      "books": [
         {
            "title": "Harry Potter and the Philosopher's Stone",
            "author": "J.K. Rowling"
         },
         {
            "title": "To Kill a Mockingbird",
            "author": "Harper Lee"
         },
         {
            "title": "1984",
            "author": "George Orwell"
         }
      ]
   }
}

The query retrieves the title and author fields of all the books and returns them in the response.

Mutations in GraphQL

While queries are used for retrieving data, mutations are used for modifying data. Let's modify our schema to include a mutation for adding a new book. Update the typeDefs constant in server.js as follows −

// server.js
const typeDefs = gql`
   type Book {
      title: String
      author: String
   }

   type Query {
      books: [Book]
   }

   type Mutation {
      addBook(title: String, author: String): Book
   }
`;

In the updated schema, we define a new Mutation type with an addBook field that takes title and author as arguments and returns a Book object.

Next, update the resolvers constant in server.js to provide a resolver function for the addBook mutation:

// server.js
const resolvers = {
   Query: {
      // Query resolvers
   },
   Mutation: {
      addBook: (parent, args) => {
         const newBook = { title: args.title, author: args.author };
         // Logic to save the new book
         return newBook;
      }
   }
};

In the resolver function for addBook, we create a new book object using the title and author arguments provided. We can add logic here to save the new book to a database or perform any other necessary operations.

Restart the server and open the GraphQL Playground. In the left panel, enter the following mutation:

mutation {
   addBook(title: "The Great Gatsby", author: "F. Scott Fitzgerald") {
      title
      author
   }
}

Execute the mutation, and you should see the following output −

{
   "data": {
      "addBook": {
         "title": "The Great Gatsby",
         "author": "F. Scott Fitzgerald"
      }
   }
}

The mutation adds a new book with the provided title and author to the data source and returns the added book in the response.

Conclusion

GraphQL provides a powerful and efficient way to build API-driven applications. With its flexible querying mechanism and ability to retrieve exactly the required data in a single request, it has become a popular choice among developers. In this article, we explored the basics of GraphQL with JavaScript by building a GraphQL server, executing queries, and performing mutations.

We learned how to set up a GraphQL server using Apollo Server and defined a simple schema with queries and mutations. We executed queries to retrieve data and mutations to modify data. Throughout the article, we provided code examples with explanations and observed the corresponding output.

Updated on: 24-Jul-2023

109 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements