GraphQL — A Query Language — Part 1

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

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 .

I learned that you can install more than 1 node package in 1 command. For example we need to install Apollo Server and GraphQL. Install them both with terminal command: npm i apollo-server graphql .

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):

server/index.js

Write the schema.js file (directly from the Apollo Docs here):

server/schema.js

Adding type definitions to schema.js:

server/schema.js

Back in the index.js file, add the call to the server at the bottom of the file:

server/index.js

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)):

package.json

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:

GraphQL Playground

You can view the schema in the playground:

Playground schema

Or you can view the docs:

Playground 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 .

dataExplore/earthquakeFetch.js

Run this file, and make the fetch by terminal command: node dataExplore/earthquakeFetch.js .

Response Data for earthquakeData.features[0]

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 .

server/datasources/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:

server/index.js

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):

server/index.js

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; )

server/resolvers.js

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:

GraphQL Playground at localhost:4000
  1. Full-Stack Apollo GraphQL with React and Node | willjs3 | “https://www.youtube.com/watch?v=VjXb3PRL9WI
  2. What is GraphQL | Red Hat | “https://www.redhat.com/en/topics/api/what-is-graphql
  3. GraphQL | “https://graphql.org/
  4. Apollo | “https://www.apollographql.com/docs/
  5. What is GraphQL | LevelUpTuts | “https://www.youtube.com/watch?v=VjXb3PRL9WI
  6. GraphQL Explained in 100 Seconds | Fireship | “https://www.youtube.com/watch?v=eIQh02xuVw4
  7. Full Stack GraphQL with Apollo, Meteor and React| LevelUp Tutorials | “https://www.leveluptutorials.com/tutorials/full-stack-graphql-with-apollo-meteor-and-react

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Osha Groetz

Osha Groetz

93 Followers

Software Engineer. A new addict of ReactJS & Javascript, CSS & APIs, with a little dabbling in Ruby, Ruby On Rails…