Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

GraphQL Tutorial

Introduction to GraphQL

GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data. GraphQL isn't tied to any specific database or storage engine and is instead backed by your existing code and data.

Setting Up a GraphQL Server

To set up a GraphQL server, you need to choose a server library for your programming language. For this tutorial, we'll use Node.js and Express along with the Apollo Server library.

First, create a new directory for your project and initialize a new Node.js project:

mkdir my-graphql-server
cd my-graphql-server
npm init -y

Next, install the necessary dependencies:

npm install express apollo-server-express graphql

Creating a Basic GraphQL Schema

A GraphQL schema is at the core of any GraphQL server implementation. It defines the types and relationships in your data model. Create a file named schema.js:

touch schema.js

In schema.js, define a simple schema:

const { gql } = require('apollo-server-express');

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!'
  }
};

module.exports = { typeDefs, resolvers };

Setting Up Apollo Server with Express

Next, set up Apollo Server with Express in your index.js file:

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const { typeDefs, resolvers } = require('./schema');

const startServer = async () => {
  const app = express();
  const server = new ApolloServer({ typeDefs, resolvers });
  await server.start();
  server.applyMiddleware({ app });

  app.listen({ port: 4000 }, () =>
    console.log(`Server ready at http://localhost:4000${server.graphqlPath}`)
  );
};

startServer();

Running Your GraphQL Server

To start your server, run the following command:

node index.js

You should see the following output:

Server ready at http://localhost:4000/graphql

Querying Your GraphQL API

With your server running, open your browser and navigate to http://localhost:4000/graphql. You will see the Apollo Server Playground, an interactive, in-browser GraphQL IDE.

In the Playground, you can run the following query:

{
  hello
}

You should get the following response:

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

Advanced GraphQL Concepts

GraphQL offers many advanced features including mutations, subscriptions, and more complex schemas. To learn more about these topics, refer to the official GraphQL documentation and Apollo Server documentation.

Conclusion

In this tutorial, we covered the basics of setting up a GraphQL server using Node.js, Express, and Apollo Server. We created a simple schema, set up Apollo Server, and ran queries against our GraphQL API. GraphQL provides a powerful and flexible way to work with APIs, and there's much more to explore beyond this introduction.