0% found this document useful (0 votes)
104 views37 pages

REST Vs GraphQL

REST is an architectural style for building APIs that uses a stateless, client-server architecture and focuses on resources, representations of resources, and relationships between resources. The core constraints that define REST include client-server separation, statelessness, cacheability, layered system, code on demand, and uniform interface. RESTful APIs are commonly implemented using HTTP and leverage HTTP methods, status codes, and authentication/authorization.

Uploaded by

jankos11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views37 pages

REST Vs GraphQL

REST is an architectural style for building APIs that uses a stateless, client-server architecture and focuses on resources, representations of resources, and relationships between resources. The core constraints that define REST include client-server separation, statelessness, cacheability, layered system, code on demand, and uniform interface. RESTful APIs are commonly implemented using HTTP and leverage HTTP methods, status codes, and authentication/authorization.

Uploaded by

jankos11
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

REST vs GraphQL

REST Definitions

What is REST?
REST is short for Representational State Transfer. REST is a software
architectural style… a set of rules and conventions for the creation of an API.

A computer scientist by the name of Roy Fielding defined the principles of


REST in his 2000 PhD dissertation. Like any theoretical ideal, there are a lot
of practical exceptions to Fielding’s principles. But the principles of REST are
intended to make APIs and systems that are: efficient, scalable, simple,
reliable and modifiable (i.e. future-proof) among other things … all excellent
ideals!

Slide 2
The 6 constraints of REST (1)
1. Client-Server architecture – Simply put, RESTful systems separate the
systems responsible for storing and processing the data (the server) from the
systems responsible for collecting, requesting, consuming, and presenting the
data to a user (the client). This separation should be so distinct that the client
and server systems can be improved and updated independently each other.

Client Server

An upgrade to the client should not


necessitate an upgrade to the server… and
vice versa.

Slide 3
The 6 constraints of REST (2)
2. Statelessness – As far as the server is concerned, all client requests are
treated equally. There’s no special, server-side memory of past client activity.
The responsibility of managing state (for example, logged in or not) is on the
client. This constraint is what makes the RESTful approach so scalable.

Be advised! In REST each and every resource request is to convey the


application state. That means the state gets transferred with each request!

Slide 4
The 6 constraints of REST (3)
3. Cacheability – Clients and servers should be able to cache resource data that
changes infrequently. For example, there are 52 states and other jurisdictions
in the U.S.A. That’s not likely to change soon. So, it is inefficient to build a
system that queries a database of states each and every time you need that
data. Clients should be able to cache that infrequently updated date and web
servers should be able to control the duration of that cache.

4. Layered system – A client cannot tell whether it is connected directly to an


end server, or to an intermediary along the way. Intermediary servers can also
improve system scalability.

B
A
C

As far as the client is D


concerned, only “A” exists!

Slide 5
The 6 constraints of REST (4)
5. Code on demand (Optional) – Servers can temporarily extend or customize
the functionality of a client by transferring executable code. This is constraint is
optional.

n ew feature , please?!
Can I have A

e!
Yes! New cod

6. Uniform Interface – This constraint is comprised of 4 additional “constraints”


or “principles”. Taken together, these 4 additional principles basically require
the API to be consistent with HTTP standards and self describing.

Slide 6
Uniform Interface (1)
1. Identification of Resources
The REST style is centered around resources. This is unlike SOAP and other RPC
styles that are modeled around procedures (or methods).
On an implementation level, it is often the database tables (with business logic on
top) that are exposed as resources.
Each resource in a RESTful design must be uniquely identifiable via an URI
(Uniform Resource Identifier)

2. Manipulation of Resources through Representations


The second sub-constraint in the Uniform Interface is that resources are
manipulated through representations.
This means that the client does not interact directly with the server’s resource. For
example, we don’t allow the client to run SQL statements against our database
tables. Instead, the server exposes a representation of the resource’s state.
The most common format for RESTful web services is JSON, which is used in the
body of the HTTP requests and responses.

Slide 7
Uniform Interface (2)
3. Self-Descriptive Messages
The third constraint in the Uniform Interface is that each message (i.e.
request/response) must include enough information for the receiver to understand
it in isolation.
HTTP is not formally required for RESTful web services, but if you use the HTTP
methods you should follow their formal meaning, so the user won’t rely on out of
band information to understand them (i.e. don’t use POST to retrieve data,
or GET to save data).

4. Hypermedia as the Engine of Application State


The fourth and final sub-constraint in the Uniform Interface is called Hypermedia
as the Engine of Application State (HATEOAS). It sounds a bit overwhelming, but
in reality it’s a simple concept.
A web page is an instance of application state, hypermedia is text with hyperlinks.
The hypermedia drives (i.e. engine) the application state. In other words, we click
on links to move to new pages (i.e. application states).
So when you are surfing the web, you are using hypermedia as the engine of
application state!

Slide 8
The marriage of REST and HTTP

Roy Fielding was also one of the


principle authors of the HTTP
specification. Fielding created the REST
constraints with HTTP in mind.

Part of the power of the REST


architectural style is that HTTP was
already widely in use before the REST
constraints were formally defined.

In theory, the six REST constraints we


just reviewed could be applied to other
protocols, but in practice RESTful APIs
are HTTP based.

Slide 9
RESTful API conventions – HTTP Methods
GET – The get method is used to retrieve data from a resource. According to RESTful
conventions, GETs are safe to execute over and over. For example: It is safe to run
the following GET request as many times as you want:

https://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywor
ds=robot

POST – The POST method would be used to create a data record, or initiate an
action. Imagine each POST as being a request to make a amazon purchase. You
would want to be careful about doing that more times than necessary!

PUT -- The PUT method exists in HTTP. It should be used to update an existing data
record.

DELETE – The DELETE method exists in HTTP. It should be used to delete a data
record.

Slide 10
RESTful API conventions – HTTP Status Codes
Every HTTP request results in a status code to be sent back to the client.

Request

Status
Code Server
Client

2xx Status codes indicate success. The most common status code is 200, OK.

3xx Status codes indicate that the client needs to do something else to complete
the request. Usually this means making the request from a different location.
Status code 301 means the resource has been permanently moved somewhere
else.

Slide 11
HTTP Status Codes continued
4xx Status codes indicate a client error. That is, the client sent a request that did
not make sense.

A classic example of this is “404 Not Found”. Try it! Go to


https://www.google.com/bad then try going to https://www.temple.edu/bad Notice
that both pages report the code 404. That’s not just a coincidence.

The internet is built on standards like HTTP and these error codes are part of that
standard.

5xx Status codes indicate a server error. That means that the request made by the
client appears to be fine. But the server is experiencing some difficulty.

A server experiencing some difficulty might report “500 Internal server error”

More thorough documentation of the HTTP status codes can be found here:
https://www.restapitutorial.com/httpstatuscodes.html

Slide 12
Authentication vs. Authorization
Authentication is the verification of the credentials of the connection attempt. This
process consists of sending the credentials from the remote access client to the
remote access server in an either plaintext or encrypted form by using an
authentication protocol.

Authorization is the verification that the connection attempt is allowed.


Authorization occurs after successful authentication.

In other words: Authentication is stating that you are who are you are and
Authorization is asking if you have access to a certain resource.
I know that it is a bit confusing that in REST APIs we are using the Authorization
header for doing Authentication (or both) but if we remember that when calling an
API we are requesting an access to certain resource it means that the server should
know whether it should give access to that resource or not, hence when 
developing and designing RESTful API Authorization header sounds just fine.

Slide 13
4 Most Used Authentication Methods

1. HTTP Authentication Schemes (Basic & Bearer)

2. API Keys

3. OAuth (2.0)

4. OpenID Connect

Slide 14
A quick reality check…

The REST design constraints are good in theory. However, in practice no


one … not even the largest technology companies … implements them
perfectly. Three of the most common constraint violations follow.

Slide 15
Wrinkles and exceptions
1. Abuse of the GET method.

Again, GET is assumed to be a safe operation that never modifies the state of the
resource. However, it has been often contorted into performing other functions…
for example:

http://exampleapi.xyz?action=ADD&productname=Widget

2. APIs are not self-documenting

This RESTful ideal has yet to be fully realized. Even so, some API providers don’t
even try!

3. State matters – In the REST design, the burden of managing state is on the client.
That, however, raises many security concerns. API providers like the efficiency
gains made possible by REST … but there is no one consistent approach to
managing state.

Slide 16
RESTful APIs - presentation time…..

Slide 17
GraphQL introduction

GraphQL is a new API standard that provides a more efficient, powerful and
flexible alternative to REST.
It was developed and open-sourced by Facebook and is now maintained by a
large community of companies and individuals from all over the world.

At its core, GraphQL enables declarative data fetching where a client can specify


exactly what data it needs from an API. Instead of multiple endpoints that return
fixed data structures, a GraphQL server only exposes a single endpoint and
responds with precisely the data a client asked for.

GraphQL is often confused with being a database technology. This is a


misconception, GraphQL is a query language for APIs - not databases. In that
sense it’s database agnostic and effectively can be used in any context where an
API is used.

Slide 18
What GraphQL IS

- A Query Language for APIs


- A Specification for servers to execute GraphQL
queries
- A thin API and routing layer
(field resolver can fetch data from different sources)

Slide 19
What GraphQL is NOT

- No Database
- No Storage Engine
- No Library
- No Software to install (i.e. no GraphQL server to buy
and install)
- Not bound to a programming language
- Not bound to a network transport protocol (can use
HTTP, websockets, …)

Slide 20
Core Concepts

- The Schema Definition Language (SDL)


- Fetching Data with Queries
- Writing Data with Mutations
- Realtime Updates with Subscriptions

Slide 21
The Schema Definition Language (SDL)
GraphQL has its own type system that’s used to define the schema of an API.
The syntax for writing schemas is called Schema Definition Language (SDL).

Let’s make some types:

type Person { type Post {


name: String! title: String!
age: Int! }
}

Let’s also express relationships between types:

type Person { type Post {


name: String! title: String!
age: Int! author: Person!
posts: [Post!]! }
}

Slide 22
Fetching Data with Queries (1)
When working with REST APIs, data is loaded from specific endpoints.
Each endpoint has a clearly defined structure of the information that it
returns.
The approach that’s taken in GraphQL is radically different. Instead of
having multiple endpoints that return fixed data structures, GraphQL APIs
typically only expose a single endpoint.
That means that the client needs to send more information to the server to
express its data needs - this information is called a query.

Here is an example of query in our SDL (schema), which we fetching data with
argument last:
type Query {
allPersons(last: Int): [Person!]!
}

Slide 23
Fetching Data with Queries (2)

Basic Queries

{ {
allPersons(last: 3) { "data": {
name "allPersons": [
} {
} "name": "Johnny"
},
{
"name": "Sarah"
},
{
"name": "Alice"
}
]
}
}

Slide 24
Fetching Data with Queries (3)

One of the major advantages of GraphQL is that it allows for naturally querying
nested information. For example, if you wanted to load all the posts that a Person
has written, you could simply follow the structure of your types to request this
information: {
"data": {
{ "allPersons": [
{
allPersons(last:2) { "name": "Johnny",
"age": 23,
name "posts": [
age {
"title": "GraphQL is awesome"
posts { },
{
title "title": "Relay is a powerful GraphQL Client"
} }
]
} },
{
} "name": "Sarah",
"age": 20,
"posts": [
{
"title": "How to get started with React & GraphQL"
}
]
}
]
} Slide 25
}
Writing Data with Mutations (1)
Next to requesting information from a server, the majority of applications also
need some way of making changes to the data that’s currently stored in the
backend. With GraphQL, these changes are made using so-called mutations.
There generally are three kinds of mutations:

- creating new data


- updating existing data
- deleting existing data

Here is an example of mutation in our SDL (schema):

type Mutation {
createPerson(name: String!, age: Int!): Person!
}

Slide 26
Writing Data with Mutations (2)

Mutations follow the same syntactical structure as queries, but they always need
to start with the mutation keyword. Here’s an example for how we might create a
new Person:

mutation { {
createPerson(name: "Bob", age: 36) { "data": {
name "createPerson": {
age "name": "Bob",
} "age": 36
} }
}
}

Slide 27
Realtime Updates with Subscriptions

Another important requirement for many applications today is to have a realtime


connection to the server in order to get immediately informed about important
events. For this use case, GraphQL offers the concept of subscriptions.

When a client subscribes to an event, it will initiate and hold a steady connection
to the server. Whenever that particular event then actually happens, the server
pushes the corresponding data to the client. Unlike queries and mutations that
follow a typical “request-response-cycle”, subscriptions represent a stream of
data sent over to the client.

Here is an example of subscription in our SDL (schema):

type Subscription {
newPerson: Person!
}

Slide 28
Schema at the end:
type Query {
allPersons(last: Int): [Person!]!
}

type Mutation {
createPerson(name: String!, age: Int!): Person!
}

type Subscription {
newPerson: Person!
}

type Person {
id: ID!
name: String!
age: Int!
posts: [Post!]!
}

type Post {
id: ID!
title: String!
author: Person!
}

Slide 29
GraphQL Use Cases

- GraphQL server with a connected database

- GraphQL server that is a thin layer in front of a number of


third party or legacy systems and integrates them
through a single GraphQL API

- A hybrid approach of a connected database and third


party or legacy systems that can all be accessed through
the same GraphQL API

Slide 30
GraphQL server with a connected database
This architecture will be the most common for greenfield projects. In the setup,
you have a single (web) server that implements the GraphQL specification.

When a query arrives at the GraphQL server, the server reads the query’s
payload and fetches the required information from the database. This is called
resolving the query.

Slide 31
GraphQL layer that integrates existing systems

Another major use case for GraphQL is the integration of multiple existing
systems behind a single, coherent GraphQL API. 

Slide 32
Hybrid approach with connected database and integration
of existing system
Finally, it’s possible to combine the two approaches and build a GraphQL server
that has a connected database but still talks to legacy or third—party systems.

When a query is received by the server, it will resolve it and either retrieve the
required data from the connected database or some of the integrated APIs.

Slide 33
Data Fetching with REST vs GraphQL

Slide 34
Data Fetching with REST vs GraphQL

Slide 35
Data Fetching with REST vs GraphQL

Slide 36
GraphQL API - presentation time…..

Slide 37

You might also like