Starting with GraphQL? Here are some basics.

Deniz Jusufović
Codeart
Published in
7 min readOct 13, 2021

It seems that every day there is a release of new technology, claiming to be better, faster, or more efficient. And this is just one of them, but with a big difference. It was developed and introduced by Facebook, and in a short time period, it was adopted by big companies like Shopify, Instagram, Twitter, Airbnb, and many more, which makes us wonder if it’s really worth it, and should we invest our time and find out what all the fuss is about?

Let’s find out!

What is GraphQL actually?

GraphQL is an API standard that enables a more effective, stronger, and more flexible alternative to the REST. GraphQL enables a declarative fetching of data, where the client is able to specify the data he wants from the API. Thus instead of multiple API endpoints that return data with a fixed structure, the GraphQL server has only one endpoint and it returns only the data that is required by the client.

Very often the GraphQL is represented as a database technology which is wrong of course. It is just a Query Language for APIs (hence the name GraphQL), and not for databases.

Okay, so… How can I implement it?

You have multiple ways of implementation actually. One of them, and mostly used, is by setting up a GraphQL Server.

GraphQL Server is a server-side implementation that exposes the data and acts like a GraphQL API, where the client application can send requests and fetch data. The positive is that the client application can be a SPA, CMS, mobile app, or anything else. For example, if we have a MySQL database and we want to open the data for a React application, we can create a GraphQL server that will enable the data fetching indirectly through it.

You can also set up GraphQL on the client-side, but it is highly recommended to be a server-side implementation. Now once we start the GraphQL server, it will expose a single endpoint that you hit with your queries. By default, that endpoint is /graphql, but of course, you can name it anything you want.

Wait, one endpoint only? Are there any similarities with REST?

The short answer is yes. The longer one is that the similarities are bigger than one can imagine. You are still required to set the “endpoints” on the back-end layer, set the queries, mutations, resolvers, etc. They are only abstracted differently.

So the idea of GraphQL is not to simplify the endpoints but to move the specification from the URL to the query parameters. On the opposite side, we know that abstraction doesn’t always lower the complexity, and you can see that if you ever get to debug an overly abstracted code.

So are there any advantages of using it then?

Of course, that’s why we’re here! Here they come:

Only one endpoint. As opposed to REST APIs, in GraphQL we have only one endpoint for sending all of our queries.

Prevents over and under fetching. Often in the REST API’s we are facing over and under fetching.
For example, if we need a list of user names, there is a huge chance that there is only one endpoint /users, where we can fetch all the users with all of their data, and just… not use it.

There are no dependent requests, where we would wait for series of requests to fetch the data we need.

Clean and easily readable. As we will see later.

Great for legacy APIs

Great! Finally a flawless technology!

Well.. not really. Having a flawless standard, service, or technology in general, is really just a dream we developers have. Let’s see what kind of issues you are going to face.

Writing complex queries is still the developer’s job. It won’t just magically give you all the data you need without a few of your sweatdrops.

You will need external libraries so you can ensure the correctness of your queries. You will also need the library for easy managing of the client-side code.

Caching. So if you have a REST API you know the structure and data you get from a specific endpoint, and you can easily decide to cache a specific resource. It is much more challenging to cache a specific resource if you don’t know what it is, right?

Let’s take a sneak peek into a simple graphQL query

We can see that a simple GraphQL query consists of an operation type, endpoint, and the fields that you wish to retrieve. Pretty neat right?

How will the GraphQL server understand my queries?

First of all, every GraphQL server needs a schema. That is the place we define the possibilities of the server. Same as in a database, a schema describes the structure and the types that the API can provide. A GraphQL schema consists of types, queries, mutations, and subscriptions. Let’s see what they are in little more details, shell we?

Types are considered a primary block in a GraphQL schema and they define the possibilities of the API and the types of data it can return.

Here’s an example:

type User {    id: ID!    name: String!    email: String!    age: Integer!}

The Query is a core part of the schema. It consists of queries that the API provides. You can imagine the queries as REST resources that receive arguments and return results.

type Query {    users: [User!]!    userById(id: ID): User}

As you can see in the example above, the query is the place where we just fetch the data, the changing of the data is done within another operation type.
The Mutation type allows us to actually make changes to the data on the servers. So that means that this is where we do the create/edit/delete operations.

type Mutation {    createUser(name: String!, email: String!, password: String!): User @create    updateUser(id: ID, email: String, password: String): User @update    deleteUser(id: ID): User @delete}

The Subscription type, on the other hand, allows us to return a stream of results with real-time updates, instead of just returning one result. They function as web sockets.

type Subscription {    newUser: User}

Schema done. Now implementation!

Okay, now that we saw how we can write our schema, let’s see how we can implement GraphQL.

Of course, the difficulty and complexity of implementation differ depending on your needs. In my opinion, implementing GraphQL within your application is a little bit easier than if you try to run a standalone GraphQL server.

Let’s say that you want to serve your GraphQL server directly from your application.

  • If you have an application written in Laravel, you can use this amazing library called Lighthouse, define your schema, and start executing your queries. What is nice about the Lighthouse framework is that it is optimized for Eloquent, so it uses the already existing models to execute optimized queries.
  • If you need a GraphQL library for a Django project you might want to give the package called Graphene-Python a try. You can take a look at this tutorial to help you set up GraphQL into your application
  • Maybe you have a VueJS application, and you need GraphQL integrated? No problem, Vue Apollo got you covered

If you are not thinking about serving GraphQL from your application, you have the option of setting up a raw GraphQL server with Node.js and Prisma.

  • Prisma is an open-source toolkit that supports automated generating of queries and automates a large part of the backend code that you would usually write to send database queries. It also supports sending queries through GraphQL, which is exactly what we need here.
  • You can find a step-by-step tutorial on how to set up a GraphQL server with Node.js and Prisma here.

Now because Prisma doesn’t support roles, it can not differentiate between logged and a guest user, it can not filter or transform data, we should set up a separate GraphQL where we would implement that logic.

Of course, the internet is full of information, tutorials, and pros-cons articles about GraphQL, but just as in any other new technology it is on you to investigate more by yourself and see if GraphQL is a real fit for your application before using it.

Summa Summarum

If the low bandwidth, overall performance, the size of the payload, or the legacy API support is taken into account, or maybe you are just facing constant change of client needs, using GraphQL just seems like the right choice. It does not look like GraphQL is going to make REST completely obsolete in the near future, but it sure is becoming one of the most used tools for creating APIs.

On the other hand, if you do not have a need to improve any of the things I mentioned above, instead of adding GraphQL that will just introduce additional complexity to your application, you might want to stick to your already working REST.

If you do your research properly and decide that GraphQL really is the right fit for your application, the results can be nothing but great!

--

--

Deniz Jusufović
Codeart
Writer for

Web development, Elasticsearch, Software Architecture