GraphQL APIs or RESTful APIs
Tags: graphql, javascript
Published: 2021-07-26 16:38:29

There is no certain way to do things, and we can go on and on about which way is the proper way to do things or which has better advantages over the other. I think as far as you get your problem solved in an efficient and effective manner then it's quite the right way to do it. You will often hear people go on about this versus that, i'm not really interested in that, but rather let's see what each party brings to the tale and try to use that advantage in the right context. We will be exploring a few things about RESTful APIs and we will be exploring some few things about graphQL APIs and then see the cons and the draw backs that come with using each.

### REST APIs

Imagine walking to a restaurant, you grab a seat and they give you their menu. You make an order and you get what you ordered for. Now you can't really describe the type of food you want and the ingredients you want when ordering. You just pick what's on the menu and you get everything that comes with it even if you don't necessarily need it and you are even restricted to the type of orders you can make. REST apis describe a method for getting data from or interacting with other applications. `REST` is an acronym for Representational State Transfer Protocol

The use of http verbs like `GET, POST or PUT` is fundamental to REST apis and are among the methods that can be specified when making a request to a REST api. The server looks at the request made, it will check the method that was called with the request and call the appropriate handler to process the request. The server can handle the request and send some data back if the need be. One thing with RESTful apis is that you can only make a request to a particular url with a specific method although an endpoint can handle request with different methods. For a particular endpoint the API will always handle the request the same way and will always return the same shape or format of data back to the client. 

Most of the time when making a request you will want to attach a payload along with the request. Payloads are attached to the body of request when you want to send data along with the request. Optionally you can also add parameters inside the url, they are know as `query strings`. a typical request to a REST api would look like the example provided below;

```http
POST http://localhost:3000/book/
Content-Type: application/json

{
	"name": "The God's are not to blame",
	"author": "Ola Rotimi"
}
```

The payload is often sent in the form of JSON data. We can also send other forms of data too, like files and normal strings. We tell the server the type of payload we are sending by specifying setting the content type on the request header to be of the the type of payload we are sending. In the example above we make an example `POST` request and also send some mock JSON data with it, this is to give you a basic idea of how REST apis work. We can set more than one type of header on the request if there is a requirement for it.

```http
GET http://localhost:3000/book?id=2345698
accept: application/json
API-KEY: 234WES7Y5WEQ

```

From above we can say that these four things are the make up of a request to a REST api

* The URL of the request and/or query string
* The headers of the request
* The method of the request
* Optional Body of the request

Other types of methods that REST apis exposes are;

* PATCH
* DELETE

`PATCH` and `PUT` request are quite similar. 

#### Great Things About REST apis

* REST APIs are stateless, this means that each part of the API can actually handle and respond to request without relying or depending on other parts of the API, in essence each part has everything it needs to actually do it's own work. Even after it is done with that work the result of that work will not alter, change or affect any other part of the application.  This can make REST apis quite easy to debug, since you know that each url has a handler, you are certain that whatever bug that's causing it to behave strange is only in that handler except of course you share it between different routes.
* REST apis have full support for caching, it is very easy to implement caching for REST and a lot of the process is already handled for you, specifically `GET` requests. They can be cached, bookmarked, and can even be stored in a history. All these are easy because every request to a REST api is destined for a particular url and has a particular method associated with that method, another obvious cool thing about REST apis.
* REST apis encourage and promote non-shared/micro-service architecture. Each request to a url on a server can be handled by a separate micro-service for that url while a request to another url on that same server will be handled by another micro-service . To the client, it looks like the request is to a single resource meanwhile there are distributed services responsible for each request.

#### Not so Cool Things About REST APIs

* Over-fetching is a well know issue with REST apis, the server is already programmed to return a particular format of data so each time a request is made to the API, it will return the same structure of data, there are certain situations where the returned values are much more than we need.
* There is a situation where the response from the API contains less data than we need so we have to compensate for that by making multiple requests to get one thing after the other.
* Making multiple request also becomes an issue on it's own. We have to make so much request to the server just to fetch bits of information from it and this might present a real issue if the Internet connection is slow, it also increases the number of request we make to the API over time which could ultimately show up in our bill.

#### Scenarios For REST API

In my opinion i think REST apis are pretty good for handling things like authentication, it is very simple and easy to implement an authentication service with a REST api and it is straight forward. small scale projects with very little requirements that don't change often are also a good fit for REST apis, it doesn't make sense to go all out graphQL for a project where the number of endpoints is quite insignificant. The extra layer of complexity is not justified and is much like using a sledgehammer to kill a fly.  REST apis are also suitable for projects where emphasis is placed on caching, query strings and incoming data on the request body. 

### GraphQL

GraphQL is a new way of building APIs that has caused a lot of emotions. Once you successfully build a graphQL API you will feel so amazed about how fast it was and how much flexibility and freedom it offers you. A GraphQL API is like a restaurant that allows you to chose your own food right down to the very ingredients you want on it. The result is that you get exactly what you asked for or something that looks quite like what you asked for. This is the obvious cool thing about graphQL, you describe what you want and the server replies with a response that mirrors what you asked for.

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. You create a schema that describes the shape of your data, then you write resolvers that fulfills each query you make to the server, 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, this makes it easier to evolve APIs over time. GraphQL is strongly typed and provides primitive types that you can use to compose your own complex types that mirrors what your data looks like.  

GraphQL is not tied to any particular language or technology, instead it leverages existing technology and language to build up your API. For almost any language or framework there is a graphQL extension built for that language or framework. You are also not limited to any particular database or storage engine. And this gives you so much freedom and control, it also makes it very easy to port already existing REST API to graphQL technology.

A typical graphQL schema will look definition will look like this.

```typescript
type User{
	_id: ID!,
	name: String,
	age: Int,
  	friends: [User!]
}
```

And a typical client side query will have the following shape;

```typescript
query {
    user {
        name,
        age,
        friends {
            name,
            _id
        }
    }
}
```

If it isn't already apparent from the query above, graphQL allows us to get exactly what we want with each request we make to the API, we can still add headers to the request. This is great for implementing things like authentication which is quite a headache on it's own to implement in graphQL. GraphQL also provides `mutation` for changing the state of our data

#### Great things about graphQL APIs

* GraphQL allows you to get all the data your application needs with just one single request, this eliminates things like under fetching and over fetching. Make one request and get as much information as you need.
* GraphQL also reduces the amount of requests you actually have to make to the server, since we can get all the data we need with a single request, it leans toward reducing the amount of request we make to get some data from the server.
* GraphQL ensures that your API is not tied to any particular language or database. You can upgrade your existing graphQL APIs easily or port your existing APIs to graphQL quite easily, irregardless of the tech stack it is built upon.
* GraphQL applications can perform much betterr on slower internet connections because the amount of communication between the server and the client is reduced so less time is spent waiting for the server to fill a request made to it.

#### Not so cool things about graphQL APIs

* GraphQL is not built from the ground up to implement the http protocol so things like caching is very difficult to implement with graphQL, authentication is also quite difficult to implement especially if you are quite new to it.
* GraphQL resolvers can lead to exhausting server side computation due to the amount of server side joins that you have to make to ensure that the data in the response matches the shape of the defined schema. 
* GraphQL requests are made to a single endpoint so you cannot actually represent a time based history of each request to API. Only a single history will be entered. Bookmarking a single request is also not really possible too because we can query for different things but to the same API endpoint. Things like query strings and requests body cannot be accessed on a graphQL endpoint.

#### When to use graphQL

GraphQL is suitable for very large and complex projects. This is because complexity is easy to manage with graphQL and it really scalable. If the need be to modify the shape of the response, most often your concern is with your schema. This makes your work quite easier and increases your productivity a lot. GraphQL is also suitable for projects that changes are often made to. 
I recently ported a REST api i made at work to graphQL and i would tell you that it took me less time to build compared to the time i spent setting up the REST api. I also observed that some data that had separate url and controllers defined for them in the REST api were just properties that i defined on the schema and i wrote resolvers for filling out those fields. 

The overall developer experience was also really great, this does not mean that it was all fun and no stress. It was quite a nightmare to implement the kind of authentication i wanted and i ended up settling for a hybrid of a REST api and a graphQL api.

That's it for now, i hope i have added more confusion to the mix between graphQL and REST api and you see that each way of building API's have their own drawbacks and benefits. And the best thing to do is to settle for the both of them, why pick one when you can have the best of both worlds?? Feel free to leave a comment below.