Learning GraphQL can feel daunting at first. I remember when I started - my head was spinning with all the new concepts of schemas, resolvers, mutations and more! But stick with it, because GraphQL is so worth learning. Let me walk you through everything step-by-step.
What is GraphQL?
GraphQL is a query language that was developed internally by Facebook in 2012 before being publicly released in 2015. I like to think of GraphQL as a communication protocol between client and server. The client can request exactly the data it needs from the server, and the server specifies how clients can request data through a schema.
My friend Tanishq explained it to me like this:
With GraphQL, the client is in charge! It asks for the data it needs. Think of the GraphQL server like a waiter, and the client like a customer ordering food off a menu. The client can order exactly what they want from the menu, in a single request.
This allows the client to avoid overfetching and underfetching data like what can happen with REST APIs. The data requirements are more predictable.
Why Use GraphQL?
There are a few key reasons GraphQL improves over traditional REST:
-
Flexible Queries
The core idea of GraphQL is that the client can query for the exact data it needs, avoiding both overfetching and underfetching.
For example, say you have a
books
endpoint that returns all book fields. If your app only needs the titles, it wastes bandwidth to fetch everything. With GraphQL, you could write a query to just get the titles. -
Strong Typing
GraphQL schemas provide excellent documentation of what queries are possible with strong typing. My friend Sai who writes React apps (like me) loves this:
I never have to wonder what data I can fetch or what parameters to pass. The GraphQL schema tells me everything I need to know without guesswork.
-
Powerful Evolutability
Changing REST API endpoints often requires versioning to avoid breaking changes. With GraphQL, you can smoothly add new fields and types without needing major version updates. Existing queries keep working as-is.
-
Unified API
GraphQL serves as a unified interface between the client and varying backends like databases, microservices, REST APIs and more. This simplifies the client.
-
Developer Experience DX
The GraphQL ecosystem offers some amazing developer tools like GraphiQL for interactive exploration of schemas, improved error messaging, and auto-generated documentation.
Core GraphQL Concepts
To use GraphQL effectively, you'll need to understand its core concepts:
-
Type System
This defines the different object types available, with fields on each type. For example, a
Book
type might havetitle
,author
andpages
fields. -
Query Language
This lets the client request data by specifying fields. You can query for just the fields needed and join data across types.
-
Resolve Functions
These functions are provided by the developer to fetch real data for each field. They plug into databases, services, etc.
-
Schema
The schema defines all the types, fields, relationships and operations available. It's like the API contract between client and server.
-
Mutations
Along with queries, mutations allow modifying data by creating, updating or deleting records. The schema defines available mutations.
A Simple Query Example
Let's look at a very simple schema:
type Query {
hello: String
}
This defines a root Query
type with one field, hello
, that returns a String
.
Here is a query that a client could make against this schema:
{
hello
}
When executed, the server would respond:
{
"data": {
"hello": "Hello world!"
}
}
Already from this simple example, you can see GraphQL's power:
- The schema serves as documentation for what queries are allowed.
- The client requests only the specific data fields they need.
- The response data maps perfectly to the shape of the query. ## Fetching Objects and Fields
Let's look at a more advanced schema:
type Query {
books: [Book]
}
type Book {
title: String
author: String
}
This defines a Book
type with some fields, and the root Query
that returns a list of Book
objects.
The client could query this like:
{
books {
title
author
}
}
The server would respond with:
{
"data": {
"books": [
{
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"title": "The Catcher in the Rye",
"author": "J.D. Salinger"
}
]
}
}
This allows the client to select only the specific Book
fields needed.
Arguments and Variables
Adding arguments to a field allows passing parameters:
type Query {
book(id: ID): Book
}
Now the book
field takes an id
argument to query a specific book.
We could call it like:
{
book(id: "1") {
title
}
}
Variables let you extract out the dynamic arguments for reuse:
query GetBook($bookId: ID) {
book(id: $bookId) {
title
author
}
}
And pass in the variable value:
{
"bookId": "1"
}
Mutations
Along with queries, GraphQL includes mutations to modify your data:
type Mutation {
addBook(title: String, author: String): Book
}
This provides an addBook
mutation that takes a title and author and returns the new Book
object.
A client could call it like:
mutation {
addBook(title: "Moby Dick", author: "Herman Melville") {
title
}
}
GraphQL Clients
There are many client options for calling GraphQL APIs from different languages:
- JavaScript: Apollo, Relay, urql
- Java/Kotlin - Apollo Android
- Swift - Apollo iOS
- Ruby - graphql-client
- Python - Graphene, Apollo-Python
- Go - graphql-go
- C# - GraphQL .NET
These clients handle query parsing, network handling, caching and other features required to call a GraphQL API.
GraphQL Servers
On the server, you need a GraphQL library to provide a runtime for executing queries against your schema. Some options include:
- JavaScript: Apollo Server, GraphQL Yoga
- Java: graphql-java
- Ruby: graphql-ruby
- Python: Graphene, Apollo-Python
- Go: graphql-go
- .NET: GraphQL .NET
The server parses incoming queries, validates them against the schema, executes by calling your resolve functions, and returns the response.
Learn with Great Resources
The best way to learn GraphQL is by writing some queries yourself! I recommend starting with the official GraphQL docs:
Some other excellent resources I used when learning:
How to GraphQL -> By Prisma
YouTube
The GraphQL community is also extremely friendly and helpful if you get stuck! Don't be afraid to reach out.
I hope this guide gave you a great introduction to GraphQL. There are a lot of new concepts, but just take it slow and try writing some examples. Over time, it will all come together. Have fun unleashing the power of GraphQL!
⚡⚡Happy Coding ⚡⚡
Top comments (0)