CRUD operations using Apollo-GraphQL

Srikar Gvs
8 min readMay 30, 2021
Image credit: Apollo

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!!

Excited!!

Contents

  1. What is a REST API?
  2. What is GraphQL?
  3. GraphQL Glossary.
  4. Benefits of GraphQL
  5. Introduction to Apollo.
  6. 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.

GraphQL Glossary

Before we start writing the code, we should be knowing few of the important design concepts of GraphQL,

  1. 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.
  2. Scalar Types: Int, Float, String, Boolean, and ID (unique identifier of each object).
  3. Query: A Query type consists of fields using which clients can ask for data from the server. It defines READ part of the schema.
  4. 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.
  5. 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

  1. It Avoids over fetching.
  2. Uses single endpoint to oversee multiple operations over multiple devices (Web or Mobile)
  3. Needs no extra documentation. Its self-documented.
Diff Methods: GraphQL vs REST

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:

  1. Apollo Gateway and federation.
  2. Caching your GraphQL API using frameworks like Redis etc.
  3. 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!!

Image Source: Google

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.

As I mentioned, I am using Node.JS as my backend and npm as my package manager.

Hope you shall code along with me.

Prerequisites

  1. Node.JS version ≥ v8.x
  2. npm version ≥ v6.x
  3. Any cool IDE for better coding experience!

Folder Structure

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.

  1. npm init -y
  2. npm install apollo-server
  3. npm install graphql
  4. 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.

Tasks.json

It’s an array of tasks with id, title and completed status as properties.

Server.js

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.

Schema.js

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.

Resolvers.js

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

  1. 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.
  2. 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.
  3. 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.

Utils.js

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 sreekarsai19@gmail.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.

--

--

Srikar Gvs

I am a technical enthusiast who loves to build software applications at an enterprise scale.I engage myself reading books,watching thrillers in my free time.