DEV Community

Brianna Skinner
Brianna Skinner

Posted on

Intro Guide to GraphQL

This blog will provide a brief explanation of GraphQL.

What is GraphQL?

GraphQL is a query language designed for APIs. When a query is sent to a API, you'll be able to grab exactly what you are looking for. This reduces the need for multiple endpoints in API routes, over and under fetching data. Another plus is that the returns are highly customizable. This is referred to as declarative data fetching.

Example of REST API vs GraphQL

REST API

REST_API_URL/customers/13
Enter fullscreen mode Exit fullscreen mode

GraphQL

Breaking Down GraphQL

GraphQL is made up of Schema, Queries and Mutations, and Resolvers. This will define how you want to create, store, and retrieve data.

Schema

The Schema sets up the layout of how the data will be stored and resolved when it is being fetched through queries, or changed with mutations. Below is an example from the GraphQl documentation. The provided link also shows more types of schemas you can design to best fit your needs.

var MyAppSchema = new GraphQLSchema({
  query: MyAppQueryRootType
  mutation: MyAppMutationRootType
});

Enter fullscreen mode Exit fullscreen mode

Queries and Mutations

Queries are used to fetch the data and mutations will be to modify data. When fetching or manipulating data, you can even get specifics by passing in arguments to the query string. Shown in the example below.

query{
   customers(id: "13") {
      name
      email
      number
   }
}
mutation {
  createCustomer(input: {
    name: "Jane Doe",
  }) {
    id
  }
}
Enter fullscreen mode Exit fullscreen mode

Resolvers

Resolvers are functions that describe how queries should be handled and responded to. Below is a hard coded example of a resolver, but it can also be an api request for data.

const RootQuery = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    launches: {
      type: new GraphQLList(LaunchType),
      resolve(parent, args) {
        // can be an api request for data
        return [{
            flight_number: 1,
            flight_name: 'Mocha',
            flight_boolean: false,
            rocket: {
              id: 1,
              name: 'BRIBRI',
              boolean: true,
            },
          }]
      }
    }
Enter fullscreen mode Exit fullscreen mode

Conclusion

The flexibility of GraphQL one of the reasons it can be integrated with other tools such as Mongo and Postgres to handle queries server side. GraphQL can even be used on client side data collection using tools such as Apollo.

I hope you enjoyed this brief example of using GraphQL.

Top comments (0)