Introduction
While REST API's are still extremely popular, there's a new kind of API gaining popularity at a very high pace: GraphQL. GraphQL is a data query and manipulation language developed by Facebook. Just like REST surpassed SOAP as the de facto standard, it's expected that GraphQL will do the same to REST. While both REST and GraphQL use the HTTP protocol and JSON as data structure, REST is based on community conventions and best practices, whereas GraphQL is strict and strongly typed.
Why replace REST?
The main downside of REST is that for more complex data structures, it becomes nearly impossible to have endpoints that follow the REST protocol without making a ton of request. Imagine the following data structure: you have a user, which can have friends. These friends work for different companies and have specific positions in that company. If you would want to get all the roles and positions of the users' friends, you could do the following things:
-
You make a lot of separate HTTP requests to get the necessary information.
/users/23/friends
/users/1/companies/
/users/1/positions/
/users/2/companies/
/users/2/positions/ -
You make a very specific endpoint
/users/23/friends/companies/users/23/friends/positions
-
You break from a REST-ful endpoint
/users/23/friends_with_companies_and_positions
To solve this, GraphQL has a different approach of dealing with data models: rather than looking from the viewpoint of a user, we look at the data in its entirety. In other words, we make a graph (as in a data structure of nodes and edges) of all the data and its connections. You will see in the next chapter that this makes it a lot simpler to deal with more complex data models.
Setting up a GraphQL API
Before we can start fetching data in our application, obviously we need a GraphQL API. There are several public GraphQL APIs to experiment with, but for TaskFlow we are going to set up our own mocked API. We are going to use json-graphql-server
for this. First, install the package:
npm install -g json-graphql-server
You can use the db.json
file you've created earlier, but make sure the keys aren't hyphenated (so you might have to change time-entries
to timeEntries
). To start the GraphQL server on localhost port 3333, run:
json-graphql-server db.json --p 3333
You can now visit http://localhost:3333 to check out the GraphiQL IDE, a useful tool to explore your data (try using the Documentation Explorer on the right) and test queries.
For fetching all time entries for example, you can use the following query:
query GetTimeEntries {
allTimeEntries {
id
activity
client
endTime
startTime
}
}
GetTimeEntries
is the name we gave to that query, but you can choose another one to suit yourself. It's also possible to leave the query unnamed, but this practice is discouraged.