Learning GraphQL: What you need to know to get started

GraphQL traverses your application data graph producing query result trees

What is it?

REST vs GraphQL

~/v1/artists/{id}/albums
~/v1/artists/{id}/top-tracks
~/v1/artists/{id}/related-artists
# This query operation might retrieve where an artist is
# performing next, as well as the venues' locations
query {
event(artist: "Kendrick Lamar") {
venue_names
coordinates
}
}
# If a document contains only one query operation, and the query
# defines no variables & contains no directives, the query may be
# represented in short‐hand, omitting the query keyword & name.
# For example,{
field
}
# This mutation operation might “like” a story and then
# retrieve the new number of likes:
mutation {
likeStory(storyID: 12345) {
story {
likeCount
}
}
}
# We want to query a specific user (requested via the id argument)
# and their profile picture of a specific size:
{
user(id: 4) {
id
name
profilePic(size: 100)
}
}
# Subscriptions are written using the same syntax
# as queries and mutations
subscription {
user(id: 9001) {
name
}
}
// Sample GraphQL endpoint
// https://www.app-does-not-exist.com/graphql
// Sample POST request using fetch
// Note how the body field's structure matches a query operation
fetchData(artist) { return fetch('https://www.app-does-not-exist.com/graphql', {
method: 'POST',
body: JSON.stringify({ query: `{ event(artist: "${artist}") { venue_names coordinates} }` }), headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json()) .catch(error => console.error(error));}

What do the results look like?

Representation of the returned JSON; the returned data represents the “leaves” of the query

So…about that back-end schema?

Initial Setup

> mkdir graphql-demo
> cd graphql-demo
> npm init -y
> touch schema.js server.js
> npm i graphql express express-graphql node-fetch dataloader cors --save

Simple Server & Schema

# Sample Query
{
Pokemon(id: 149){
id
name
}
}
# Sample response from /graphql endpoint
{
"data": {
"Pokemon": {
"id": 149,
"name": "dragonite"
}
}
}

TL;DR

Additional Resources

Former mechanical engineer turned software engineer. Living in NYC.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store