Introduction to GraphQL
History
- In 2012, Facebook decided to rewrite their mobile apps.
- Originally, the apps were just web views.
- Wanted native implementations for iOS and Android.
Problems
Up until this point, the News Feed data had been served as HTML. And there was no API endpoint available.
Developers grew frustrated at the amount of queries required to get the data required for different views.
This frustration led to the development of GraphQL.
What is GraphQL?
- Applications requests data in specific structure.
- The JSON response comes back in that structure.
{
github {
user(username: "gaearon") {
id
login
company
}
repo(ownerUsername: "gaearon" name: "redux"){
id
name
branches(limit: 1) {
name
}
}
}
}
{
"data": {
"github": {
"user": {
"id": 810438,
"login": "gaearon",
"company": "Facebook"
},
"repo": {
"id": 36535156,
"name": "redux",
"branches": [
{
"name": "core-enhancer"
}
]
}
}
}
}
That's cool.
But how does this work?
Application protocol
GraphQL is just a string sent from the client to be processed by the server.
There are many server implementations:
Check out the repo chentsulin/awesome-graphql for more!
Aliases
Suppose we wanted to query a couple users from GitHub
{
github {
gaearon: user(username: "gaearon") {
id
login
company
}
substack: user(username: "substack") {
id
login
company
}
}
}
{
"data": {
"github": {
"gaearon": {
"id": 810438,
"login": "gaearon",
"company": "Facebook"
},
"substack": {
"id": 12631,
"login": "substack",
"company": "cyberwizard institute"
}
}
}
}
Notice how the "user" field has been renamed
Fragments
It's possible to group common fields in a query
{
github {
gaearon: user(username: "gaearon") {
...GithubUserFragment
}
substack: user(username: "substack") {
...GithubUserFragment
}
}
}
fragment GithubUserFragment on GithubUser {
id
login
company
}
{
"data": {
"github": {
"gaearon": {
"id": 810438,
"login": "gaearon",
"company": "Facebook"
},
"substack": {
"id": 12631,
"login": "substack",
"company": "cyberwizard institute"
}
}
}
}
Introduction to GraphQL
By Tony Gaskell
Introduction to GraphQL
- 1,698