Published on

Introduction to GraphQL

Authors

GraphQL is a query language that allows clients to request specifically for the data they need from an API. It's a flexible alternative to REST, and can be used with any existing codebase or storage engine. Some popular implementations of GraphQL include Insomnia, GraphQLite, Mercurius, Relay, and Apollo.

GraphQL services are created by defining types and fields on those types, and then creating functions for each field on each type. These functions are then used to execute queries and return results to the client.

There are three main types of operations in GraphQL: queries, mutations, and subscriptions.

Queries

Queries allow clients to request specific data from the server. One of the main benefits of GraphQL is the ability to define a schema for the fields you want to fetch, including the ability to join data from multiple sources into a single JSON response. For example, you can fetch data about a hero character, such as R2-D2, and include data about their friends in the same response. GraphQL also supports arguments, variables, and the special "__typename" meta field, which returns the type name of the entity being requested.

Mutations

Mutations allow clients to modify data on the server. Like queries, mutations can have a defined schema for the fields that will be returned after the mutation is complete. This can be useful for updating the client with the new data after a successful mutation.

Subscriptions

Subscriptions are a long-lasting operation that maintains an active connection to the server and allows updates to be pushed to the client in real-time. While not part of the base GraphQL specification, there are various plugins available, such as graphql-websocket, that can add support for subscriptions.

GraphQL is strictly typed, which means that even in dynamically typed languages like PHP or Ruby, you can expect clear results on the client-side. If you're using TypeScript, there are also plugins available that can generate types from the GraphQL schema on the server.

The GraphQL Schema Language

The GraphQL schema language is used to define the types and fields in a GraphQL service. Here's a simple example:

type Query {
  hero(id: Int!): Hero
  human(id: String!): Human
}

type Hero {
  id: Int!
  name: String
  friends: [Character]
}

type Human {
  id: String!
  name: String
  appearsIn: [Episode]
}

type Character {
  id: Int!
  name: String
  appearsIn: [Episode]
}

enum Episode {
  NEWHOPE
  EMPIRE
  JEDI
}

Building a GraphQL Server with Express and graphql-js

Now, let's build a simple GraphQL server using Express and graphql-js. First, we'll initialize a new npm project and install the required dependencies:

npm init
npm install express graphql

Next, we'll import the necessary modules:

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');

Now, let's define our schema and prepare a resolver function:

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

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

const app = express();

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true
}));

app.listen(4000, () => {
  console.log('Running a GraphQL API server at localhost:4000/graphql');
});

This sets up an Express route at /graphql, and passes the schema and root value (our resolver functions) to the graphqlHTTP middleware. The graphiql option is set to true, which enables the GraphiQL interactive development environment for testing our GraphQL queries.

With this setup, we can now start our server by running node server.js, and visit http://localhost:4000/graphql in our browser to test out our GraphQL query. In the GraphiQL interface, we can enter the following query:

query {
  hello
}

And we should see the following response:

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

This is just a basic example of setting up a GraphQL server with Express and graphql-js. You can find more detailed documentation and examples in the official GraphQL documentation.