Objectives
Discover how to leverage GraphQL for API querying and establish a GraphQL server utilizing Apollo.
Tech Stack
Setup the starter project
I will use the starter project provided by Apollo for this blog post.
First, clone the repository:
git clone -b typescript https://github.com/apollographql/odyssey-lift-off-part1
In this blog post, we will only utilize the backend part.
Then, install all the required npm packages:
cd server && npm install
Intro to GraphQL
What is GraphQL
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. To learn more about GraphQL, I recommend you to read the GraphQL official documentation.
What is GraphQL schema
The GraphQL schema acts as a blueprint for the data available in the API and describes how clients can interact with it. It outlines the types of data that can be queried and manipulated and the relationships between them. The schema provides a unified interface for clients to request specific data requirements and receive predictable responses. To learn more about GraphQL schemas, I recommend you to read the GraphQL official documentation about Schemas and Types.
Build our schema
To get started with our schema, we'll need a couple packages first: @apollo/server, graphql and graphql-tag.
npm install @apollo/server graphql graphql-tag
A schema with three types: Query, User, Address
These are the data types we'll be able to retrieve from the backend. To learn more about schemas and types, check out this documentation.
What is gql?
It's a tagged template literal, used for wrapping GraphQL strings like the schema. This converts GraphQL strings into the format that Apollo libraries expect when working with operations and schemas, and it also enables syntax highlighting.
Populate mock data
Here we utilize this JavaScript package: casual to generate mock data.
Create a GraphQL server
The purpose of building the backend
Let's walk throug the code:
Apollo Explorer
What is Apollo Explorer?
Also known as The GraphOS Studio Explorer. It is a powerful web IDE for creating, running, and managing GraphQL operations.
Start running your server
npm run dev
You will find the server running on http://localhost:4000/. And you should see something like this on the browser:
In the Apollo Explorer, the middle panel allows you to structure your query according to your preferences in order to obtain the desired output. The right panel shows the result of the query. The left panel shows the schema of the server. It is a great tool to use when you are developing your GraphQL server. This is my top two used tools besides Postman for API development.
To learn more about how Apollo Explorer works checkout their documentation.
Conclusion
Source