What Is GraphQL?
February 06, 2019
(This is Part 1 of a series: Part 2, Part 3, Part 4)
What is GraphQL? To answer that, in this short video we compare a REST API to a GraphQL API using a concrete example so you see how they match up.
In summary, GraphQL offers a more flexible approach for working with APIs:
GraphQL lets you query your data and get exactly what you want. Nothing more, nothing less. So if you only want three fields of a resource, then you send your API a GraphQL query specifying those fields and the result is a JSON document that contains only the three fields you asked for. No more transferring stuff you don’t need over the network, parsing it in the frontend, only to then ignore it.
{
place(name: "Spanish Villa") {
location
description
image
}
}
With GraphQL you can query multiple related resources in a single request. In other words, you can query across relationships and get all the data you need in one fell swoop. No more multiple endpoints.
{
place(name: "Spanish Villa") {
location
description
image
bookings {
startDate
endDate
}
}
}
GraphQL also gives you the flexibility to query related objects and get back a response that’s exactly the same shape as the query itself. No more multiple requests that either over- or under-fetch data you want.
{
place(name: "Spanish Villa") {
location
description
image
bookings {
startDate
endDate
user {
name
email
}
}
reviews(last: 3) {
stars
comment
user {
name
avatar
}
}
}
}
So, what is GraphQL? Well, it’s an expressive query language for your data which you can think of as a graph of related objects and their fields.
In addition to queries, GraphQL also supports mutations for changing data and event-based subscriptions for delivering live feeds of data. But those are topics for the next video.
Unpack a Full-Stack GraphQL App Layer-By-Layer
Learn what it takes to put together a full-stack GraphQL app using Absinthe, Phoenix, and React in our Unpacked: Full-Stack GraphQL course. No need to piece together solutions yourself. Use this application as a springboard for creating your own GraphQL apps!