Hey you there! Hope this post finds you in good health :)
This is my first ever article on medium and I wanted to start this with a BANGGGG!!!
It's been quite a long time; I have been thinking how to start my technical blogging journey with medium and suddenly APOLLO GRAPHQL hit me.
For a technical enthusiast like me I strongly felt exploring and sharing my knowledge on industry leading technologies will be a wonderful experience to start with. Apollo GraphQL is one such tech stack, that made me to fall in ❤ with it soon.
So, with no further delay let's begin our journey together!!
- What is a REST API?
- What is GraphQL?
- GraphQL Glossary.
- Benefits of GraphQL
- Introduction to Apollo.
- CRUD operations using apollo server.
Refreshing RESTful API concepts in brief
As you might already be knowing REST (REpresentational State Transfer) is a well-known and well-reputed software architectural style used for developing Application Programming interfaces (APIs — briefly) that establishes a communication channel between two different web applications using HTTP protocols.
Let's say you are hungry and want to order delicious food. You will quickly open any one of the food apps available and start searching for your dish. The moment you start typing on the search bar, client (your application basically) will start searching their inventories hosted on various servers (databases for example) using the APIs, may be a RESTful one or a GraphQL service :)
RESTful API majorly uses four HTTP verbs or methods you can say, while interacting with data providers.
What is GrapqhQL?
Let's hear it out from GraphQL.org
GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.
Key point to be noted in the above definition is - “gives clients the power to ask for exactly what they need and nothing more.”
To make you understand better let's say you need to show only the username and email id of the current user on their profile page of any account-based application.
In a traditional RESTful API call you might be requesting a user's service which returns you with the entire user data including mobile number and address that you don't need in this case.
This can be avoided using a GraphQL API. By using a simple Query call you can get what you need. Also, a Mutation call to insert/update/delete the data. We shall be seeing this in action soon.
Facebook Inc. developed GraphQL as an internal project initially, which they later made it as an open source. It uses the concepts of Graph theory.
Before we start writing the code, we should be knowing few of the important design concepts of GraphQL,
- Schema: It’s a blueprint of your data graph structure. Schema helps clients to understand what types are available and how it can read and write data.
- Scalar Types: Int, Float, String, Boolean, and ID (unique identifier of each object).
- Query: A Query type consists of fields using which clients can ask for data from the server. It defines READ part of the schema.
- Mutation: Fields defined in the Mutation type lets the clients to write the data back to the server. It manages CREATE, UPDATE and DELETE operations. Subscription is another type available which is currently out of this blog’s context.
- Resolvers: Every field defined in a schema type (Query, Mutation and Other Custom Types) is intended to return a particular data based on the inputs provided. Resolver is one such function that helps the schema fields to resolve the data by using parent, args, context and info arguments passed to it by the GraphQL server.
If you want to deep dive into these concepts, click here!
Benefits of GraphQL
When it comes to benefits, I personally feel GraphQL beats REST.
Few of the benefits are
- It Avoids over fetching.
- Uses single endpoint to oversee multiple operations over multiple devices (Web or Mobile)
- Needs no extra documentation. Its self-documented.
Introduction to Apollo
Apollo is an ecosystem and industry standard open source GraphQL implementation that enables developers to build APIs in a faster approach using Apollo server and for client applications (like React etc.) to communicate with the server, Apollo Client does the job. Data graph layer provided by Apollo helps your modern application to get connected with Cloud.
Some of the cool features of Apollo Server are:
- Apollo Gateway and federation.
- Caching your GraphQL API using frameworks like Redis etc.
- Integrations for Express, Azure and AWS lambda. It can also be a standalone and run by itself.
Shall be discussing about Apollo-client in detail later in my upcoming blogs.
Meanwhile learn more about Apollo here.
Wow!! That's a lot of talking. It's time to get our hands dirty!!
Uh Oh!! Hand hygiene is important. Kindly sanitize them frequently :)
CRUD operations using apollo server — THE CODE
Here we are trying to create, read, update, and delete a To-do task list hosted as a JSON object on our apollo-grapqhl server. We will be using node’s fs module for file read/write operations.
Hope you shall code along with me.
- Node.JS version ≥ v8.x
- npm version ≥ v6.x
- Any cool IDE for better coding experience!
npm commands to install required packages
Open the root directory (here apollo-server-demo) in the terminal to execute below commands one after the other or even as a single command.
- npm init -y
- npm install apollo-server
- npm install graphql
- npm install nodemon(ignore if its globally available in your node modules)
Files that I am going to share below will be created under src folder.
It’s an array of tasks with id, title and completed status as properties.
Server.js is the entry point of our application. It imports task array object from tasks.json and passes it as data sources to every field resolver. TypeDefs is your schema in other words and resolvers will be discussed soon. All these objects are passed to instantiate new Apollo Server class which will be firing up and listening on port 4000 of web server. Accessing it will open a brand new GraphQL Playground UI for all your client-server interactions.
Remember, I mentioned Graphql APIs are self-documented. Click schema and docs tabs on your playground which opens your pre-defined schema with types for better readability. Also, playground is enabled with autofill options for the types and fields declared. You also have the privilege to choose among the fields of the types that you need. This avoids over fetching.
You might have also noticed that all these operations will be performed using single endpoint (http://localhost:4000) here! That's the beauty of GraphQL.
All the types in this schema file have already been discussed above apart from Input type. Input type defines the variables that a field resolver would expect from the client.
Array of Tasks is represented as type [Task] and if at all field value shouldn't be null, it gets appended with a ‘!’.
Resolver receives the input types from the client as query variables and responds back with the data as a return type object after performing necessary commands.
fieldName: (parent, args, context, info) => data;
Query resolvers (READ):
Tasks resolver expects tasks json object passed as data source and returns it back when its queried using client (playground here)
Mutation Resolvers (CREATE/UPDATE/DELETE):
Mutation type in our schema is defined with create, update, and delete tasks fields. Let's see what they are intended to do
- createTask expects a new task object from the query variables and master tasks list as data source. If the new task doesn't exist in the master list, it shall append it to list and writes back the data to the master JSON file. Also, it returns new task along with the id as a response to the mutation call. If the task already exists, it will throw a duplicate error.
- updateTask needs an id to search for the task in master task list and update the completed status of that task, provided as query variables. Again, these updates shall be written back to the master JSON file and returned as a response to the mutation call.
- deleteTask follows the footsteps of updateTask resolver, just that it deletes the task instead of updating it, which matches the incoming id as query variable. After deleting the matching task, it returns updated master list as a response to the mutation call. It does updates the master JSON file as well.
Errors will be thrown separately in case of ids mismatch.
The decisive moment — TESTING OUR APOLLO GRAPHQL API USING PLAYGROUND.
READ ALL THE TASKS (Query):
All the tasks from the json file shall be returned for the above query call.
CREATE A TASK(Mutation):
A new singing task has been passed as query variable and same can be seen on the response window with id field appended back by the resolver.
UPDATE A TASK BASED ON ID(Mutation):
Task from the master list that matches the id is returned with the new completed status.
DELETE A TASK BASED ON ID (Mutation):
Task with id 1 has been deleted from the master list and rest of the list is returned.
Hurray!!!! We have successfully designed our first ever GraphQL API using Apollo sever :)
Checkout the complete code here.
Hope I have kept you engaging throughout the blog by exploring various concepts of REST and APOLLO GRAPHQL.
Thanks a ton for reading. Feel free to reach out to me over my email address email@example.com or via LinkedIn
If you want to encourage me, please do clap :)
Suggestions or feedbacks are most welcomed.
See you in my next blog. Until then enjoy learning.