What the duck is GraphQL?

What the duck is GraphQL?

Why do I need something better than REST APIs? GraphQL has nothing to do with ReactJs. GraphQL is an application interface (API) just like REST, which is much more powerful and flexible and can be written in pretty much any language.

Yes, that’s how I am starting this post, there has been a huge confusion among developers that GraphQL is only for React apps because it was introduced in one of the React conferences.

Facebook has been using GraphQL since 2012 internally and later on made it open source. If such a tech giant company has been using GraphQL for so long on production, GraphQL definitely deserves some attention.

Who else uses GraphQL?

From 2015 many companies have adopted GraphQL and slowly migrating it to. Coursera, Github, Twitter, Shopify are few of big names using GraphQL.

You should read the list of these case-studies sections to get some insight why few of these companies chose GraphQL and how are they planning their future relationship with GraphQL.

Companies using GraphQL in production

By now I think I am able to convince you to some extent, that you should really know more about GraphQL 😁.

Let’s continue our ice breaking session with GraphQL.

But why GraphQL? I was happy with REST

Imagine a restaurant serves only three kinds of pizzas, chicken pizza, broccoli pizza, and cheese pizza but you want a pizza with toppings of chicken, cheese, and broccoli.

If you visit RESTurant you have to order all the three pizzas throw pizza base of the two and combine the toppings of all the three pizzas.

In GraphQL restaurant, it allows you to customize and in one order you get whatever you want. This leads to no extra wait time and no wastage of pizza base.

The above analogy pretty much explains what is the fundamental difference between REST and GraphQL.

GraphQL stands for Graph query language.

Which means type your query and the API responds to your query.

You get, what you ask.

No doubt REST has solved many problems over SOAP.

REST has been helping all the companies make profits for a couple of decades now. With REST APIs everything looked perfect, but when we want to get more data in less number of API calls or fewer roundtrips from client to server, we smell a lot of stuff in the way REST API is designed.

When we look at the REST APIs with magnifying glasses we can see the scars and those scars are screaming for optimizations.

Sample API request in REST vs GraphQL

Let me share a quick example of how REST works.

In REST we have multiple well-defined API endpoints which are responsible for only one task.

Let’s take an example, imagine you want to get some details from the movie details platform and you want to know:

  • The details of the first actor from the best movie of the year 2019.

The REST APIs that we need to call is roughly the following list:

  1. To get all the details of the best movie of the year 2019, you have to call:
GET /api/movies?bestOfYear=2019
Response: 
{
    id: 4,
    name: "The superAPI",
    ...,
    ...
}

  1. To get the actors from the above movie, you have to call:
GET /api/movies/4/actors
Response:
[
    {
        id: 10,
        name: "Mark Zuckenburg",
        ...,
    },
    {
        id: 11,
        name: "REST",
        ...,
    },
    {...}
]

  1. To get the details of the actor with id 10 you have to call one more API.
GET /api/actors/10
Response:
{
    id: 10,
    name: "Facebook"
    age: 15,
    ...,
    ...
}

And if you want more details you have to call more and more APIs 😫

The above is the real problem with REST APIs.

Whereas in GraphQL you need to call only one API, e.g

POST /api/graphql
Request:
{
    movie(category = "best", year = 2019){
        id,
        name,
        releaseYear,
        actors(limit = 1){
            id,
            name,
            age,
        }
    }
}
Response 200 ok:
{
    date: [
        id: 10,
        name: "The super API",
        releaseYear: 2019,
        actors: [{
            id: 10,
            name: "Facebook",
            age: 15
        }]
    ]   
}

And that’s it 😎

Let’s summarise a few of the problems with REST APIs

  1. Multiple roundtrips and data over fetching
  2. As in above example, we wanted the details of one actor from the best movie, there have been a couple of API calls, a lot of over fetched data which we did not want and never asked for, e.g the details of other actors.
  3. The APIs are tightly coupled with the client
  4. Imagine if you want to change some structure or URL of API, the same has to be reflected in the frontend app.
  5. If there is any single change in API and you have a web app, an android app, and ios app, all the different client apps have to be synced with API changes and redeployed, isn’t it too much?
  6. More wait time for the end user to receive the final set of data
  7. The above points are directly responsible for more wait time to receive the data.
Benefits of GraphQL over REST API

How to write GraphQL API?

The GraphQL is the thinnest layer in the application codebase, which doesn’t contain any business logic, this layer only helps as an interface to interact with services or data sources. This layer is more like a controller layer.

The GraphQL API is built using the following main components:

  • Types

The types are the data models in GraphQL which is strictly typed. These types indirectly help in API documentation to the client.

type Actor {
  id: String!, # `!` represents required
  name: String!,
  age: Int!
}
type Movie {
  id: String!,
  name: String!,
  releaseYear: Int!,
  actors: [Actor] # Actor is another type and [] represents array of
}

  • Query

The queries are used to create an interface where the client can put their queries and **GraphQL **resolves it and responds with the data. To set up the query, **GraphQL **needs to have strictly typed schema. These schemas also help in creating the documentation which helps the clients to get details what properties it can query from one GraphQL API.

Compared to REST the query helps in writing all the GET APIs.

type Query {
  movie(category: String, year: Int): Movie # takes category and year as param and return Movie
  movies: [Movie], # equivalent to GET /api/movies
  actors: [Actor], # equivalent to GET /api/actors
  actor(id: String): Actor # equivalent to GET /api/actors/{id}
}

  • Mutation

As the name suggests, the mutations are used to create the interface through which the client can create resources or update the resources.

Compared to REST the mutations helps in writing the POST, PUT and DELETE APIs.

In the following example, we are creating a mutation which takes the name, release year and list of actors as input to create a new movie and returns the newly created movie.

Please note the Actor is ActorInput, it is another model representing the input fields of the actor.

type mutation {
 addNewMovie($name: String!, $releaseYear: Int!, $actors: [ActorInput]): Movie
}

What does it take to replace REST API with GraphQL?

Please note the mutation and query looks like the function header. We would need to define a query resolver class, and it should contain an equivalent name of the function definition to perform the task. Those functions can inject other services and interact with the data source.

I hope this gives a better understanding of how the queries are resolved.

So to answer in short you just need to replace the controller layer of your REST APIs with Query resolver and define these types and GraphQL schema. And everything from services to data source and ORM (if any) remains as it is. Isn’t it super awesome? 😎

Though this needs more details and more things are involved when migrating from REST to GraphQL, but this is the crux of it and I hope you get it.

What’s next?

There are many more topics we need to discuss in detail, follow me and keep an eye on this place. In the next few posts I will write in detail about the following topics:

  • Authentication and Authorization in GraphQL
  • How to migrate from REST APIs to GraphQL
  • GraphQl API Documentation

Please share your thoughts about this article in the comment section or share it on twitter.

What the difference between REST API and RESTful API?

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

The short answer is that REST stands for Representational State Transfer. It’s an architectural pattern for creating web services. A RESTful service is one that implements that pattern.

The long answer starts with “sort of” and “it depends” and continues with more complete definitions.

Defining REST

Let’s start by defining what REST is and is not. For some, REST means a server that exchanges JSON documents with a client over HTTP. Not only is that not a complete definition, but it’s also not always true. The REST specification doesn’t require HTTP or JSON. (The spec doesn’t mention JSON or XML at all.)

The Origins of REST

Roy Fielding introduced the REST architectural pattern in a dissertation he wrote in 2000. The paper defines a means for clients and servers to exchange application data. A key feature is that the client doesn’t need to know anything about the application in advance. The link is to chapter five of his paper. While the entire dissertation describes the hows and whys of REST, that chapter defines the architectural pattern.

Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements.

REST’s Architectural Constraints

Here is a summary of the constraints.

  • Client-server – REST applications have a server that manages application data and state. The server communicates with a client that handles the user interactions. A clear separation of concerns divides the two components. This means you can update and improve them in independent tracks.
  • Stateless – servers don’t maintain any client state. Clients manage their application state. Their requests to servers contain all the information required to process them.
  • Cacheable – servers must mark their responses as cacheable or not. So, infrastructures and clients can cache them when possible to improve performance. They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – this constraint is REST’s most well known feature or rule, depending on who you ask. Fielding says “The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.” REST services provide data as resources, with a consistent namespace. We’ll cover this in detail below.
  • Layered system – components in the system cannot “see” beyond their layer. So, you can easily add load-balancers and proxies to improve security or performance.

A RESTful service is more than a web server that exchanges JSON, or any other, documents. These constraints work together to create a very specific type of application.

Applying the Constraints

First, the client-server, layered systems and stateless constraints combine to form an application with solid boundaries and clear separations between concerns. Data moves from the server to the client upon request. The client displays or manipulates it. If the state changes, the client sends it back to the server for storage. Fielding specifically contrasts REST with architectures that use distributed objects to hide data from other components. In REST, the client and server share knowledge about data and state. The architecture doesn’t conceal data, it only hides implementations.

The cacheable and uniform state constraints go one step further. Application data is available to clients in a clear and consistent interface and cached when possible.

So, that’s the technical definition of REST. What does it look like in the real world?

RPC Over HTTP vs. RESTful

Often when someone says that a service “isn’t REST,” they’re looking at the URIs or how the service uses HTTP verbs. They’re referring to REST’s presentation of data as a uniform set of resources.

This distinction is sometimes framed as a difference between remote procedures calls (RPC) and REST. Imagine a web service for listing, adding, and removing, items from an e-commerce inventory.

In one version, there’s a single URL that we query with HTTP GETs or POSTs.  You interact with the service by POSTing a document, setting the contents to reflect what you want to do.

Add new items with a POST with a NewItem:

POST /inventory HTTP/1.1
 
{
    "NewItem": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

Query for items with a POST and an ItemRequest:

POST /inventory HTTP/1.1
 
{
    "ItemRequest": {
          "id": "1001"
      }
}

Some implementations accept a request for a new item with a get, too.

POST /inventory?id=1001 HTTP/1.1

We also change or delete items with a POST and an ItemDelete or ItemUpdate.

POST /inventory HTTP/1.1
 
{
    "ItemDelete": {
          "id": "1001"
      }
}

This isn’t REST. We’re not exchanging the state of resources. We’re calling a function with arguments that happen to be in a JSON document or URL arguments.

A RESTful service has a URI for each item in the inventory.

So, adding a new item would look like the example above.

POST /item HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

But the similarities end there. Retrieving an item is always a GET:

GET /item/1001 HTTP/1.1   

Deleting is a DELETE:

DELETE /item/1001 HTTP/1.1  

Modifying an item is a PUT:

POST /inventory HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "7.99",
          "id": "1001"
      }
}    

The difference is important. In REST, operations that use distinct HTTP actions. These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts. Most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.

The critical point is that the URIs operate on the data, not on remote methods.

But there’s another reason why the resource model is essential.

REST vs RESTful and the Richardson Maturity Model

When you model your URIs after resources and use HTTP verbs you make your API predictable. Once developers know how you defined your resources, they can almost predict what the API looks like. Here again, the emphasis is on understanding the data, not the operations.

But even if you can’t make the API entirely predictable, you can document any REST service with hypertext. So, each item returned in the inventory app would contain links for deleting, modifying, or setting the inventory level of the resource. Fielding says that before a service is RESTful, it must provide hypertext media as part of the API.

Many sites don’t meet this requirement but are still called REST. Fact is, many sites break the rules in one way or another. So many that Leonard Richardson created a model breaks down REST into levels of compliance

We’ve already covered the source levels:

  • 0 – exporting an API over HTTP with methods called with arguments
  • 1 – Exporting resources instead of methods
  • 2 – Proper use of HTTP verbs
  • 3 – Exporting hypertext with objects that make all or part of the API discoverable.

Richardson’s model is his own, and it doesn’t map directly into Fielding’s spec. Since Fielding requires level three, he would say that most apps aren’t REST anyway.

The point is many services that we colloquially refer to as REST, technically aren’t.

REST vs RESTful: Does It Matter?

So, does the REST vs. RESTful comparison matter? Probably not. How well your architecture complies with an arbitrary standard isn’t as important with how well it suits your needs and can grow with your business.

The REST architectural pattern has many advantages. Fielding designed it for the web and, 18 years later, most of the constraints he had in mind are still with us. In 2000 we didn’t have Android or the iPhone. IE5 had 50% of the browser market share. It’s biggest rival was Firefox. But Fielding recognized what online applications needed and how web clients would evolve from HTML display engines into complete applications. The tools we use today have grown to suit REST, not the other way around.

Thank you for reading. Hope this tutorial will help you!

What the difference between REST API and RESTful API?

What the difference between REST API and RESTful API?

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web. RESTful is typically used to refer to web services implementing such an architecture.

The short answer is that REST stands for Representational State Transfer. It’s an architectural pattern for creating web services. A RESTful service is one that implements that pattern.

The long answer starts with “sort of” and “it depends” and continues with more complete definitions.

Defining REST

Let’s start by defining what REST is and is not. For some, REST means a server that exchanges JSON documents with a client over HTTP. Not only is that not a complete definition, but it’s also not always true. The REST specification doesn’t require HTTP or JSON. (The spec doesn’t mention JSON or XML at all.)

The Origins of REST

Roy Fielding introduced the REST architectural pattern in a dissertation he wrote in 2000. The paper defines a means for clients and servers to exchange application data. A key feature is that the client doesn’t need to know anything about the application in advance. The link is to chapter five of his paper. While the entire dissertation describes the hows and whys of REST, that chapter defines the architectural pattern.

Fielding doesn’t mandate specific requirements. Instead, he defines REST regarding constraints and architectural elements.

REST’s Architectural Constraints

Here is a summary of the constraints.

  • Client-server – REST applications have a server that manages application data and state. The server communicates with a client that handles the user interactions. A clear separation of concerns divides the two components. This means you can update and improve them in independent tracks.
  • Stateless – servers don’t maintain any client state. Clients manage their application state. Their requests to servers contain all the information required to process them.
  • Cacheable – servers must mark their responses as cacheable or not. So, infrastructures and clients can cache them when possible to improve performance. They can dispose of non-cacheable Information, so no client uses stale data.
  • Uniform interface – this constraint is REST’s most well known feature or rule, depending on who you ask. Fielding says “The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components.” REST services provide data as resources, with a consistent namespace. We’ll cover this in detail below.
  • Layered system – components in the system cannot “see” beyond their layer. So, you can easily add load-balancers and proxies to improve security or performance.

A RESTful service is more than a web server that exchanges JSON, or any other, documents. These constraints work together to create a very specific type of application.

Applying the Constraints

First, the client-server, layered systems and stateless constraints combine to form an application with solid boundaries and clear separations between concerns. Data moves from the server to the client upon request. The client displays or manipulates it. If the state changes, the client sends it back to the server for storage. Fielding specifically contrasts REST with architectures that use distributed objects to hide data from other components. In REST, the client and server share knowledge about data and state. The architecture doesn’t conceal data, it only hides implementations.

The cacheable and uniform state constraints go one step further. Application data is available to clients in a clear and consistent interface and cached when possible.

So, that’s the technical definition of REST. What does it look like in the real world?

RPC Over HTTP vs. RESTful

Often when someone says that a service “isn’t REST,” they’re looking at the URIs or how the service uses HTTP verbs. They’re referring to REST’s presentation of data as a uniform set of resources.

This distinction is sometimes framed as a difference between remote procedures calls (RPC) and REST. Imagine a web service for listing, adding, and removing, items from an e-commerce inventory.

In one version, there’s a single URL that we query with HTTP GETs or POSTs.  You interact with the service by POSTing a document, setting the contents to reflect what you want to do.

Add new items with a POST with a NewItem:

POST /inventory HTTP/1.1
 
{
    "NewItem": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

Query for items with a POST and an ItemRequest:

POST /inventory HTTP/1.1
 
{
    "ItemRequest": {
          "id": "1001"
      }
}

Some implementations accept a request for a new item with a get, too.

POST /inventory?id=1001 HTTP/1.1

We also change or delete items with a POST and an ItemDelete or ItemUpdate.

POST /inventory HTTP/1.1
 
{
    "ItemDelete": {
          "id": "1001"
      }
}

This isn’t REST. We’re not exchanging the state of resources. We’re calling a function with arguments that happen to be in a JSON document or URL arguments.

A RESTful service has a URI for each item in the inventory.

So, adding a new item would look like the example above.

POST /item HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "9.99",
          "id": "1001"
      }
}    

But the similarities end there. Retrieving an item is always a GET:

GET /item/1001 HTTP/1.1   

Deleting is a DELETE:

DELETE /item/1001 HTTP/1.1  

Modifying an item is a PUT:

POST /inventory HTTP/1.1
 
{
    "Item": {
          "name": "new item",
          "price": "7.99",
          "id": "1001"
      }
}    

The difference is important. In REST, operations that use distinct HTTP actions. These verbs correspond directly to the activity on the data. GET, POST, PUT, DELETE and PATCH all have specific contracts. Most well-designed REST APIs also return specific HTTP codes, depending on the result of the request.

The critical point is that the URIs operate on the data, not on remote methods.

But there’s another reason why the resource model is essential.

REST vs RESTful and the Richardson Maturity Model

When you model your URIs after resources and use HTTP verbs you make your API predictable. Once developers know how you defined your resources, they can almost predict what the API looks like. Here again, the emphasis is on understanding the data, not the operations.

But even if you can’t make the API entirely predictable, you can document any REST service with hypertext. So, each item returned in the inventory app would contain links for deleting, modifying, or setting the inventory level of the resource. Fielding says that before a service is RESTful, it must provide hypertext media as part of the API.

Many sites don’t meet this requirement but are still called REST. Fact is, many sites break the rules in one way or another. So many that Leonard Richardson created a model breaks down REST into levels of compliance

We’ve already covered the source levels:

  • 0 – exporting an API over HTTP with methods called with arguments
  • 1 – Exporting resources instead of methods
  • 2 – Proper use of HTTP verbs
  • 3 – Exporting hypertext with objects that make all or part of the API discoverable.

Richardson’s model is his own, and it doesn’t map directly into Fielding’s spec. Since Fielding requires level three, he would say that most apps aren’t REST anyway.

The point is many services that we colloquially refer to as REST, technically aren’t.

REST vs RESTful: Does It Matter?

So, does the REST vs. RESTful comparison matter? Probably not. How well your architecture complies with an arbitrary standard isn’t as important with how well it suits your needs and can grow with your business.

The REST architectural pattern has many advantages. Fielding designed it for the web and, 18 years later, most of the constraints he had in mind are still with us. In 2000 we didn’t have Android or the iPhone. IE5 had 50% of the browser market share. It’s biggest rival was Firefox. But Fielding recognized what online applications needed and how web clients would evolve from HTML display engines into complete applications. The tools we use today have grown to suit REST, not the other way around.

Thank you for reading. Hope this tutorial will help you!

REST vs GraphQL - What's the best kind of API?

REST vs GraphQL - What's the best kind of API?

REST vs GraphQL - What's the best kind of API? Should you build/ use a REST API or a GraphQL API? Can you only use GraphQL with React? Time for a detailed comparison!

REST vs GraphQL - What's the best kind of API?

Should you build/ use a REST API or a GraphQL API?

Can you only use GraphQL with React? Time for a detailed comparison!

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Creating RESTful APIs with NodeJS and MongoDB Tutorial

How to build RESTful APIs with ASP.NET Core

Understanding the basics of RESTful APIs

Spring Data REST Tutorial: Developing RESTful APIs with Ease

Developing RESTful APIs with Lumen (A PHP Micro-framework)