GraphQL for
Front-end Developers

Why GraphQL?

"I have seen the future, and it looks a lot like GraphQL. Mark my words: in 5 years, newly minted full-stack app developers won’t be debating RESTfulness anymore, because REST API design will be obsolete."

- Is GraphQL the future?
lan Johnson (Engineering Lead at Artsy)

 

Why GraphQL?

"Facebook has played a tremendous role in shifting not only in the way we build our servers, but also how we write code for browsers and phones," says Adam Neary, a tech lead at Airbnb. "The entire ecosystem is driven by technologies that Facebook pioneered and then open sourced."


- How Facebook has changed computing
Wired Magazine
 

GraphQL is a big deal!

GraphQL is a big deal!

My own Journey

  • What exactly is GraphQL?
     
  • What is the problem that GraphQL is trying to solve?
     
  • The GraphQL equivalent of 'Hello World!'
     
  • Examples of GraphQL in the real world.

My own Journey

What exactly is GraphQL?

"...It lets you model the resources and processes provided by a server as a domain-specific language (DSL). Clients can use it to send scripts written in your DSL to the server to process and respond to as a batch."

- Is GraphQL the future?
lan Johnson (Engineering Lead at Artsy)

 

  • DSLs are programming languages that express a very specific and predefined type of digital information (in other words a domain).
     
  • A General purpose language is more like a swiss-army knife that gives you tooling (and the freedom) to express digital information in all kinds of crazy ways.
     
  • HTML (built on SGML/GML), CSS, JSON, YAML or XML

Domain-what-a-thing?

  • Very limited scope, so tend to be used in conjunction with other languages.
     
  • However, their limited scope makes them very expressive.
<part id="part-B">
  <num>B</num>
  <heading>Submission of applications</heading>
  <section id="section-1">
     <num>1.</num>
     <subsection id="section-1.subsection-0">
        <content>
           Other than those signs referred to in Sections 55 to 62 hereinbelow, no person shall display any advertisement or erect or use any sign or advertising structure for advertising purposes without the <term refersTo="#term-Municipality" id="trm19">Municipality</term>'s approval in terms of this By-law and any other applicable legislation.
         </content>
      </subsection>
   </section> 
</part>

Domain-what-a-thing?

  • For example: Akoma Ntoso.
     
  • Limited scope can be frustrating.
     
  • However, their limited scope makes them extremely expressive.
     
  • We use the same principle in 'real-life' languages as well (called 'register' and/or 'jargon').

Domain-what-a-thing?

Flying sky car?

"The Skylon is a fully reusable single stage to orbit (SSTO) vehicle, able to achieve orbit without staging [...]  Because the SABRE engine uses the atmosphere as reaction mass at low altitude, it will have a high specific impulse (around 4,100–9,200 seconds for SABRE 4,[9]:6 or 3,600 seconds for SABRE 3[3]:3), and burn about one fifth of the propellant that would have been required by a conventional rocket."


- Skylon (spacecraft)
Wikipedia
 

Problem that
GraphQL solves?

  • GraphQL was created internally in 2012 by tech team behind Facebook as a DSL to write more expressive and powerful data queries in their mobile app.
     
  • Both Netflix and Coursera developed their own DSLs. Netflix released as Falcor, and Coursera ditched in favour of GraphQL.

One API to rule them all

“With REST, we might have a /authors/:id endpoint to fetch an author, then another /authors/:id/posts endpoint to fetch the post of that particular author. Lastly, we could have a /authors/:id/posts/:id/comments endpoint that fetches the comments on the posts. […] It is easy to fetch more than the data you need with REST, because each endpoint in a REST API has a fixed data structure which it is meant to return whenever it is hit.”


- Rest versus GraphQL
Chimezie Enyinnaya (Pusher Blog)

GraphQL is released

  • GraphQL released 3 years later (in 2015) under
    open-source MIT license.
     
  • Underpins open-source services like Apollo (using GraphQL to read and/or change both local and remote app state)
     
  • Even used in Gatsby to query front-matter and
    textual content from markdown files.

Real World Example

  • Find all users following me on Github and display on page:
const addFollower = follower => `<li>${follower.login}</li>`;

const createList = (data) => {
  return document.body.innerHTML = `<ul>{data.map(addFollower)</ul>`;
}

fetch('https://api.github.com/users/schalkventer/followers')
  .then(response => response.json())
  .then(createList);

Enter Github Equity™

  • Scientifically proven to be best method to determine clout in open-source community!
     
  • Total Repositories * Total Followers
    
    
  • Pretty easy! However, getting data is a bit trickier, requires several asynchronous REST API queries.
     
  • Complex orchestration of the Promise native API (or even async/await or callbacks).

Request all the APIs!

GraphQL to the rescue

  • As data queries go, still pretty reasonable.
     
  • Still very hard to read/follow due to all
    asynchronous request running in parallel.

     
  • Getting information required from 10 followers
    alone adds up to 31 REST API queries.
     
  • Means we easily hit the Github hourly rate limit.

GraphQL Playgrounds

  • In-browser IDE's for exploring GraphQL.
     
  • Often ships with GraphQL library you are using.
     
  • Most well known is GraphiQL, GraphQL Bin and Altair.
     
  • Github has playground built on top GraphiQL.
     
  • Gatsby (that we will look at later) also has a playground built on top of GraphiQL.

'Hello World!'

"A 'Hello, World!' program generally is a computer program that outputs or displays the message 'Hello, World!'. [...] it is often used to illustrate the basic syntax of a programming language and is often the first program that those learning to code write. A 'Hello, World!' program is traditionally used to introduce novice programmers to a programming language.”


- "Hello World!" program
Wikipedia

The GraphQL Query

"In its simplest form, GraphQL is all
about asking for specific fields of objects


- Fullstack GraphQL
Julian Mayorga (Developer at GraphCMS)

Client‐specified queries

"These queries are specified at field‐level granularity. In the majority of client‐server applications written without GraphQL, the server determines the data returned in its various scripted endpoints. A GraphQL query, on the other hand, returns exactly what a client asks for and no more.”


- GraphQL Working Draft (July 2015)

Release the Queries!

Down to business

  • Let's start with Pokéapi, an endpoint that let’s you query ‘ all the Pokémon data you’ll ever need’.
     
  • Exposes entire Pokedex through GraphQL endpoint.
     
  • Let’s say that we want to determine the average weight of Pikachu’s final evolution.

Spoiler

It's Raichu and his average weigth is 29.5kg.

Queries as instructions

  • In short: queries are little maps in the form of Strings.
     
  • A GraphQL server uses these strings to navigate and find all the required data in a single round-trip.
     
  • Queries are so central that if you do not specify an action, GraphQL assumes that you are doing a Query.
     
  • GraphQL as a DSL for everyday life.

Other instructions

Query Concepts

  • Fields (asking for fields from object-like structure)
     
  • Arguments (optional information for a Field)
     
  • Aliases (naming results, useful when same Field)
     
  • Fragments (abstracting parts of a Query away)
     
  • Variables (pass data through variables into Query)
     
  • Directives (add conditional logic to Query)

Advanced Concepts

  • Mutations (allow changing of data through GraphQL)
     
  • Subscriptions (listens for changes on the server)

Shoutouts!

  • All the Codebridge Newlands community of volunteers that see our shared interest in
    technology as a force that brings us together.
     
  • All my friends in the #tech-for-good channel
    on the ZA Tech Slack workspace.
     
  • OpenUp for encouraging me to share the
    GraphQL work I've done Khetha
     
  • New Media Labs for sponsoring transport and snacks!

 

 

Get in touch

 

 

GraphQL for Front-end Developers

By Schalk Venter

GraphQL for Front-end Developers

A (hopefully!) easy guide for front-end developers interested in getting started (and avoiding common pitfalls) learning GraphQL.

  • 1,353