How to Implement a GraphQL API on Top of an Existing REST API

Tyler Hawkins
codeburst
Published in
6 min readFeb 1, 2021

--

Dad joke “dadabase” app
Dad joke “dadabase” app

Where do you keep your dad jokes? In a dadabase of course! Let’s imagine that you are a site maintainer for the world’s best dad joke database. Your app communicates with the database using a REST API that allows you to retrieve jokes and post ratings for those jokes. Visitors to your site can rate each joke they see via a simple user interface.

Recently you heard of a fancy new technology called GraphQL that provides the flexibility to request only the data that you need using a single API endpoint. It sounds neat, and you’d like to start using it in your app. But, you’d really prefer not to make any breaking changes to the existing REST API. Is it possible to support both the REST API and the GraphQL API in your app? You’re about to find out!

In this article, we’ll explore what it takes to implement a GraphQL API on top of an existing REST API. This strategy allows you to start using GraphQL in legacy portions of your app without breaking any existing contracts with functionality that may still rely on the original REST API.

If you’d like to see the end result, you can find the code for the REST API here and the code for the frontend and GraphQL API here. Don’t forget to visit the app as well to groan at some jokes.

The Initial Architecture

The app’s backend was originally built using Node and JSON Server. JSON Server utilizes Express to provide a full REST API to a mock database generated from a simple JSON file. A separate Express server takes care of serving the static HTML, CSS, and JavaScript assets for the frontend. The frontend is implemented in vanilla JS and uses the browser’s built-in Fetch API to make the API requests. The app is hosted on Heroku to make deployment and monitoring a breeze.

Our JSON file contains information for a few jokes as well as some ratings. It’s reproduced in full below:

JSON Server takes that file as a starting point for the database and then implements a…

--

--