RESTIFARIAN

A RESTifarian is a zealous proponent of the REST software architectural style as defined by Roy T. Fielding

REST

REpresentational State Transfer

Architectural style for distributed systems

REST components perform actions on a resource by using a representation

A single datum of information is a resource. Any information is a resource - document, image, video - Like: "Today's weather in TLV"

REST

So when we are talking Restful, we talk about RPC as

Things (resources) vs actions (nouns vs verbs)

 

 

 

 

 

 

 

Versus SOAP-RPC (Simple Object Access Protocol)

(extreme verbosity, XML, complicated structure)

Identified by URIs (Unified Resource Identifier)

Multiple URIs (may) refer to the same resource

REST

View comedy movies:

REST                                  Classique API
--------------------------------------------------------------------
(GET) movies/comedy           |         imdb.getComedyMovies(); 

DELETE a single movie:

REST                                  Classique API
--------------------------------------------------------------------
(DELETE) movies/1234          |         imdb.deleteMovie(1234); 

representations

A serialized description of a resource

Resource

  •  Movie (The dark night returns)

Service

  • Service: GET (View meta data)

Representation

  • Name, length, director, rating, list of actions, etc
  • JSON or XML format (other)

HTTP

Request / Response protocol

HTTP 2(?)

Request

response

HTTp verbs

They actually mean something

  1. GET - view
  2. POST - create
  3. PUT - update
  4. DELETE - delete

When we use this, what does it mean?

rest constrains

Uniform Interface

Basically it's consistency

Stateless

*Each request holds all the data - optimized for the server

Cache

Ability to  add caching rules:

cache-control, expires, eTag, pragma

Client - Server paradigm

Layered system

No matter which node serves the client

Code on demand

[Optional]

DESIGNING good api

Always think externally rather than internally

(eyal mrejen 1025 B.C)

2 Types of approaches

  • Dogmatic (restifarian)
  • Pragmatic

Dogmatic

View list of movies

v1/movies/0/20

 

  • URI is King

pragmatic

View list of movies

v1/movies?offset=0&limit=20

 

  • Use Query Strings
  • ​Breaks some rules

2 URLS per resource

  1. /movies [Collection]
  2. /movies/:id [Element]

Prefer the plural use over singular

Verbs (bad) vs nouns (gooood)

Bad

good

/v1/getAllMovies
/v1/getMovieById?id=5322
/v1/importMovie
/v1/deleteMovie?id=5322
[GET]     /v1/movies
[GET]     /v1/movies/5322
[POST]    /v1/movies
[DELETE]  /v1/movies/5322

API version

Bad

GOOD

/movies/authors/v1/123
/movies/authors/v1.1/123
...
...
/movies/authors?v=1.2
v1/movies/authors/123
v2/movies/authors/123/name
Twilio
/2010-04-01/Accounts

salesforce.com
/services/data/v20.0/sobjects/Account

Facebook
?v=1.0

Header || part of the URI

http RESPONSE

  • Information - 1xx
  • All is well - 2xx
  • Redirection - 3xx (not really for API)
  • Client error - 4xx
  • Server error - 5xx

always - 200 ok

  • Always return http 200
  • In the response - return a detailed code and error

http response

http response - all is well

  • 200 - OK [GET /v1/movies/123]
  • 201 - Created [POST /v1/movies/]
  • 204 - Deleted [DELETE /v1/movies/123]

http code - client error

  • 400 - BAD_REQUEST [...missing data]
  • 401 - UNAUTHORIZED [...permissions/login/roles/ etc]
  • 404 - NOT_FOUND [GET /movies/-322]

http code - server error

  • 500 - SERVER_INTERNAL_ERROR (exception/no db connection etc)

Nice to have

Give the client control on the size/response data

[GET] /v1/movies/2234?fields=Title,Rated,Plot
{
  "Title": "The Avengers",
  "Year": "2012",
  "Rated": "PG-13",
  "Released": "04 May 2012",
  "Runtime": "143 min",
  "Genre": "Action, Adventure, Sci-Fi",
  "Director": "Joss Whedon",
  "Writer": "Joss Whedon (screenplay), Zak Penn (story), Joss Whedon (story)",
  "Actors": "Robert Downey Jr., Chris Evans, Mark Ruffalo, Chris Hemsworth",
  "Plot": "Heroes and across Earth and the universe must stop a fierce demigod from taking over New York and the world over, but they must assemble as a team, since the battle will not be won with just one.",
  "Language": "English, Russian",
  "Country": "USA",
  "Awards": "Nominated for 1 Oscar. Another 30 wins & 62 nominations.",
  "Poster": "http://ia.media-imdb.com/images/M/MV5BMTk2NTI1MTU4N15BMl5BanBnXkFtZTcwODg0OTY0Nw@@._V1_SX300.jpg",
  "Metascore": "69",
  "imdbRating": "8.2",
  "imdbVotes": "700,900",
  "imdbID": "tt0848228",
  "Type": "movie",
  "Response": "True"
}

Nice to have

HTTP status code & detailed body

[POST] /v1/movies
{
    "Year": 2012
    "Plot": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod"
}



400 BAD_REQUEST
{
    "error": {
        "property": "Title",
        "type": "required",
        "message": "Property Title is mandatory"
    }
}

naming conventions

Abstract? or Real?

Highest
-------------------------------------
    /v1/fun_stuff

High
-------------------------------------
    /v1/entertainment 

Ground level - easy to understand
-------------------------------------
    /v1/movies

-------------------------------------
Maybe too low....
    /v1/horrorMovies ---> /v1/movies/{genres} ---> /v1/movies/horror
    /v1/comedyMovies                          ---> /v1/movies/comedy

API chaining / associations

[GET] /v1/movies/{ID}/actors

[GET] /v1/movies/244/actors

Response formats

Google
---------------------
?alt=json

Foursquare
---------------------
/venue.json

Digg
---------------------
Accept: application/json (sent in the REQUEST!)
?type=json




....or

XML

Defaults

Always have defaults...and well documented ones

  • Format: json
  • Pagination: offset=0&limit=25

A note about JSON RESPONSE

JSON is for Javascript!
--------------------------------------
const result = JSON.parse(response);


Ugly syntax...when:
var time = result.created_at || result.DateTime;

.....
Luckily...java follows the CamelCase notation like javascript

Bad form

Create
-----------------------------
/v1/movies?method=post

Read
-----------------------------
/v1/movies

Update
-----------------------------
/v1/movies/2241?method=put&rating=10

Delete
-----------------------------
/v1/movies/2241?method=delete


Can you spot the issue?

Good architecture

Use the facade pattern

summary

  • 2 URLS per resource
  • No english verbs - go with HTTP ones
  • Use plurals
  • Be 'real' and down to earth
  • Use defaults 
  • Facade
  • Be verbose
  • Be Dogmatic

Further reading

http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

RESTIFARIAN

By Eyal Mrejen

RESTIFARIAN

Short lecture about what is REST Architecture, and some API design points

  • 220