GraphQL — A Query Language — Part 1
Moving Away From REST API’s to Get Data From an API to Your Application
First thing to know: GraphQL is a specification (how it should work and look), not an implementation. There is no installing GraphQL, you implement it using a server library, a client framework like Apollo and playgrounds like GraphiQL or Graphcool to test out your queries.
GraphQL key points:
- server-side runtime
- fast, flexible, developer-friendly
- gives clients exactly the data they want/have specified, not the entire payload of data
- great relational queries — where all queries can be done in one query, no ‘over-fetching’²
- gives backend developers a type system to develop a schema for data
- strong data types reduce errors between client and server
- multiple urls to fetch data are discarded, instead there is now only a single entry point
- the response is still sent back as json
- the syntax can work with any programming language
- a consumer reads data with ‘type Query’
- a consumer mutates (create, update, delete) data with ‘type Mutation’
GraphQL: easier relational queries, self documenting. With GraphQL Server as soon as you start up the server, the API calls are made, the responses are received and processed and only the necessary data is put into the shape that we requested/specified for client-side queries. Unlike in RESTful API’s, now there is no wait time on the response, the response was already processed. The only wait time is for the data to be received from the cloud and presented.¹ Call and response are handled as soon as server has started running, making app faster.
Apollo: GraphQL system. Not as opinionated as Relay, and less code. Easy to get up and running with GraphQL
Apollo has 2 components: the Apollo Server, and the Apollo Client.
The Apollo server is what allows Apollo and GraphQL to work together and will become the client side API. Apollo replaces the API and mutations will replace server side routes and Meteor methods.
The Apollo Server creates a graph for your app, then allowing you to build an API to connect to this graph. The access to this graph is through 1 single GraphQL endpoint. Checkout Graph Theory here.
GREAT! LET’S BUILD
The build from here on out will be entirely from the notes I take going through willjw3’s FREE tutorial on Full-Stack Apollo GraphQL with React and Node — here. I can not take any credit on what’s to follow!
We are going to build a full-stack application with: Apollo, GraphQL & React.js, and Node.
Create the app directory and cd into it with terminal command: mkdir graphql-usgs-earthquake-api && cd graphql-usgs-earthquake-api .
Initialize the application with terminal command: npm init -y .
Open your app in your preferred text editor.
Set up 2 directories in the root of your applicaiton: Server & Client . Those terminal commands are mkdir server and mkdir client .
In the server folder, set up 2 files: index.js and schema.js . In the index.js file, code out the following (directly from the Apollo Docs here):
Write the schema.js file (directly from the Apollo Docs here):
Adding type definitions to schema.js:
Back in the index.js file, add the call to the server at the bottom of the file:
We’ll need to install Nodemon for automatic updating of server; type terminal command: npm i nodemon . Set up a custom script for running server in package.json file ((line 7)):
Your terminal should show you that you’re up and running successfully:
Also, if everything is connected successfully, if you navigate over to http://localhost:4000/ , you’ll see you have full access now to the GraphQL Playground:
You can view the schema in the playground:
Or you can view the docs:
Connecting the Data Sources
Let’s set up a file that will fetch directly from the USGS API to see what kind of data we are receiving back about earthquakes. This file will not be used in our application in the long run, it will just be a testing ground.
Install Node-Fetch: npm i node-fetch .
In the root folder, create a new folder: mkdir dataExplore . Set up a file in that folder called earthquakeFetch.js .
Run this file, and make the fetch by terminal command: node dataExplore/earthquakeFetch.js .
Create External API Data Source
Install the package Apollo REST Data Source: npm i apollo-datasource-rest . This package exports a (
RESTDataSource) class which is used for fetching data from a REST API and exposing it via GraphQL within Apollo Server.
Create a folder inside of the server folder and name it datasources . Inside datasources create a file earthquake.js .
Add Data Source to Apollo Server
Once the data source has been built, it has to be added to the Apollo Server.
Update the index.js file (inside the server folder) with the following code:
Directly from the documentation: Pass a
dataSources option to the
ApolloServer constructor. This option is a function that returns an object containing newly instantiated data sources. This connects instances of earthquakeAPI to our graph.
Write the Graph Resolvers
Graph Resolvers allow you to see the data in the GraphQL playground. What is a resolver? A resolver is a function that’s responsible for populating the data for a single field in your schema. When a client makes a query, the resolver is in charge of fetching the requested data from the correct data source.
A resolver returns one of either:
- Data of the type required (according to the resolvers corresponding schema field)
- A promise that fulfills with data of the type required
To start, we’ll update our server/index.js to require a resolver file and pass that module to the ApolloServer (lines 3 and 9):
Set up the resolvers file: In the server folder directly, make a new file: resolvers.js . (Note the resolver function signature is:
fieldName: (parent, args, context, info) => data; )
Great! Now let’s make sure everything is querying correctly. Head over to the GraphQL playground: http://localhost:4000/ . type in your query in the left hand column (note: control space will give you all avail options for queries), then hit the run button (center screen arrow), and your query, if all the code was implemented correctly, should populate in the right hand side of screen:
- Full-Stack Apollo GraphQL with React and Node | willjs3 | “https://www.youtube.com/watch?v=VjXb3PRL9WI”
- What is GraphQL | Red Hat | “https://www.redhat.com/en/topics/api/what-is-graphql”
- GraphQL | “https://graphql.org/”
- Apollo | “https://www.apollographql.com/docs/”
- What is GraphQL | LevelUpTuts | “https://www.youtube.com/watch?v=VjXb3PRL9WI”
- GraphQL Explained in 100 Seconds | Fireship | “https://www.youtube.com/watch?v=eIQh02xuVw4”
- Full Stack GraphQL with Apollo, Meteor and React| LevelUp Tutorials | “https://www.leveluptutorials.com/tutorials/full-stack-graphql-with-apollo-meteor-and-react”