How to wrap a Graphql API around a REST API

How to wrap a Graphql API around a REST API

Grapqhl was created from Facebook and in the long-run has changed the perspective of how API's query data and how backend end API's work as a whole. In this one, we would be looking at how to wrap your REST API's with Grapqhl or a Graphql API. Before you jump into this tutorial you should have a fair knowledge of how Graphql works basically, how the schemas work and how Grapqhl is being set up as a whole.

I used a news REST API with this link: News API

STEPS INVOLVED IN WRAPPING YOUR REST API WITH GRAPHQL.

Step 1:
We model our Graphql schema to match our Rest API schema from the link provided above "News API".  Nb: You need to set up your Graphql API  and make sure it's running on a local port on your machine.


Step 2:
In our resolvers, create a Query resolver where our articles would be returned and we can see that in the illustration above "articles: [Article!]!".  Setup the articles resolver in our Query resolver. Illustrated below.



Don't get confused about the results yet it will be explained in Step 3, This Query article resolver just demonstrates how the data fetched from our REST API is being wrapped with our Graphql API. 

Step 3
We see in Step 2 that there were two unknown variables used "fetch" and "Url". Fetch is an npm package that was is used to fetch the data from our REST API and Url was the pinpoint of where our REST API can be found on the web.


We then store our data "json.articles" that was returned from the REST API in our results variable that would be used by our Graphql API. Thus, we then return "results" in our articles resolver which should query the Articles from our REST API in our Graphql API. 

Step 4

After implementing our resolver, we open our Graphql API or Graphql playground on either our local port or development endpoint and run our resolver. Here we see that data from the REST API is being used or fetched into our Graphql API. Thus, we have a REST API wrapped with Graphql or a Graphql API.
       
Previous Post Next Post