REST Vs GraphQL
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.
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
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.
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.
B
A
C
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
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)
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).
Slide 8
The marriage of REST and HTTP
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.
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.
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
2. API Keys
3. OAuth (2.0)
4. OpenID Connect
Slide 14
A quick reality check…
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
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.
Slide 18
What GraphQL IS
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
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).
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:
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
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.
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
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