DEV Community

Cover image for Turn a REST API into a GraphQL API
Audrey Roy Greenfeld for Feldroy

Posted on

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:


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"){
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!

Top comments (3)

spock123 profile image
Lars Rye Jeppesen

That was nice and simple, thanks!
Many of use serve a REST API and cannot "replace" it with GraphQL.

In this way we can do both at the same time, let the REST API do the bulk of the loading and just provide the interface for the clients. Nice.

adgower profile image
Alex Gower


adityapadwal profile image
Aditya Padwal

Nice, would be great to know how to wrap a a GraphQL on top of REST in Python.