Restful Web Services

27 December 2018

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer.

What is REST?

REST stands for REpresentational State Transfer.It is a simple scalable stateless architecture used in enterprise web applications that runs over HTTPS.

It is web standards based architecture and uses HTTP Protocol for data communication. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000.

In REST architecture, a REST Server simply provides access to resources and REST client accesses and presents the resources. Here each resource is identified by URIs/ global IDs. REST uses various representations to represent a resource like text, JSON and XML. Now a days JSON is the most popular format being used in web services.

RESTful Web Services

Web services based on REST Architecture are known as RESTful web services. These web services use HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, provides resource representation such as JSON and set of HTTP Methods. RESTful web services make use of HTTP protocol as a medium of communication between client and server.

Constrains of REST

Restful web service has following constraints.

Stateless:
Stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of request and response. A stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests.

Client–server: A uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state for eg (UUI) , so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered.

Cacheable: Clients can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients from reusing stale or inappropriate data in response to further requests

Layered system - Service Chaining: A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load balancing and by providing shared caches. They may also enforce security policies.

Uniform interface:

The uniform interface constraint is fundamental to the design of any REST service. The uniform interface simplifies and decouples the architecture, which enables each part to evolve independently.

The four constraints for this uniform interface are:

  • Identification of resources

Individual resources are identified in requests, for example using URIs in web-based REST systems. The resources themselves are conceptually separate from the representations that are returned to the client. For example, the server may send data from its database as HTML, XML or JSON, none of which are the server’s internal representation, and it is the same one resource regardless.

  • Manipulation of resources through these representations

When a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource.

  • Self-descriptive messages

Each message includes enough information to describe how to process the message. For example, which parser to invoke may be specified by an Internet media type (previously known as a MIME type). Responses also explicitly indicate their cacheability.

  • Hypermedia as the engine of application state (HATEOAS)

Clients make state transitions only through actions that are dynamically identified within hypermedia by the server (e.g., by hyperlinks within hypertext). Except for simple fixed entry points to the application, a client does not assume that any particular action is available for any particular resources beyond those described in representations previously received from the server.

Commonly used HTTP methods used in REST based Architecture

GET: Provides a read only access to a resource.GET operations are read only and are safe operations.It reads the resource content

PUT: Used to create a new resource or for Update/Replace.

DELETE: Used to remove a resource content.

POST: Used to update a existing resource or create a new resource.

OPTIONS: Used to get the supported operations on a resource. The purpose of OPTIONS method of RESTful web services is to list down the supported operations in a web service and should be read only.

PATCH: Update/Modify the resource

POST, PUT, and PATCH operations require you to provide both headers. The GET and DELETE operations require only the Accept header. Failing to provide the required headers results in a 400 Bad Request error

Resource in REST?

REST architecture treats every content as a resource. These resources can be text files, html pages, images, videos or dynamic business data. REST Server simply provides access to resources and REST client accesses and modifies the resources. Here each resource is identified by URIs/ global IDs.

Representing a resource in REST

REST uses various representations to represent a resource where text, JSON, XML. XML and JSON are the most popular representations of resources.

Following are important points to be considered while designing a representation format of a resource in a RESTful web services.

Understandability: Both Server and Client should be able to understand and utilize the representation format of the resource.

Completeness: Format should be able to represent a resource completely. For example, a resource can contain another resource. Format should be able to represent simple as well as complex structures of resources.

Linkablity: A resource can have a linkage to another resource, a format should be able to handles such situations.

Messaging in RESTful webservices?

A client sends a message in form of a HTTP Request and server responds in form of a HTTP Response. This technique is termed as Messaging. These messages contain message data and metadata i.e. information about message itself.

Components of a HTTP Request

Components Description Examples
Verb identifies the operation/HTTP Methods to be performed on the resource GET, POST, DELETE, PUT etc.
Uniform Resource Identifier(URI) Used to identify the resource on server. Example URI
HTTP Version Indicate HTTP version for example HTTP v1.1
Request Header Contains metadata for the HTTP Request message as key-value pairs. For example, client ( or browser) type, format supported by client, format of message body, cache settings etc.
Request Body Message content or Resource representation {“firstName”:”Nitendra”,”lastName”:”Gautam”}

Components of a HTTP Response

Components Description Examples
Status or Response Code Indicate Server status for the requested resource 404, 200
HTTP Version Indicate HTTP version for example HTTP v1.1
Response Header Contains metadata for the HTTP Response message as key-value pairs content length, content type, response date, server type etc.
Response Body Response message content or Resource representation {"status":"success"}

Addressing in RESTful webservices

Addressing refers to locating a resource or multiple resources lying on the server. It is analogous to locate a postal address of a person.

URI in Restful Webservice

URI stands for Uniform Resource Identifier. Each resource in REST architecture is identified by its URI. Purpose of an URI is to locate a resource(s) on the server hosting the web service.

Below is the format of a URI in REST architecture?

<protocol>://<service-name>/<ResourceType>/<ResourceID>

A URI can be split into two different classifications.

  • URN A URN, or Unique Resource Name, is a form-normal identifier for the resource.

  • URL. a URL, or Uniform Resource Locator, stores the location of a resource.

A common example of a URN is an ISBN, used to uniquely identify books. A book locator service may accept an ISBN as a URN for a book resource and retrieve a list of URLs, representing locations where the book may be retrieved.

Standard URI Best practices

Below are the best practices to create a standard URI for a web service.

Use Plural Noun: Use plural noun to define resources. For example, we’ve used users to identify users as a resource.

Avoid using spaces: Use underscore(_) or hyphen(-) when using a long resource name, for example, use authorized_users instead of authorized%20users.

Use lowercase letters: Although URI is case-insensitive, it is good practice to keep url in lower case letters only.

Maintain Backward Compatibility: As Web Service is a public service, a URI once made public should always be available. In case, URI gets updated, redirect the older URI to new URI using HTTP Status code, 300.

Use HTTP Verb: Always use HTTP Verb like GET, PUT, and DELETE to do the operations on the resource. It is not good to use operations names in URI.

Statelessness in RESTful Webservices

Statelessness as per REST architecture is the restriction that makes sure that a web service should not keep a client state on server.

It is responsibility of the client to pass its context to server and then server can store this context to process client’s further request. For example, session maintained by server is identified by session identifier passed by the client.

Advantages of statelessness in RESTful Webservices?

  • Web services can treat each method request independently.
  • Web services need not to maintain client’s previous interactions. It simplifies application design.
  • As HTTP is itself a statelessness protocol, RESTful Web services work seamlessly with HTTP protocol.

Disadvantages of statelessness in RESTful Webservices?

Main disadvantage of statelessness in RESTful web services is that Web services need to get extra information in each request and then interpret to get the client’s state in case client interactions are to be taken care of.

Idempotent operation?

Idempotent operations means their result will always same no matter how many times these operations are invoked. In Resful based web servuces PUT and DELETE operations are idempotent.

Difference between PUT and POST and Head operations?

PUT and POST operation are nearly same with the difference lying only in the result where PUT operation is idempotent and POST operation can cause different result.

Head Method should return only HTTP Header, no Body and should be read only.

Caching in Web services

Caching refers to storing server response in client itself so that a client needs not to make server request for same resource again and again. A server response should have information about how a caching is to be done so that a client caches response for a period of time or never caches the server response.

Headers

Each of the supported methods can be overridden if you set the X-http-method-override header. The Accept and Content-Type request headers are required for proper data formatting. These request headers have the following valid values:

  • Accept: application/json, application/xml
  • Content-Type: application/json, application/xml

REST API HTTP Response Header and their Uses

Header Uses
Date Header It provides the date and time of the resource when it was created
Last Modified header It provides the date and time of the resource when it was last modified
Cache-Control It is the primary header of HTTP response provides control over caching
Expires header sets expiration date and time of caching
Public directive of Cache Control Header It indicates that resource is cachable by any component
Private directive of Cache Control Header It indicates that resource is cachable by only client and server, no intermediary can cache the resource
no-cache or no-store directive of Cache Control Header It indicates that resource is not cachable
Max-Age directive of Cache Control Header It indicates that the caching is valid up to max-age in seconds. After this, client has to make another request.
must-revalidate directive of Cache Control Header It provides indication to server to revalidate resource if max-age has passed.

Best practices for caching

Always keep static contents like images, css, JavaScript cacheable, with expiration date of 2 to 3 days.

Never keep expiry date too high.

Dynamic contents should be cached for few hours only.

Best practices for secure RESTful web service

As RESTful web services work with HTTP URLs Paths so it is very important to safeguard a RESTful web service in the same manner as a website is be secured. Following are the best practices to be followed while designing a RESTful web service.

Validation: Validate all inputs on the server. Protect your server against SQL or NoSQL injection attacks.

Session based authentication: Use session based authentication to authenticate a user whenever a request is made to a Web Service method.

No sensitive data in URL: Never use username, password or session token in URL , these values should be passed to Web Service via POST method.

Restriction on Method execution: Allow restricted use of methods like GET, POST, DELETE. GET method should not be able to delete data.

Validate Malformed XML or JSON: Check for well formed input passed to a web service method.

Throw generic Error Messages: A web service method should use HTTP error messages like 403 to show access forbidden etc.

Purpose of HTTP Status Code

HTTP Status code are standard codes and refers to predefined status of task done at server. For example, HTTP Status 404 states that requested resource is not present on server.

REST Response HTTP Status Codes

Below are some of commonly used HTTP Status Codes.

Status Code Message Details
200 OK It shows success.
201 CREATED when a resource is successful created using POST or PUT request. Return link to newly created resource using location header.
204 NO CONTENT when response body is empty for example, a DELETE request.
304 NOT MODIFIED used to reduce network bandwidth usage in case of conditional GET requests. Response body should be empty. Headers should have date, location etc.
400 BAD REQUEST states that invalid input is provided e.g. validation error, missing data. The request URI does not match the APIs in the system, or the operation failed for unknown reasons. Invalid headers can also cause this error.
401 Unauthorized or FORBIDDEN It states that user is not having access to method being used for example, delete access without admin rights.The user is not authorized to use the API
403 Forbidden The requested operation is not permitted for the user. This error can also be caused by ACL failures, or business rule or data policy constraints.
404 NOT FOUND It states that method is not available.he requested resource was not found. This can be caused by an ACL constraint or if the resource does not exist.
405 Method not allowed The HTTP action is not allowed for the requested REST API, or it is not supported by any API.
409 CONFLICT states conflict situation while executing the method for example, adding duplicate entry.
500 INTERNAL SERVER ERROR It states that server has thrown some exception while executing the method.

JAX-RS?

JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Webservices.

Its 2.0 version was released in 24 May 2013. JAX-RS makes heavy use of annotations available from Java SE 5 to simplify development of JAVA based web services creation and deployment. It also provides supports for creating clients for RESTful web services.

References

REST Architecture

REST API tutorials

Share: Twitter Facebook Google+ LinkedIn
comments powered by Disqus