GraphQL: Centralize existing REST API endpoints for easier development

Roelof Jan Elsinga
ITNEXT
Published in
4 min readAug 27, 2020

--

API gateways are great for development teams because they expose the data you need for all kinds of different purposes in a central location. There are a few great REST API gateways out there, like KrakenD, but what if you wanted to go in a different direction and choose GraphQL for your API infrastructure? Well, that works out perfectly, as it’s one of the goals of GraphQL: Abstracting many different services into a single place and allowing the developers very fine-grained control over the data they need.

In this post, we’re going to look over a GraphQL implementation, which keeps the previous sentence in mind: Abstracting existing REST API Endpoints into a fast GraphQL server. To build the GraphQL server, we’re going to use Golang: It’s fast, it’s memory efficient, and provides just enough tools, but not too many. The GraphQL package we’ll use is github.com/graphql-go/graphql. This package is very closely aligned with the JavaScript implementation graphql-js. This makes it a perfect candidate because you’ll be able to follow JavaScript tutorials and be able to port this to Go.

The entry point

To show how you can abstract an existing REST API Endpoint in GraphQL, we’re going to need an example project. I’ve created an example project at github.com/roelofjan-elsinga/graphql-rest-abstraction. You can use this to follow along in this post, as I will go over different parts of the GraphQL server and explain what’s going on.

The entry point of our GraphQL server is main.go. Here we specify two resources in our GraphQL server: users and user.

We intend to use a dummy REST API service to fetch JSON data for all users and also a single user. The “users” resources will be used to fetch all users at https://jsonplaceholder.typicode.com/users, while the “user” resource will be used to fetch a single user by ID from https://jsonplaceholder.typicode.com/users/1 or any other user available to us.

Fetching all users

Now that we have a REST API we can use, we can create a resource to be able to fetch this data through a GraphQL resource. You can find this resource in queries/users.go:

--

--

Writer for

I'm a web developer, working with Docker, Laravel, Go, Angular, and Solr. My posts can be found on my personal blog at roelofjanelsinga.com