Turn a REST API into a GraphQL API

audreyfeldroy

Audrey Roy Greenfeld

Posted on April 27, 2020

Turn a REST API into a GraphQL API

I really like working with GraphQL APIs. I like being able to get data in the shape I want, and using subscriptions to get it in realtime. This weekend I discovered that transforming a REST API into a GraphQL one is easier than it sounds.

This is a walkthrough of turning one REST endpoint to GraphQL. Once you can do one, you can do more 😀

The REST API Endpoint We'll Transform

To keep things simple, we'll use a simple GET REST endpoint as our starting point:

GET https://pokeapi.co/api/v2/pokemon/pikachu/

Now let's create a GraphQL endpoint.

Define the GraphQL Schema for a Pokemon Object

First we define our GraphQL type for the Pokemon data we'll be returning from our new API endpoint:

type Pokemon {
  id:       String!
  name:     String!
  base_experience:  Int!
}
Enter fullscreen mode Exit fullscreen mode

For the sake of example, we're limiting the fields, but add more if you want.

Define the GraphQL Query Type

Then we define a GraphQL query called getPokemon that takes an id and returns a Pokemon object:

type Query {
  getPokemon(id: String!): Pokemon
}
Enter fullscreen mode Exit fullscreen mode

Define the Query Resolver

When a getPokemon GraphQL query comes in, under the hood of our resolver, we send a GET request to /pokemon/<id>/:

const resolvers = {
  Query: {
      getPokemon: async (_, { id }) => {

          const response = await fetch(MY_REST_URL + '/pokemon/' + id + '/');
          return response.json();
      },
  }
Enter fullscreen mode Exit fullscreen mode

Try the Query in GraphQL Playground

A copy of the above code is editable here on Glitch, and running live here with interactive querying via GraphQL Playground

Go to GraphQL Playground and try the query we just created:

query {
  getPokemon(id: "pikachu"){
    id
    base_experience
  }
}
Enter fullscreen mode Exit fullscreen mode

It responds with real data from PokeAPI:

{
  "data": {
    "getPokemon": {
      "id": "25",
      "base_experience": 112
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Yay! As a practice exercise, try implementing another field besides base_experience:

  1. Remix my Glitch app
  2. Add the field to the Pokemon schema
  3. Add it to your query and see the results in GraphQL Playground

You Can Do It

With this knowledge and a little practice, there's so much you can do. Enjoy!

💖 💪 🙅 🚩
audreyfeldroy
Audrey Roy Greenfeld

Posted on April 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Turn a REST API into a GraphQL API
tutorial Turn a REST API into a GraphQL API

April 27, 2020