Skip to main content

Class 1: Introduction to GraphQL

Learn what GraphQL is, why to use it, and how it differs from REST.

Duration: ~10 minutes | Difficulty: Beginner | Prerequisites: None


What is GraphQL?

GraphQL is an open-source query language for APIs and a server runtime for fulfilling those queries.

REST often makes you call several endpoints to gather related data, which is under-fetching, or return large JSON documents full of fields you never use, which is over-fetching. GraphQL fetches exactly the data you need, in a single request.

GraphQL vs REST

GraphQL at a Glance
  • Query language for APIs (not databases)
  • Single endpoint for all operations
  • Client specifies exactly what data it needs
  • Server returns JSON matching the query shape
  • Strongly typed schema as the contract

GraphQL isn't tied to any specific database or storage engine - it sits in front of your existing code and data.


The Core Idea

GraphQL comprises two parts:

  1. Query Language - specific language that enables the API client to specify their intent, such as what data to query, which action to perform...
  2. Server Runtime - executes above requests against a schema

Request Flow

We will talk a lot about this later, but as an overview, the usual flow goes something like:


GraphQL vs REST

As most developers are already familiar with REST APIs, I find it easiest to explain GraphQL just by drawing a parallel with a similar REST API.

The Scenario

Let's imagine we want to build a website showing some info about movies. We want to display a page that lists the movie title, its release year, some reviews, and the awards it has received or been nominated for.

REST Approach

With REST, we typically need multiple requests:

REST Problems
  • Multiple round-trips to the server
  • Over-fetching - response includes unused fields
  • Under-fetching - need separate endpoints for related data
GET /movies
[
{
"id": 1,
"title": "Star Wars: Episode IV",
"genre": "Adventure Epic",
"releaseYear": 1977,
"durationMinutes": 121,
"originalTitle": "Star Wars",
"summary": "Luke Skywalker joins forces with a Jedi Knight..."
}
]

GET /movies/reviews?movieIds=1
[
{
"id": 111,
"movieId": 1,
"rating": 9.5,
"title": "Visually stunning sci-fi",
"comment": "The story starts slow but really pays off.",
"userId": 42,
"createdAt": "2024-06-12T14:23:00Z"
}
]

GET /movies/awards?movieIds=1
[
{
"id": 111,
"movieId": 1,
"name": "Oscar",
"category": "Best Picture",
"status": "NOMINATED"
}
]

GraphQL Approach

With GraphQL, one request gets exactly what we need:

GraphQL Benefits
  • Single round trip
  • No over-fetching - only requested fields returned
  • Client controls the exact shape of the response

Query:

query MoviesWithReviewsAndAwards {
movies {
title
releaseYear
reviews {
rating
}
awards {
name
category
}
}
}

Response:

{
"data": {
"movies": [
{
"title": "Star Wars: Episode IV",
"releaseYear": 1977,
"reviews": [
{ "rating": 9.5 },
{ "rating": 9.8 }
],
"awards": [
{ "name": "Oscar", "category": "Best Picture" }
]
}
]
}
}

Notice that the response shape mirrors the query shape exactly.


Key Differences

AspectRESTGraphQL
EndpointsMultiple (one per resource)Single (/graphql)
Data shapeServer decidesClient decides
FetchingOften over/under-fetchesPrecise fetching
VersioningURL versioning (/v1/, /v2/)Schema evolution
DocumentationExternal (OpenAPI, etc.)Built-in (introspection)

The Schema (The Contract)

A GraphQL service is created by defining types and their fields in a Schema, and we'll go through it in detail in a dedicated class. Still, for now, this is how a Schema might look for the example service we defined above.

type Movie {
id: ID!
title: String!
releaseYear: Int!
reviews: [Review!]!
awards: [Award!]!
}

type Review {
id: ID!
rating: Float!
comment: String
}

type Award {
id: ID!
name: String!
category: String!
status: AwardStatus!
}

enum AwardStatus {
NOMINATED
WON
}

type Query {
movies: [Movie!]!
movie(id: ID!): Movie
}

Don't worry if this looks unfamiliar to you - we'll explore schemas in depth in the next class.


When to Use GraphQL

GraphQL excels when:

  • Multiple clients need different data shapes (web, mobile, etc.)
  • Complex UIs require data from multiple sources
  • Rapid iteration demands flexible APIs
  • Network efficiency matters (mobile, slow connections)

GraphQL may not be the best fit when:

  • Simple CRUD with a few clients
  • File uploads are the primary use case (GraphQL as a specification doesn't support file upload)
  • Caching at the HTTP level (CDN) is critical

Summary

ConceptDescription
GraphQLQuery language for APIs with a server runtime
Single endpointAll operations go through one URL
Client-drivenClients specify exactly what they need
SchemaTyped contract defining the API
Response shapeMirrors the query structure

What's Next?

In the next class, we'll explore Class 2: A Brief History of GraphQL - how it was created at Facebook and evolved into a mainstream API technology.