Turn a REST API into a GraphQL API
Audrey Roy Greenfeld
Posted on April 27, 2020
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!
}
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
}
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();
},
}
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
}
}
It responds with real data from PokeAPI:
{
"data": {
"getPokemon": {
"id": "25",
"base_experience": 112
}
}
}
Yay! As a practice exercise, try implementing another field besides base_experience
:
- Remix my Glitch app
- Add the field to the
Pokemon
schema - Add it to your query and see the results in GraphQL Playground
With this knowledge and a little practice, there's so much you can do. Enjoy!
Posted on April 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.