Apollo GraphQL Server From Scratch

Taran
codeburst
Published in
7 min readSep 6, 2020

--

What is GraphQL

GraphQL is a query language and a server-side runtime that is used to request data from the server. The first thing that comes to mind when hearing the term “query language” is SQL. Just as SQL is used for querying databases, GraphQL is a bit like SQL but for querying web APIs as it eliminates the need to repeatedly develop or change existing end-points. GraphQL also enables the client/front-end to retrieve exactly the data they have requested and no more. This means that, within a single request of GraphQL, you can traverse from the entry point to the related data (whereas in RESTful API you have to call multiple endpoints to fetch similar results).

The following example will help you to understand this better. Let us consider an object person which has the attributes name, age, email, and contactNumber. Suppose the front-end only needs the name and age of the person. If we design a REST API, the endpoint will look like api/persons, which will end up fetching all the fields for the person object. The issue arises here because there is no easy way to communicate that I am interested in some fields and not others (which causes REST API to over fetch the data).

GraphQL query given below will retrieve the value for name and age fields only for the Person Object.

// query
{
persons {
name
age
}
}

The result of the above query will contain exactly the fields we have requested as shown below

// result
{
“data”: {
“persons”: [
{
“name”: “Alex”,
“age”: 25
},{
“name”: “Mac”,
“age”: 35
}
]
}
}

Tutorial — GraphQL using Apollo Server

Pre-Requisites

  • A computer running Linux, macOS, or Windows with node.js installed
  • A web browser
  • A code editor (in this tutorial I am using Visual Studio Code)

GraphQL Apollo Server from scratch

Let's expose GraphQL API over the HTTP using the Apollo Server. For this we must first create a folder with the name server. Then create a file, with the name package.json, in the newly created…

--

--

I am a Full stack developer. I enjoy learning and building new skills, and sharing what I’ve learned.