Understanding the Basics of GraphQL

GraphQL is a modern, efficient query language for APIs that revolutionizes how we interact with data. Unlike traditional REST APIs, GraphQL enables clients to request only the data they need, minimizing unnecessary data transfer and improving performance.

Understanding the Basics of GraphQL
Understanding the Basics of GraphQL

Introduction 

  GraphQL is a powerful query language for APIs, developed by Facebook, that allows clients to request exactly the data they need, making it more efficient than traditional REST APIs. Unlike REST, where multiple endpoints may be required to fetch different pieces of data, GraphQL enables clients to retrieve everything in a single request, leading to faster, more flexible interactions between the client and server.

Prerequisites

·       GraphQL is typically used in JavaScript environments. We need to Install Recent version of node installed in our system.

·       Choose a text editor like VS Code to write your code.

Set Up a GraphQL Server

I opened a terminal and navigated it to this directory where I want to make the project using  npm init –y

Generating package.json

This will generate the package.json file for us. Next, run npm pkg set type="module", which will enable us to use ES6 modules. You’ll be able to see this change inside the package.json file.

Enable us to use ES6

To open the project in Visual Studio Code, use the following command. This will launch the project for you.

Opening the project in Visual Studio Code

Now, let's install the necessary dependencies. Open a new terminal and paste the npm install command that are copied from the Apollo documentation. npm install @apollo/server graphql

 

Installing necessary dependencies

After that, I’ll create an index.js file. This is where we’ll set up our Apollo server for GraphQL.

import { ApolloServer } from '@apollo/server'

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

// data

import db from './_db.js'

// types

import { typeDefs } from './schema.js'

// resolvers

const resolvers = {

  Query: {

    games() {

      return db.games

    },

    game(_, args) {

      return db.games.find((game) => game.id === args.id)

    },

    authors() {

      return db.authors

    },

    author(_, args) {

      return db.authors.find((author) => author.id === args.id)

    },

    reviews() {

      return db.reviews

    },

    review(_, args) {

      return db.reviews.find((review) => review.id === args.id)

    }

  }

}

// server setup

const server = new ApolloServer({

  typeDefs,

  resolvers

})

const { url } = await startStandaloneServer(server, {

  listen: { port: 4000 }

})

console.log(`Server ready at: ${url}`)

This code sets up an Apollo Server for GraphQL, importing necessary dependencies and data. We define resolvers for querying games, authors, and reviews from a mock database. The Apollo Server is initialized with the typeDefs and resolvers. The server is then started on port 4000 using startStandaloneServer. Finally, the server’s URL is logged to indicate it's ready to accept requests.

GraphQL: Syntax Highlighting

Before we proceed, make sure you have the necessary package installed for GraphQL syntax highlighting in your editor. This will make it easier to work with GraphQL queries and schemas, providing better readability and code completion.

GRAPHQL-SERVER

The typeDefs in GraphQL define the structure of the data in the API, such as fields for an author type like name, avatarUrl, and bio. The schema outlines how data types are related and what queries can be made. Typically, the schema mirrors the data in your application’s database, acting as a layer between the database and client-side queries. This design ensures consistency and efficient data fetching. Let’s now create the schema to match the data we want to expose.

export const typeDefs = `#graphql

  type Game {

    id: ID!

    title: String!

    platform: [String!]!

  }

  type Review {

    id: ID!

    rating: Int!

    content: String!

  }

  type Author {

    id: ID!

    name: String!

    verified: Boolean!

  }

  type Query {

    games: [Game]

    game(id: ID!): Game

    reviews: [Review]

    review(id: ID!): Review

    authors: [Author]

    author(id: ID!): Author

  }

`


In this case, if a query requests all the games, we would typically fetch all the game records from a database and return them as a response. However, since we don’t have a database set up for this example, we’ll use some local data stored in a variable in another file. That said, it would be easy to connect to any database we decide to use in the future.

Now, let's create a new file called db.js, where we will store our data.

let games = [

    {id: '1', title: 'Zelda, Tears of the Kingdom', platform: ['Switch']},

    {id: '2', title: 'Final Fantasy 7 Remake', platform: ['PS5', 'Xbox']},

    {id: '3', title: 'Elden Ring', platform: ['PS5', 'Xbox', 'PC']},

    {id: '4', title: 'Mario Kart', platform: ['Switch']},

    {id: '5', title: 'Pokemon Scarlet', platform: ['PS5', 'Xbox', 'PC']},

  ]

 

  let authors = [

    {id: '1', name: 'mario', verified: true},

    {id: '2', name: 'yoshi', verified: false},

    {id: '3', name: 'peach', verified: true},

  ]

 

  let reviews = [

    {id: '1', rating: 9, content: 'lorem ipsum', author_id: '1', game_id: '2'},

    {id: '2', rating: 10, content: 'lorem ipsum', author_id: '2', game_id: '1'},

    {id: '3', rating: 7, content: 'lorem ipsum', author_id: '3', game_id: '3'},

    {id: '4', rating: 5, content: 'lorem ipsum', author_id: '2', game_id: '4'},

    {id: '5', rating: 8, content: 'lorem ipsum', author_id: '2', game_id: '5'},

    {id: '6', rating: 7, content: 'lorem ipsum', author_id: '1', game_id: '2'},

    {id: '7', rating: 10, content: 'lorem ipsum', author_id: '3', game_id: '1'},

  ]

 

  export default { games, authors, reviews }

 

In the index.js file, we have imported the db (which contains our data), the typeDefs schema, and the resolver queries to tie everything together.

If you have nodemon installed, it will automatically restart the server whenever you make changes to your files. This is especially useful during development, as it saves you from having to manually stop and start the server. Simply run nodemon index.js to start the server with auto-reloading.

Starting the server

 

Once the server is up and running, you'll see the message "Server ready at: http://localhost:4000/". By visiting this URL in your browser, you’ll be able to access the Apollo Explorer. This interactive tool automatically spins up, providing a convenient way to test your GraphQL server. With Apollo Explorer, you can easily execute queries and mutations, explore your API schema, and view real-time responses. It's a powerful feature that allows you to quickly interact with your GraphQL server.

 

Conclusion: 

GraphQL is a modern, efficient query language for APIs that revolutionizes how we interact with data. Unlike traditional REST APIs, GraphQL enables clients to request only the data they need, minimizing unnecessary data transfer and improving performance. With its strongly-typed schema, developers gain better control over the data flow, while also benefiting from real-time updates and a more flexible approach to handling complex relationships between data. Tools like Apollo further enhance the development experience by offering powerful features for testing, debugging, and optimizing GraphQL queries. By understanding the core principles of GraphQL, developers can create faster, more efficient, and maintainable APIs, driving better user experiences and more scalable applications.

Mulecraft Footer