How to build a GraphQL server with Swift and Vapor

Alexander Steiner
6 min readFeb 9, 2020

GraphQL is a query language for APIs developed by Facebook but open sourced in 2015. It is an alternative to REST-based APIs because it allows clients to decide which data they need instead of the server upfront deciding which data is delivered on each endpoint. It is a modern way of querying data, for example, some big companies next to Facebook like GitHub or Shopify have seen the advantages and implemented their APIs with GraphQL.

This Article can also be read on my personal blog:

If you want to learn more about GraphQL go and check out their website. They provide great articles and tutorials to get started.

At the end of this article, we’ll have a running GraphQL server that we can reach via the web-based GraphQL query tool GraphiQL. As an example, we use a todo app. We are going to create new todos, list all existing once and also delete todos.

If you already have some experience with Vapor and have created a new application before, you will recognize the todo template, that comes with every new Vapor application, in this article. We are going to build the same functionality with GraphQL.

Getting started

Let’s start by creating a new Vapor project. The easiest way to do that is using the toolbox which provides the command vapor new GraphQL-Todo. This creates a new Swift Package Manager application with some default configuration for Vapor. We'll use this as a base to build our GraphQL server on top of that.

First, we need to modify our Package.swift file and add new dependencies. The GraphQLKit package provides a thin wrapper around the core functions to make them easier to use with Vapor. It also includes the GraphQL implementation for Swift itself, Graphiti with GraphQL. We don't need to import both packages directly as GraphQLKit imports and exposes them automatically. The second new dependency is optional but provides us with a GraphiQL web page we can serve from our web server that gives as an IDE-like interface to send queries against our GraphQL server.

Alexander Steiner

Server Side Swift developer with background in iOS and web development.