Restful webservice

26
Introduction of Restful Web Service Main steps for building a Restful Web Service Some frameworks use to build a Restful Web Service Restful Web Service Agenda

Transcript of Restful webservice

• Introduction of Restful Web Service

• Main steps for building a Restful Web Service

• Some frameworks use to build a Restful Web Service

Restful Web Service Agenda

• REST is described by a set of architectural constraints that attempt to minimize latency and

network communications while, at the same time, maximizing the independence and scalability of

component implementations.

• REST characteristic/constraints(ordered)

– Client-Server: Separation of concerns is the principle behind the client-server.

– Stateless: communication must be stateless in nature

– Caching: improve network efficiency

– Uniform interface: The uniform interface simplifies and decouples the architecture, which

enables each part to evolve independently

– Layered System: A REST-based solution can be comprised of multiple architectural layers,

and no one layer can "see past" the next

– Code On-Demand(optional):

Rest concept

• Restful web service built base on the REST architecture style with some

important features:

– Use HTTP protocol for communication between components.

– The web services are completely stateless.

– A caching infrastructure can be leveraged for performance.

– Bandwidth is particularly important and needs to be limited. REST is particularly

useful for limited-profile devices, such as PDAs and mobile phones.

– The service producer and service consumer have a mutual understanding of the

context and content being passed along by having a negotiation.

Restful Web Service

• Simplicity

– Compliant with unique interface for abstraction.

– Reduce step of service define and discovery.

– Utilize non-schema format for transferring data like Json.

• Performance

– Cacheable

– Reduce network latency and bandwidth

• Scalability

– Easy to scale with statelessness

– Support load balancing across service instances via the layered and Uniform interface

constraints.

• Reliability

– Help to avoid single points of failure

• Portability

– The ease of moving services and solutions from one deployed location to another

Benefit of Restful Web Service

• Define resource/service want to expose

• Determine appropriate HTTP methods

• Add authentication/encryption

• Caching appropriate data

• Applying best practices

Main steps building a Restful WS

• Base on business domain model

– An abstraction to represent an object associate with type, data, and relationship: a user,

document, image, services…

– Has data associate with it.

– It is a “noun” in application.

– Resource can contain sub-resource

• Has an identification

– Each resource has an unique associate to identify.

– Can use URL, URI

• Resource representation

– Is a view of resource state at particular time.

– A representation of resource is transferred between components, not resource itself.

– Can be represented by various format: JSON, XML,HTML… to interact between components

– A resource can be represented by many representation.

Restful Resource model

A resource model sample

http://localhost/hotel/hotelId -> Single Resource

http://localhost/hotel/1/room/1 -> sub-resource

http://localhost/hotel/1/Reservation/15

http://localhost/hotel/1/Room/4/Reservation/15

• Resource metadata

– Id: Identifies the unique ID of a resource.

– Href: Identifies the URL of the current resource.

– Link: Identifies a relationship for a resource. This attribute is itself an object and has “rel”

“href” attributes.

– This can be referred to HATEOAS

• Resource state and application state

– Resource state: value of resource at particular time and maintained at server, be persistent

and survivable, ex purchase status….

– Application state: maintain at client, the way client interact with server, like paging info,

authentication info….and can refer as session state

– Each client request encapsulating all necessary application state , server doesn’t maintains

session state for working with each client….

Resource model

Resource state and application state

• Use HTTP as a standard protocol for manipulate resource

– Used to transfer representation of resource over network

– Utilize all verbs in HTTP

– Hierarchy the URI to express hierarchy parameter

• GET to retrieve a resource

– GET http://www.example.com/hotel/12345

– Is safe and Idempotent

– Is cacheable

• DELETE to delete a resource

– DELETE http://www.example.com/hotel/12345

Operation on Resource

• POST to add a resource

– POST http://www.example.com/customers

– Create resources when you do not know the resource identifier.

• PUT to update a resource

– Requests you MUST send all the available properties/values, not just the ones

you want to change.

– Is Idempotent

– Can use to create new Resource.

• For other operations to represent status(not state) of resource belong to a

process: cancel…

– Encapsulate in the resource representation.

– Define another resource

Operation on resource

Resource operation samples

Guest cancel reservation:

DELETE /guest/1/reservation/233?cance=true

Guest transfer money for reservation:

POST /guest/1/reservation/233/acount/1/transfer/2

Register a user

POST /register/

Operation on resource summary

• Authentication

– Various approaches can be used

• Authorization

– Role of user to use service

• Other consideration

– Validation all input on server

– Validate Malformed XML/JSON

– No sensitive data in URL

Restful WS security

• Authentication a restful Web Service

– Stateless , so can’t rely on session to keep authentication info.

– Client need to provide all necessary info a each request.

– Base on some methods: Basic, Digest, Token base, Oauth2

• Basic authentication

– Send pair of Username/Password encode base64.

– Not secure

• Digest authentication

– Password is encrypted using MD-5

– More secure than Basic Authentication.

• Token-base authentication

• Oauth2 approach

Restful WS: Authentication

Token Base Authentication

• Database for validating token

• Json web token for self validation token.

Oauth2 authentication

• The API suggests its own usage

– Using common and concrete terms

– Using noun, not verb: /getAllCars -> /cars

– Do not mix up singular and plural nouns, prefer plural for all resources.

• JSON when possible, XML if have to

• SSL everywhere - all the time

• Deal with collection of resources via GET

– Appling filter via query parameter

– Sort the result

– Limiting which fields are returned by the API

• Average granularity

– Balancing between Fine grained and Coarse Grained

– Don’t mix DB CRUD and Resource CRUD.

• Use sub-resources for relations

• Updates & creation should return a resource representation

– Prevent an API consumer from having to hit the API again

Some best practices

• Versioning with timestamp, a release number and in the path, not header

• Leverage the HTTP status codes and error In a payload

• Allow overriding HTTP method

– Some proxies support only POST and GET methods, using custom HTTP Header X-HTTP-

Method-Override.

• Use HTTP headers for specifying serialization formats

– Content-Type defines the request format

– Accept defines a list of acceptable response formats

• Self-description the request-response.

• Stateless design.

Some other best practices

• Java platform

– Base on JAX-RS specification stand for Java API for RESTful Web Services

– Various compliant implementation: Jersey, RESTEasy

– Spring MVC also support building a Restful Web Service.

• .Net platform

– Using ASP.NET Web API

– WCF

• Other platforms

– Scala with Akka HTTP

– Golang with Revel

Frameworks/Tools to build a Restful WS

• Annotation

– @Path: is used to define a URI matching pattern for incoming HTTP requests to

a specific resource. URI value can be a regular expression, variables are

denoted by braces and :

@Path("/users/username") -> http://example.com/users/Galileo

@Path("database-db")

public Object getDatabase(@PathParam("database") String db) ->

http://example.com/oracle-db

– @GET: HTTP GET method is used to retrieve a representation of a resource,

and It is both an idempotent and safe operation

• GET http://www.example.com/customers/12345

• GET http://www.example.com/customers/12345/orders

– @POST: HTTP POST to *create* new resources

• POST http://www.example.com/customers

• POST http://www.example.com/customers/12345/orders

JAX-RS

• Annotation

– @PUT: HTTP PUT to create/update a resource, this is an idempotent

– @DELETE: HTTP DELETE use to delete a resource

– @PathParam: retrieval based on id like GET /employee/id

– @QueryParam: for filtering, allows to inject individual URI query

parameter

GET /customers?start=0&size=10 ->

@GET(“/customers”) @Produces("application/xml")

public String getCustomers(@QueryParam("start") int start,

@QueryParam("size") int size)

– @FormParam: used to access application/x-www-formurlencoded request

bodies.

– @DefaultValue

– @Cookie: use to retrieve the cookie value sending by client.

JAX-RS

• Asynchronous

– Client asynchronous call by polling using Future or callback using AsyncInvoker

interface.

– Server side asynchronous implementation

• Bean validation

– Supports the Bean Validation to verify JAX-RS resource classes.

– Using annotation: @NotNull, @Email..

• Filter and handler

– Server filter: Request Filter and Response Filter by implementing

ContainerRequestFilter, ContainerRequestFilter.

– Client filter: Request Filter and Response Filter by implementing

ClientRequestFilter, ClientResponseFilter.

JAX-RS

• Content negotiation

– Client/Server can specify the expected content:

• Media: GET /library Accept: application/json

• Language: GET /stuff Accept-Language: en-us, es

• Encode:

– Using annotation:

• @Consumes: specify which MIME media types of representations a resource can

accept, or consume, sending from the client.

• @Produces: specify the MIME media types of representations a resource can produce

and send back to the client: application/json, application/xml, text/html, image/jpeg,

image/png

• Client API

• HATEOAS

JAX-RS

Other useful tools

• Rest Client

– Google Advanced Rest Client

• Document maker

– Swagger

– RAML

• Json validation

– Json parser(http://json.parser.online.fr/)

• Monitor

– Mashape(https://www.mashape.com/)

– Kibana with Logstash

THANK YOU