Introduction to GraphQL

GraphQL is a query language and runtime for APIs. It was developed by Facebook in 2012 and publicly released in 2015 as an open-source project. GraphQL is designed to be a more efficient, powerful, and flexible alternative to traditional REST APIs.

GraphQL allows clients to specify exactly what data they need and the server returns that data in a response. This eliminates the problem of overfetching, where the client gets more data than they need, and underfetching, where the client has to make multiple requests to get all the data they need.

In this tutorial, we’ll cover the basics of GraphQL, including its syntax, types, resolvers, and execution model.

Syntax

GraphQL uses a syntax that is similar to JSON. The basic structure of a GraphQL query is a set of fields with arguments.

query {
  field1(arg1: "value") {
    subfield1
    subfield2
  }
  field2 {
    subfield1
    subfield2
  }
}

In this example, we have a query with two fields: field1 and field2. field1 takes an argument arg1 with the value "value". Each field has two subfields: subfield1 and subfield2.

Types

GraphQL has a type system that defines the shape of the data that can be queried. Types can be scalars (like Strings and Integers) or objects (like Users and Posts).

type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post]!
}

type Post {
  id: ID!
  title: String!
  body: String!
  author: User!
}

In this example, we have two types: User and Post. Each type has fields with specific types. The User type has fields id, name, email, and posts. The id field is of type ID!, which means it’s a non-null ID. The name and email fields are of type String!, which means they are non-null Strings. The posts field is of type [Post]!, which means it’s a non-null list of Post objects.

The Post type has fields id, title, body, and author. The id field is of type ID!, the title and body fields are of type String!, and the author field is of type User!.

Resolvers

Resolvers are functions that resolve a GraphQL query. Each field in a GraphQL query has a resolver that knows how to fetch the data for that field.

const resolvers = {
  Query: {
    user: (_, { id }) => {
      return getUser(id);
    },
    post: (_, { id }) => {
      return getPost(id);
    },
  },
  User: {
    posts: (user) => {
      return getPostsByUser(user.id);
    },
  },
  Post: {
    author: (post) => {
      return getUser(post.authorId);
    },
  },
};

In this example, we have three resolvers: user, post, and User.posts. The Query resolver object contains the top-level queries, user and post. The User resolver object contains the field posts, and the Post resolver object contains the field author.

The user resolver takes an argument id and returns the user with that ID. The post resolver takes an argument id and returns the post with that ID. The User.posts resolver takes a user object and returns all the posts written by that user. The Post.author resolver takes a post object and returns the user who wrote that post.

Execution

When a GraphQL query is executed, it goes through several phases: parsing, validation, execution, and response formatting.

const { graphql } = require("graphql");
const schema = require("./schema");
const resolvers = require("./resolvers");

const query = `
  query {
    user(id: "1") {
      name
      email
      posts {
        title
      }
    }
  }
`;

graphql(schema, query, resolvers).then((result) => {
  console.log(result);
});

In this example, we have a GraphQL query that gets the name, email, and titles of all posts written by the user with ID 1. We use the graphql() function to execute the query with the schema and resolvers.

The graphql() function returns a Promise with the result of the query. The result contains data and errors properties. If there are no errors, the data property contains the requested data.

Conclusion

In this tutorial, we covered the basics of GraphQL, including its syntax, types, resolvers, and execution model. GraphQL is a powerful and flexible alternative to traditional REST APIs that eliminates the problem of overfetching and underfetching. With GraphQL, clients can specify exactly what data they need and the server returns that data in a response. Use GraphQL to optimize your API today!

Related Post