Wednesday, November 27, 2019

Order of execution of Initialization blocks and Constructors in Java

Initializer block : contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class.
Constructors : are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation.

Order of execution of Initialization blocks and constructor in Java

1. Static initialization blocks will run whenever the class is loaded first time in JVM
2. Initialization blocks run in the same order in which they appear in the program.
3. Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces.

OOPS Concepts

What is an Object?
In short, Object is an instance of a class. The Object is the real-time entity having some state and behavior. In Java, Object is an instance of the class having the instance variables as the state of the object and the methods as the behavior of the object. The object of a class can be created by using the new keyword.

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. In short, a class is the specification or template of an object.

What is Abstraction and give real-world examples?
Abstraction means hiding lower-level details and exposing only the essential and relevant details to the users.
Real world example
A car abstracts the internal details and exposes to the driver only those details that are relevant to the interaction of the driver with the car.

In Java, abstraction is achieved by Interfaces and Abstract classes. We can achieve 100% abstraction using Interfaces.
For details : https://www.javaguides.net/2018/08/abstraction-in-java-with-example.html

What is Encapsulation and give real-world examples?
Encapsulation refers to combining data and associated functions as a single unit. In OOP, data and functions operating on that data are combined together to form a single unit, which is referred to as a class.
For example - if a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.
Encapsulation is implemented using private, package-private and protected access modifiers.

Difference between Abstraction and Encapsulation
Abstraction and Encapsulation in Java are two important Object-oriented programming concept and they are completely different from each other.
Encapsulation is a process of binding or wrapping the data and the codes that operate on the data into a single entity. This keeps the data safe from outside interface and misuse.
Abstraction is the concept of hiding irrelevant details. In other words, make the complex system simple by hiding the unnecessary detail from the user.
Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifiers.
Abstraction solves the problem at the design level. Whereas Encapsulation solves the problem at the implementation level.



Encapsulation: Information hiding.
Abstraction: Implementation hiding.

What is Polymorphism

The process of representing one form in multiple forms is known as Polymorphism.

Types of Polymorphism in Java
Compile time polymorphism or method overloading or static banding
Runtime polymorphism or method overriding or dynamic binding

Java Runtime Polymorphism with Data Member
The method is overridden not applicable data members, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a data member speedlimit, we are accessing the data member by the reference variable of Parent class which refers to the subclass object. Since we are accessing the data member which is not overridden, hence it will access the data member of Parent class always.




What is Composition?
Composition is an association represents a part of a whole relationship where a part cannot exist without a whole.

This is Order class, which HAS-A composition association with LineItem class. That means if you delete Order, then associated all LineItem must be deleted.

class Order {
    private int id;
    private String name;
    private List<LineItem> lineItems;
}

What is Aggregation?
Aggregation is an association represents a part of a whole relationship where a part can exist without a whole. It has a weaker relationship.

Sunday, November 24, 2019

Serialization Interview Questions

What is Serialization in java?
Serialization is process of converting object into byte stream.
 Serialized object (byte stream) can be:
 >Transferred over network.
 >Persisted/saved into file.
 >Persisted/saved into database.
Once, object have have been transferred over network or persisted in file or in database, we could deserialize the object and retain its state as it is in which it was serialized

How do we Serialize object, write a program to serialize and deSerialize object and persist it in file ?
In order to serialize object our class needs to implement java.io.Serializable interface. Serializable interface is Marker interface i.e. it does not have any methods of its own, but it tells Jvm that object has to converted into byte stream.

SERIALIZATION>
Create object of ObjectOutput and give it’s reference variable name oout and call writeObject() method and pass our employee object as parameter [oout.writeObject(object1) ]


OutputStream fout = new FileOutputStream("ser.txt");
ObjectOutput oout = new ObjectOutputStream(fout);
System.out.println("Serialization process has started, serializing employee objects...");
oout.writeObject(object1);


DESERIALIZATION>
Create object of ObjectInput and give it’s reference variable name oin and call readObject() method [oin.readObject() ]

InputStream fin=new FileInputStream("ser.txt");
ObjectInput oin=new ObjectInputStream(fin);
System.out.println("DeSerialization process has started, displaying employee objects...");
Employee emp;
emp=(Employee)oin.readObject();


Difference between Externalizable and Serialization interface (Important)?


Methods
It is a marker interface it doesn’t have any method.
It’s not a marker interface.
It has method’s called writeExternal() and readExternal()
Default Serialization process
YES, Serializable provides its own default serialization process, we just need to implement Serializable interface.
NO, we need to override writeExternal() and readExternal() for serialization process to happen.
Customize serialization process
We can customize default serialization process by defining following methods in our class >readObject() and writeObject()  
Note: We are not overriding these methods, we are defining them in our class.
Serialization process is completely customized
We need to override Externalizable interface’s writeExternal() and readExternal() methods.
Control over Serialization
It provides less control over Serialization as it’s not mandatory to define readObject() and writeObject() methods.
Externalizable provides you great control over serialization process as it is important to override  writeExternal() and readExternal() methods.
Constructor call during deSerialization
Constructor is not called during deSerialization.
Constructor is called during deSerialization.


How can you customize Serialization and DeSerialization process when you have implemented Serializable interface ?
Answer.  Here comes the quite challenging question, where you could prove how strong your Serialization concepts are.We can customize Serialization process by defining writeObject()  method & DeSerialization process by defining readObject() method.

Let’s customize Serialization process by defining writeObject()  method :

      private void writeObject(ObjectOutputStream os) {
           System.out.println("In, writeObject() method.");   
           try {
                  os.writeInt(this.id);
                  os.writeObject(this.name);
           } catch (Exception e) {
                  e.printStackTrace();
           }
    }
We have serialized id and name manually by writing them in file.
 
Let’s customize DeSerialization process by defining readObject()  method :

    private void readObject(ObjectInputStream ois) {
           System.out.println("In, readObject() method.");
           try {
                  id=ois.readInt();
                  name=(String)ois.readObject();
           } catch (Exception e) {
                  e.printStackTrace();
           }
    }

We have DeSerialized id and name manually by reading them from file.

How can you avoid certain member variables of class from getting Serialized?

Answer. Mark member variables as static or transient, and those member variables will no more be a part of Serialization.

What is serialVersionUID?
The serialization at runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.

What are compatible and incompatible changes in Serialization process?
Compatible Changes :  Compatible changes are those changes which does not affect deSerialization process even if class was updated after being serialized (provided serialVersionUID has been declared)
 Adding new fields - We can add new member variables in class.
 Adding writeObject()/readObject()  methods - We may add these methods to customize serialization process.
 Removing writeObject()/readObject() methods - We may remove these methods and then default customization process will be used.
 Changing access modifier of a field - The change to access modifiers i.e. public, default, protected, and private have no effect on the ability of serialization to assign values to the fields.
 Changing a field from static to non static OR changing transient filed to non transient field. - it’s like addition of fields.

InCompatible Changes :  InCompatible changes are those changes which affect deSerialization process if class was updated after being serialized (provided serialVersionUID has been declared)
 Deletion of fields.
 Changing a nonstatic field to static or  non transient field to transient field. - it’s equal to deletion of fields.

 Modifying the writeObject() / readObject() method - we must not modify these method, though adding or removing them completely is compatible change.

What if Serialization is not available, is any any other alternative way to transfer object over network?
>We can can convert JSON to transfer the object. JSON is helpful in stringifying and de stringifying object.
>Hibernate (ORM tool) helps in persisting object as it in database and later we can read persisted object.
>We can convert object into XML (as done in web services) and transfer object over network.

Why static member variables are not part of java serialization process (Important)?
Answer. Serialization is applicable on objects or primitive data types only, but static members are class level variables, therefore, different object’s of same class have same value for static member.
So, serializing static member will consume unnecessary space and time.
Also, if modification is made in static member by any of the object, it won’t be in sync with other serialized object’s value.

What is significance of transient variables?
Answer. Serialization is not applicable on transient variables (it helps in saving time and space during Serialization process), we must mark all rarely used variables as transient. We can initialize transient variables during deSerialization by customizing deSerialization process.

What will happen if one the member of class does not implement Serializable interface (Important)?
Answer. This is classy question which will check your in depth knowledge of Serialization concepts. If any of the member does not implement Serializable than  NotSerializableException is thrown.

What will happen if we have used List, Set and Map as member of class?
Answer. This question which will check your in depth knowledge of Serialization and Java Api’s. ArrayList, HashSet and HashMap implements Serializable interface, so if we will use them as member of class they will get Serialized and DeSerialized as well.

Are primitive types part of serialization process in java?
Yes, primitive types are part of serialization process.

Is constructor of class called during DeSerialization process?
Answer. This question which will check your in depth knowledge of Serialization and constructor chaining concepts. It depends on whether our object has implemented Serializable or Externalizable.
If Serializable has been implemented - constructor is not called during DeSerialization process.
But, if Externalizable has been implemented - constructor is called during DeSerialization process.

What values will int and Integer will be initialized to during DeSerialization process if they were not part of Serialization?
Answer.  int will be initialized to 0 and Integer will be initialized to null during DeSerialization (if they were not part of Serialization process).

How you can avoid Deserialization process creating another instance of Singleton class (Important)?
Answer. This is another classy and very important question which will check your in depth knowledge of Serialization and Singleton concepts. I’ll prefer you must understand this concept in detail. We can simply use readResove() method to return same instance of class, rather than creating a new one.

Defining readResolve() method ensures that we don't break singleton pattern during DeSerialization process.
   
  private Object readResolve() throws ObjectStreamException {
       return INSTANCE;
  }

Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done below :
  private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{
        ois.defaultReadObject();
        synchronized (SingletonClass.class) {
         if (INSTANCE == null) {
               INSTANCE = this;
         }
        }
  }

Can you Serialize Singleton class such that object returned by Deserialization process  is in same state as it was during Serialization time (regardless of any change made to it after Serialization)  (Important)?
Answer. It’s another very important question which will be important in testing your Serialization and Singleton related concepts, you must try to understand the concept and question in detail.
YES, we can Serialize Singleton class such that object returned by Deserialization process is in same state as it was during Serialization time (regardless of any change made to it after Serialization)


Defining readResolve() method ensures that we don't break singleton pattern during DeSerialization process.
   
  private Object readResolve() throws ObjectStreamException {
       return INSTANCE;
  }

Also define readObject() method, rather than creating new instance, assign current object to INSTANCE like done below :
  private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{
        ois.defaultReadObject();
        synchronized (SingletonClass.class) {
         if (INSTANCE == null) {
               INSTANCE = this;
         }
        }
  }

Purpose of serializing Singleton class OR  purpose of saving singleton state?
Answer. Let’s take example of our laptop, daily eod we need to shut it down, but rather than shutting it down hibernate (save state of  laptop) is better option because it enables us to resume at same point where we leaved it, like wise serializing singleton OR saving state of Singleton can be very handy.

How can subclass avoid Serialization if its superClass has implemented Serialization interface ?
If superClass has implemented Serializable that means subclass is also Serializable (as subclass always inherits all features from its parent class), for avoiding Serialization in sub-class we can define writeObject() method and throw NotSerializableException().
private void writeObject(ObjectOutputStream os) throws NotSerializableException {
        throw new NotSerializableException("This class cannot be Serialized");
}

Key Points :

Even though serialVersionUID is a static field, it gets serialized along with the object. This is one exception to the general serialization rule that, “static fields are not serialized”.

serialVersionUID is a must in serialization process. But it is optional for the developer to add it in java source file. If you are not going to add it in java source file, serialization runtime will generate a serialVersionUID and associate it with the class. The serialized object will contain this serialVersionUID along with other data.

The serialVersionUID for dynamic proxy classes and enum types always have the value 0L
transient and static fields are ignored in serialization. After deserialization transient fields and non-final static fields will be null.
final and static fields still have values since they are part of the class data.

ObjectOutputStream.writeObject(obj) and ObjectInputStream.readObject() are used in serialization and deserialization.
During serialization, we need to handle IOException; during deserialization, we need to handle IOException and ClassNotFoundException. So the deserialized class type must be in the classpath.
Uninitialized non-serializable, non-transient instance fields are tolerated.
When adding “private Thread th;“, no error in serializable. However, “private Thread threadClass = new Thread();” will cause exception:

Console
Exception in thread "main" java.io.NotSerializableException: java.lang.Thread
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.howtodoinjava.demo.serialization.DemoClass.writeOut(DemoClass.java:42)
at com.howtodoinjava.demo.serialization.DemoClass.main(DemoClass.java:27)
Serialization and deserialization can be used for copying and cloning objects. It is slower than regular clone, but can produce a deep copy very easily.
If I need to serialize a Serializable class Employee, but one of its super classes is not Serializable, can Employee class still be serialized and deserialized? The answer is yes, provided that the non-serializable super-class has a no-arg constructor, which is invoked at deserialization to initialize that super-class.
We must be careful while modifying a class implementing java.io.Serializable. If class does not contain a serialVersionUID field, its serialVersionUID will be automatically generated by the compiler.
Different compilers, or different versions of the same compiler, will generate potentially different values.


How serialVersionUID is generated?
serialVersionUID is a 64-bit hash of the class name, interface class names, methods and fields. Serialization runtime generates a serialVersionUID if you do not add one in source.

Computation of serialVersionUID is based on not only fields, but also on other aspect of the class like implement clause, constructors, etc. So the best practice is to explicitly declare a serialVersionUID field to maintain backward compatibility. If we need to modify the serializable class substantially and expect it to be incompatible with previous versions, then we need to increment serialVersionUID to avoid mixing different versions.



Sunday, November 17, 2019

Why Object.clone() is protected

It is not necessary to define our method by the name of clone. We can give it any name we want, e.g. createCopy(). Actually we are not overriding the Object.clone() method here, so we don’t have to follow any specification. Object.clone() is protected by its definition, so, practically, child classes of Object outside the package of the Object class (java.lang) can only access it through inheritance and within itself.

Ref: https://dzone.com/articles/shallow-and-deep-java-cloning

String.intern in Java 6, 7 and 8 – string pooling

  • Stay away from String.intern() method on Java 6 due to a fixed size memory area (PermGen) used for JVM string pool storage.
  • Java 7 and 8 implement the string pool in the heap memory. It means that you are limited by the whole application memory for string pooling in Java 7 and 8.
  • Use -XX:StringTableSize JVM parameter in Java 7 and 8 to set the string pool map size. It is fixed, because it is implemented as a hash map with lists in the buckets. Approximate the number of distinct strings in your application (which you intend to intern) and set the pool size equal to some prime number close to this value multiplied by 2 (to reduce the likelihood of collisions). It will allow String.intern to run in the constant time and requires a rather small memory consumption per interned string (explicitly used Java WeakHashMap will consume 4-5 times more memory for the same task).
  • The default value of -XX:StringTableSize parameter is 1009 in Java 6 and Java 7 until Java7u40. It was increased to 60013 in Java 7u40 (same value is used in Java 8 as well).
  • If you are not sure about the string pool usage, try -XX:+PrintStringTableStatistics JVM argument. It will print you the string pool usage when your program terminates.
Ref: http://java-performance.info/string-intern-in-java-6-7-8/

Wednesday, November 13, 2019

Spring Bean Exception

https://www.baeldung.com/spring-beancreationexception









NoSuchBeanDefinition
NoUniqueBeanDefinition

org.springframework.beans.factory.CannotLoadBeanClassException

org.springframework.beans.factory.BeanCurrentlyInCreationException

Common Application properties



1. Core Properties

debug=false Enable debug logs
logging.file.name=myapp.log Log file name (for instance, `myapp.log`). Names can be an exact location or relative to the current directory.
logging.level.* =DEBUG Log levels severity mapping. For instance, `logging.level.org.springframework=DEBUG`.

spring.aop.auto= true Add @EnableAspectJAutoProxy.
spring.application.name=xyz Application name.
spring.autoconfigure.exclude=* Auto-configuration classes to exclude.
spring.config.name=application Config file name.
spring.main.lazy-initialization=false Whether initialization should be performed lazily.
spring.main.web-application-type    Flag to explicitly request a specific type of web application. If not set, auto-detected based on the classpath. Ex : None
spring.profiles.active Comma-separated list of active profiles. Can be overridden by a command line switch.
trace=false Enable trace logs.

2. Cache properties

spring.cache.ehcache.config The location of the configuration file to use to initialize EhCache.

3. Data Properties

spring.datasource.driver-class-name Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.name Name of the datasource. Default to "testdb" when using an embedded database.
spring.datasource.password Login password of the database.
spring.datasource.url JDBC URL of the database.
spring.datasource.username Login username of the database.
spring.jpa.generate-ddl=false Whether to initialize the schema on startup.
spring.jpa.hibernate.ddl-auto DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none".
spring.jpa.show-sql=false Whether to enable logging of SQL statements.


4. Web properties

spring.http.encoding.charset=UTF-8 Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.
spring.mvc.view.prefix Spring MVC view prefix.
spring.mvc.view.suffix Spring MVC view suffix.
spring.servlet.multipart.enabled=true Whether to enable support of multipart uploads.


5.Server properties

server.address Network address to which the server should bind.
server.compression.enabled=false Whether response compression is enabled.
server.error.path=/error Path of the error controller.
server.http2.enabled=false Whether to enable HTTP/2 support, if the current environment supports it.
server.max-http-header-size=8KB Maximum size of the HTTP message header.
server.port=8080 Server HTTP port.
server.servlet.application-display-name=application Display name of the application.
server.servlet.session.timeout=30m Session timeout. If a duration suffix is not specified, seconds will be used.
server.ssl.enabled=true Whether to enable SSL support.
server.tomcat.max-connections=10000 Maximum number of connections that the server accepts and processes at any given time. Once the limit has been reached, the operating system may still accept connections based on the "acceptCount" property.

6. Security properties

spring.security.user.name=user Default user name.
spring.security.user.password Password for the default user name.
spring.security.user.roles Granted roles for the default user name.
spring.session.timeout Session timeout. If a duration suffix is not specified, seconds will be used.

7. Actuator

management.endpoint.health.enabled=true Whether to enable the health endpoint.







Ref: https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#core-properties

Tuesday, November 12, 2019

REST 19 HTTP Status Codes

REST APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result. RFC 2616 defines the Status-Line syntax as shown below:

Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
HTTP defines forty standard status codes that can be used to convey the results of a client’s request. The status codes are divided into the five categories presented below.

CATEGORY DESCRIPTION
1xx: Informational Communicates transfer protocol-level information.
2xx: Success Indicates that the client’s request was accepted successfully.
3xx: Redirection Indicates that the client must take some additional action in order to complete their request.
4xx: Client Error This category of error status codes points the finger at clients.
5xx: Server Error The server takes responsibility for these error status codes.
Now look at subset of codes that specially apply to the design of a REST APIs – in some more detail.


200 (OK)
It indicates that the REST API successfully carried out whatever action the client requested, and that no more specific code in the 2xx series is appropriate.

Unlike the 204 status code, a 200 response should include a response body.The information returned with the response is dependent on the method used in the request, for example:

GET an entity corresponding to the requested resource is sent in the response;
HEAD the entity-header fields corresponding to the requested resource are sent in the response without any message-body;
POST an entity describing or containing the result of the action;
TRACE an entity containing the request message as received by the end server.

201 (Created)
A REST API responds with the 201 status code whenever a resource is created inside a collection. There may also be times when a new resource is created as a result of some controller action, in which case 201 would also be an appropriate response.

The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field.

The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.


202 (Accepted)
A 202 response is typically used for actions that take a long while to process. It indicates that the request has been accepted for processing, but the processing has not been completed. The request might or might not be eventually acted upon, or even maybe disallowed when processing occurs.

Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent’s connection to the server persist until the process is completed.

The entity returned with this response SHOULD include an indication of the request’s current status and either a pointer to a status monitor (job queue location) or some estimate of when the user can expect the request to be fulfilled.


204 (No Content)
The 204 status code is usually sent out in response to a PUT, POST, or DELETE request when the REST API declines to send back any status message or representation in the response message’s body.

An API may also send 204 in conjunction with a GET request to indicate that the requested resource exists, but has no state representation to include in the body.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent’s active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent’s active view.

The 204 response MUST NOT include a message-body and thus is always terminated by the first empty line after the header fields.


301 (Moved Permanently)
The 301 status code indicates that the REST API’s resource model has been significantly redesigned and a new permanent URI has been assigned to the client’s requested resource. The REST API should specify the new URI in the response’s Location header and all future requests should be directed to the given URI.

You will hardly use this response code in your API as you can always use the API versioning for new API while retaining the old one.


302 (Found)
The HTTP response status code 302 Found is a common way of performing URL redirection. An HTTP response with this status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field.

Many web browsers implemented this code in a manner that violated this standard, changing the request type of the new request to GET, regardless of the type employed in the original request (e.g. POST). RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.


303 (See Other)
A 303 response indicates that a controller resource has finished its work, but instead of sending a potentially unwanted response body, it sends the client the URI of a response resource. This can be the URI of a temporary status message, or the URI to some already existing, more permanent, resource.

Generally speaking, the 303 status code allows a REST API to send a reference to a resource without forcing the client to download its state. Instead, the client may send a GET request to the value of the Location header.

The 303 response MUST NOT be cached, but the response to the second (redirected) request might be cacheable.


304 (Not Modified)
This status code is similar to 204 (“No Content”) in that the response body must be empty. The key distinction is that 204 is used when there is nothing to send in the body, whereas 304 is used when the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.

In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy.

Using this saves bandwidth and reprocessing on both the server and client, as only the header data must be sent and received in comparison to the entirety of the page being re-processed by the server, then sent again using more bandwidth of the server and client.


307 (Temporary Redirect)
A 307 response indicates that the REST API is not going to process the client’s request. Instead, the client should resubmit the request to the URI specified by the response message’s Location header. However, future requests should still use the original URI.

A REST API can use this status code to assign a temporary URI to the client’s requested resource. For example, a 307 response can be used to shift a client request over to another host.

The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s). If the 307 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.


400 (Bad Request)
400 is the generic client-side error status, used when no other 4xx error code is appropriate. Errors can be like malformed request syntax, invalid request message parameters, or deceptive request routing etc.

The client SHOULD NOT repeat the request without modifications.


401 (Unauthorized)
A 401 error response indicates that the client tried to operate on a protected resource without providing the proper authorization. It may have provided the wrong credentials or none at all. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.

The client MAY repeat the request with a suitable Authorization header field. If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the 401 response contains the same challenge as the prior response, and the user agent has already attempted authentication at least once, then the user SHOULD be presented the entity that was given in the response, since that entity might include relevant diagnostic information.


403 (Forbidden)
A 403 error response indicates that the client’s request is formed correctly, but the REST API refuses to honor it i.e. the user does not have the necessary permissions for the resource. A 403 response is not a case of insufficient client credentials; that would be 401 (“Unauthorized”).

Authentication will not help and the request SHOULD NOT be repeated. Unlike a 401 Unauthorized response, authenticating will make no difference.


404 (Not Found)
The 404 error status code indicates that the REST API can’t map the client’s URI to a resource but may be available in the future. Subsequent requests by the client are permissible.

No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when no other response is applicable.


405 (Method Not Allowed)
The API responds with a 405 error to indicate that the client tried to use an HTTP method that the resource does not allow. For instance, a read-only resource could support only GET and HEAD, while a controller resource might allow GET and POST, but not PUT or DELETE.

A 405 response must include the Allow header, which lists the HTTP methods that the resource supports. For example:

Allow: GET, POST

406 (Not Acceptable)
The 406 error response indicates that the API is not able to generate any of the client’s preferred media types, as indicated by the Accept request header. For example, a client request for data formatted as application/xml will receive a 406 response if the API is only willing to format data as application/json.

If the response could be unacceptable, a user agent SHOULD temporarily stop receipt of more data and query the user for a decision on further actions.


412 (Precondition Failed)
The 412 error response indicates that the client specified one or more preconditions in its request headers, effectively telling the REST API to carry out its request only if certain conditions were met. A 412 response indicates that those conditions were not met, so instead of carrying out the request, the API sends this status code.


415 (Unsupported Media Type)
The 415 error response indicates that the API is not able to process the client’s supplied media type, as indicated by the Content-Type request header. For example, a client request including data formatted as application/xml will receive a 415 response if the API is only willing to process data formatted as application/json.

For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.


500 (Internal Server Error)
500 is the generic REST API error response. Most web frameworks automatically respond with this response status code whenever they execute some request handler code that raises an exception.

A 500 error is never the client’s fault and therefore it is reasonable for the client to retry the exact same request that triggered this response, and hope to get a different response.

API response is the generic error message, given when an unexpected condition was encountered and no more specific message is suitable.


501 (Not Implemented)
The server either does not recognize the request method, or it lacks the ability to fulfill the request. Usually, this implies future availability (e.g., a new feature of a web-service API).

REST 18 Richardson Maturity Model

Richardson Maturity Model
Leonard Richardson analyzed a hundred different web service designs and divided them into four categories based on how much they are REST compliant. This model of division of REST services to identify their maturity level – is called Richardson Maturity Model.

Richardson used three factors to decide the maturity of a service i.e. URI, HTTP Methods and HATEOAS (Hypermedia). The more a service employs these technologies – more mature it shall be considered.

The levels of maturity according to Richardson’s model
The levels of maturity according to Richardson’s model

The levels of maturity according to Richardson’s model

In this analysis, Richardson described these maturity levels as below:

Level Zero
Level One
Level Two
Level Three
Richardson Maturity Model
Richardson Maturity Model


Richardson Maturity Model

Level Zero
Level zero of maturity does not make use of any of URI, HTTP Methods, and HATEOAS capabilities.

These services have a single URI and use a single HTTP method (typically POST). For example, most Web Services (WS-*)-based services use a single URI to identify an endpoint, and HTTP POST to transfer SOAP-based payloads, effectively ignoring the rest of the HTTP verbs.

Similarly, XML-RPC based services which send data as Plain Old XML (POX). These are the most primitive way of building SOA applications with a single POST method and using XML to communicate between services.


Level One
Level one of maturity makes use of URIs out of URI, HTTP Methods, and HATEOAS.

These services employ many URIs but only a single HTTP verb – generally HTTP POST. They give each individual resource in their universe a URI. Every resource is separately identified by a unique URI – and that makes them better than level zero.


Level Two
Level two of maturity makes use of URIs and HTTP out of URI, HTTP Methods, and HATEOAS.

Level two services host numerous URI-addressable resources. Such services support several of the HTTP verbs on each exposed resource – Create, Read, Update and Delete (CRUD) services. Here the state of resources, typically representing business entities, can be manipulated over the network.

Here service designer expects people to put some effort into mastering the APIs – generally by reading the supplied documentation.

Level 2 is the good use-case of REST principles, which advocate using different verbs based on the HTTP request methods and the system can have multiple resources.


Level Three
Level three of maturity makes use of all three i.e. URIs and HTTP and HATEOAS.

This is the most mature level of Richardson’s model which encourages easy discoverability and makes it easy for the responses to be self-explanatory by using HATEOAS.

The service leads consumers through a trail of resources, causing application state transitions as a result.

REST 17 HTTP Methods

RESTful APIs enable you to develop any kind of web application having all possible CRUD (create, retrieve, update, delete) operations. REST guidelines suggest using a specific HTTP method on a specific type of call made to the server (though technically it is possible to violate this guideline, yet it is highly discouraged).

Use below-given information to find suitable HTTP method for the action performed by API.

Table of Contents

HTTP GET
HTTP POST
HTTP PUT
HTTP DELETE
HTTP PATCH
Summary
Glossary

HTTP GET
Use GET requests to retrieve resource representation/information only – and not to modify it in any way. As GET requests do not change the state of the resource, these are said to be safe methods. Additionally, GET APIs should be idempotent, which means that making multiple identical requests must produce the same result every time until another API (POST or PUT) has changed the state of the resource on the server.

If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.

For any given HTTP GET API, if the resource is found on the server then it must return HTTP response code 200 (OK) – along with response body which is usually either XML or JSON content (due to their platform independent nature).

In case resource is NOT found on server then it must return HTTP response code 404 (NOT FOUND). Similarly, if it is determined that GET request itself is not correctly formed then server will return HTTP response code 400 (BAD REQUEST).

Example request URIs
HTTP GET http://www.appdomain.com/users
HTTP GET http://www.appdomain.com/users?size=20&page=5
HTTP GET http://www.appdomain.com/users/123
HTTP GET http://www.appdomain.com/users/123/address

HTTP POST
Use POST APIs to create new subordinate resources, e.g. a file is subordinate to a directory containing it or a row is subordinate to a database table. Talking strictly in terms of REST, POST methods are used to create a new resource into the collection of resources.

Ideally, if a resource has been created on the origin server, the response SHOULD be HTTP response code 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header.

Many times, the action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either HTTP response code 200 (OK) or 204 (No Content) is the appropriate response status.

Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields.

Please note that POST is neither safe nor idempotent and invoking two identical POST requests will result in two different resources containing the same information (except resource ids).

Example request URIs
HTTP POST http://www.appdomain.com/users
HTTP POST http://www.appdomain.com/users/123/accounts

HTTP PUT
Use PUT APIs primarily to update existing resource (if the resource does not exist then API may decide to create a new resource or not). If a new resource has been created by the PUT API, the origin server MUST inform the user agent via the HTTP response code 201 (Created) response and if an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

The difference between the POST and PUT APIs can be observed in request URIs. POST requests are made on resource collections whereas PUT requests are made on an individual resource.
Example request URIs
HTTP PUT http://www.appdomain.com/users/123
HTTP PUT http://www.appdomain.com/users/123/accounts/456

HTTP DELETE
As the name applies, DELETE APIs are used to delete resources (identified by the Request-URI).

A successful response of DELETE requests SHOULD be HTTP response code 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has been queued, or 204 (No Content) if the action has been performed but the response does not include an entity.

DELETE operations are idempotent. If you DELETE a resource, it’s removed from the collection of resource. Repeatedly calling DELETE API on that resource will not change the outcome – however calling DELETE on a resource a second time will return a 404 (NOT FOUND) since it was already removed. Some may argue that it makes DELETE method non-idempotent. It’s a matter of discussion and personal opinion.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.

Example request URIs
HTTP DELETE http://www.appdomain.com/users/123
HTTP DELETE http://www.appdomain.com/users/123/accounts/456

HTTP PATCH
HTTP PATCH requests are to make partial update on a resource. If you see PUT requests also modify a resource entity so to make more clear – PATCH method is the correct choice for partially updating an existing resource and PUT should only be used if you’re replacing a resource in its entirety.

Please note that there are some challenges if you decide to use PATCH APIs in your application:

Support for PATCH in browsers, servers, and web application frameworks is not universal. IE8, PHP, Tomcat, Django, and lots of other software has missing or broken support for it.
Request payload of PATCH request is not straightforward as it is for PUT request. e.g.
HTTP GET /users/1

produces below response:

{id: 1, username: 'admin', email: 'email@example.org'}

A sample patch request to update the email will be like this:

HTTP PATCH /users/1

[
{ “op”: “replace”, “path”: “/email”, “value”: “new.email@example.org” }
]
There may be following possible operations are per HTTP specification.

[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
{ "op": "remove", "path": "/a/b/c" },
{ "op": "add", "path": "/a/b/c", "value": [ "foo", "bar" ] },
{ "op": "replace", "path": "/a/b/c", "value": 42 },
{ "op": "move", "from": "/a/b/c", "path": "/a/b/d" },
{ "op": "copy", "from": "/a/b/d", "path": "/a/b/e" }
]

PATCH method is not a replacement for the POST or PUT methods. It applies a delta (diff) rather than replacing the entire resource.


Summary of HTTP Methods for RESTful APIs
Below table summarises the use of HTTP methods discussed above.

HTTP METHOD
CRUD
ENTIRE COLLECTION (E.G. /USERS)
SPECIFIC ITEM (E.G. /USERS/123)
POST
Create
201 (Created), ‘Location’ header with link to /users/{id} containing new ID.
Avoid using POST on single resource
GET
Read
200 (OK), list of users. Use pagination, sorting and filtering to navigate big lists.
200 (OK), single user. 404 (Not Found), if ID not found or invalid.
PUT
Update/Replace
404 (Not Found), unless you want to update every resource in the entire collection of resource.
200 (OK) or 204 (No Content). Use 404 (Not Found), if ID not found or invalid.
PATCH
Partial Update/Modify
404 (Not Found), unless you want to modify the collection itself.
200 (OK) or 204 (No Content). Use 404 (Not Found), if ID not found or invalid.
DELETE
Delete
404 (Not Found), unless you want to delete the whole collection — use with caution.
200 (OK). 404 (Not Found), if ID not found or invalid.

Glossary
Safe Methods
As per HTTP specification, the GET and HEAD methods should be used only for retrieval of resource representations – and they do not update/delete the resource on the server. Both methods are said to be considered “safe“.

This allows user agents to represent other methods, such as POST, PUT and DELETE, in a special way, so that the user is made aware of the fact that a possibly unsafe action is being requested – and they can update/delete the resource on server and so should be used carefully.

Idempotent Methods
The term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times. This is a very useful property in many situations, as it means that an operation can be repeated or retried as often as necessary without causing unintended effects. With non-idempotent operations, the algorithm may have to keep track of whether the operation was already performed or not.

In HTTP specification, The methods GET, HEAD, PUT and DELETE are declared idempotent methods. Other methods OPTIONS and TRACE SHOULD NOT have side effects so both are also inherently idempotent.

REST 16 ‘q’ Parameter in HTTP ‘Accept’ Header

A REST API can return the resource representation in many formats – to be more specific MIME-types. A client application or browser can request for any supported MIME type in HTTP Accept header. Technically, Accept header can have multiple values in form of comma separated values.

For example, an Accept header requesting for text/html or application/xml formats can be set as:

Accept : text/html,application/xml
The ‘q’ Parameter
Sometimes client may want to set their preferences when requesting multiple MIME types. To set this preference, q parameter (relative quality factor) is used.

Value of q parameter can be from 0 to 1. 0 is lowest value (i.e. least preferred) and 1 is highest (i.e. most preferred).

A sample usage can be:

Accept : text/html, application/xml;q=0.9, */*;q=0.8
In above example, client is indicating the server that it will prefer to have the response in text/html format, first. It server does not support text/html format for requested resource than it shall send application/xml format. If none of both formats are available, then send the response in whatever format it support (*/*).

One of the benefit of ‘q’ parameter is to minimize the client-server interactions, which could have happened due to failed content negotiations.
It also allows clients to receive content types of which they may not be aware, an asterisk “*” may be used in place of either the second half of MIME type value or both halves.
Here’s how the HTTP spec defines it:

Each media-range MAY be followed by one or more accept-params, beginning with the “q” parameter for indicating a relative quality factor. The first “q” parameter (if any) separates the media-range parameter(s) from the accept-params. Quality factors allow the user or user agent to indicate the relative degree of preference for that media-range, using the ‘q’ value scale from 0 to 1. The default value is 1.
If there are two MIME types for given same q value, then more specific type, between both, wins.

For example if both application/xml and */* had a preference of 0.9 then application/xml will be served by the server.

If no Accept header field is present, then it is assumed that the client accepts all media types. If an Accept header field is present, and if the server cannot send a response which is acceptable according to the combined Accept field value, then the server SHOULD send a 406 (not acceptable) response.

REST 15 N+1 Problem

N+1 problem is mostly talked in context of ORMs. In this problem, the system needs to load N children of a parent entity where only parent entity was requested for. By default, ORMs are configured with lazy-loading enabled, so 1 query issued for the parent entity causes N more queries i.e. one each for N child entities.

This N+1 problem is often considered a major performance bottleneck and so shall be solved at the design level of application.

N+1 Problem in REST APIs
Though mostly directly associated, yet the N+1 problem is not specific to ORMs only. This can be associated with the context of web APIs as well e.g. REST APIs.

In case of web APIs, N+1 problem is a situation where client applications are required to call the server N+1 times to fetch 1 collection resource + N client resources, mostly because of collection resource not had enough information about child resources to build its user interface completely.

For example, a REST API returning a collection of books as a resource.

<books uri="/books" size="100">
    <book uri="/books/1" id="1">
        <isbn>3434253561</isbn>
    </book>
    <book uri="/books/2" id="2">
        <isbn>3423423534</isbn>
    </book>
    <book uri="/books/3" id="3">
        <isbn>5352342344</isbn>
    </book>
    ...
    ...
</books>
Here /books resource return list of books with information including only it’s id and isbn. This information is clearly not enough to build a client application UI which will want to typically show the books name in UI rather than ISBN. It may be that they want to show other information such as author and publication year as well.

In above scenario, client application MUST make N more requests for each individual book resource at /books/{id}. So in the total client will end up invoking REST APIs N+1 times.

Above scenario is only for example. Idea is that insufficient information in collection resources may lead to N+1 problem in REST APIs.

How to Solve N+1 Problem
The good thing about the previously discussed problem is that we know what exactly is the issue. And this makes the solution pretty easy. Include more information in individual resources inside collection resource.

You may consult with API consumers, do market research for similar applications and their user interfaces or simply put yourself in the client’s shoe.

Moreover, you may evolve your APIs over the time as your understanding around client requirements improve. This is possible using API versioning.

REST 14 PUT vs POST

It has been observed that many people struggle to choose between HTTP PUT vs POST methods when designing a system. Though, RFC 2616 has been very clear in differentiating between the two – yet complex wordings are a source of confusion for many of us. Let’s try to solve the puzzle when to use PUT or POST.

Let’s compare them for better understanding.

PUT POST
RFC-2616 clearly mention that PUT method requests for the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource – an update operation will happen, otherwise create operation should happen if Request-URI is a valid resource URI (assuming client is allowed to determine resource identifier).
PUT /questions/{question-id}
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. It essentially means that POST request-URI should be of a collection URI.
POST /questions
PUT method is idempotent. So if you send retry a request multiple times, that should be equivalent to single request modification. POST is NOT idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on server.
Use PUT when you want to modify a singular resource which is already a part of resources collection. PUT replaces the resource in its entirety. Use PATCH if request updates part of the resource. Use POST when you want to add a child resource under resources collection.
Though PUT is idempotent, we shall not cache it’s response. Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent to retrieve a cacheable resource.
Generally, in practice, always use PUT for UPDATE operations. Always use POST for CREATE operations.
PUT vs POST : An Example
Let’s say we are designing a network application. Let’s list down few URIs and their purpose to get better understanding when to use POST and when to use PUT operations.

GET /device-management/devices : Get all devices
POST /device-management/devices : Create a new device

GET /device-management/devices/{id} : Get the device information identified by "id"
PUT /device-management/devices/{id} : Update the device information identified by "id"
DELETE /device-management/devices/{id} : Delete device by "id"
Follow the similar URI design practices for other resources as well.

REST - Part 13 Create REST APIs with JAX-RS 2.0

 In this post, we will learn to create REST APIs using JAX-RS 2.0 (Java API for RESTful Services).

Table of Contents

JAX-RS 2.0 Specification
JAX-RS 2.0 Annotations
Create Maven Application
Include JAX-RS Dependencies to Application
Create Resource Representations
Create REST Resource
Register Resource in runtime
Demo

JAX-RS 2.0 Specification
JAX-RS provides portable APIs for developing, exposing and accessing Web applications designed and implemented in compliance with principles of REST architectural style.

The Java EE 6 release took the first step towards standardizing RESTful web service APIs by introducing a Java API for RESTful web services (JAX-RS) [JSR 311]. JAX-RS ensures portability of REST API code across all Java EE-compliant application servers. The latest version is JAX-RS 2.0 [JSR 339], which was released as part of the Java EE 7 platform.

JAX-RS focuses on applying Java annotations to plain Java objects. JAX-RS has annotations to bind specific URI patterns and HTTP operations to individual methods of your Java class. It also has annotations which can help you handle in input/output parameters.

As we already said that JAX-RS is specification; it means we need to have its implementation to run REST API code. Some of the popular JAX-RS implementations available today are:

Jersey
RESTEasy
Apache CXF
Restlet


JAX-RS 2.0 Annotations 

https://restfulapi.net/create-rest-apis-with-jax-rs-2-0/

REST - Part 12 How to design a REST API

Steps in designing REST Services
Identify Object Model
Create Model URIs
Determine Representations
Assign HTTP Methods
More Actions

Identify Object Model
The very first step in designing a REST API based application is – identifying the objects which will be presented as resources.

For a network based application, object modeling is pretty much simpler. There can be many things such as devices, managed entities, routers, modems etc. For simplicity sake, we will consider only two resources i.e.

Devices
Configurations
Here configuration is sub-resource of a device. A device can have many configuration options.

Note that both objects/resources in our above model will have a unique identifier, which is the integer id property.


Create Model URIs
Now when object model is ready, it’s time to decide the resource URIs. At this step, while designing the resource URIs – focus on the relationship between resources and its sub-resources. These resource URIs are endpoints for RESTful services.

In our application, a device is a top-level resource. And configuration is sub-resource under device. Let’s write down the URIs.

/devices
/devices/{id}

/configurations
/configurations/{id}

/devices/{id}/configurations
/devices/{id}/configurations/{id}
Notice that these URIs do not use any verb or operation. It’s very important to not include any verb in URIs. URIs should all be nouns only.


Determine Representations
Now when resource URIs have been decided, let’s work on their representations. Mostly representations are defined in either XML or JSON format. We will see XML examples as its more expressive on how data is composed.

Collection of Device Resource
When returning a collection resource, include only most important information about resource. This will keep the size of payload small, and so will improve the performance of REST APIs.

<devices size="2">

    <link rel="self" href="/devices"/>

    <device id="12345">
        <link rel="self" href="/devices/12345"/>
        <deviceFamily>apple-es</deviceFamily>
        <OSVersion>10.3R2.11</OSVersion>
        <platform>SRX100B</platform>
        <serialNumber>32423457</serialNumber>
        <connectionStatus>up</connectionStatus>
        <ipAddr>192.168.21.9</ipAddr>
        <name>apple-srx_200</name>
        <status>active</status>
    </device>

    <device id="556677">
        <link rel="self" href="/devices/556677"/>
        <deviceFamily>apple-es</deviceFamily>
        <OSVersion>10.3R2.11</OSVersion>
        <platform>SRX100B</platform>
        <serialNumber>6453534</serialNumber>
        <connectionStatus>up</connectionStatus>
        <ipAddr>192.168.20.23</ipAddr>
        <name>apple-srx_200</name>
        <status>active</status>
    </device>

</devices>
Single Device Resource
Opposite to collection URI, here include complete information of a device in this URI. Here, also include a list of links for sub-resources and other supported operations. This will make your REST API HATEOAS driven.

<device id="12345">
    <link rel="self" href="/devices/12345"/>

    <id>12345</id>
    <deviceFamily>apple-es</deviceFamily>
    <OSVersion>10.0R2.10</OSVersion>
    <platform>SRX100-LM</platform>
    <serialNumber>32423457</serialNumber>
    <name>apple-srx_100_lehar</name>
    <hostName>apple-srx_100_lehar</hostName>
    <ipAddr>192.168.21.9</ipAddr>
    <status>active</status>

    <configurations size="2">
        <link rel="self" href="/configurations" />

        <configuration id="42342">
            <link rel="self" href="/configurations/42342" />
        </configuration>

        <configuration id="675675">
            <link rel="self" href="/configurations/675675" />
        </configuration>
    </configurations>

    <method href="/devices/12345/exec-rpc" rel="rpc"/>
    <method href="/devices/12345/synch-config"rel="synch device configuration"/>
</device>
Configuration Resource Collection
Similar to device collection representation, create configuration collection representation with only minimal information.

<configurations size="20">
    <link rel="self" href="/configurations" />

    <configuration id="42342">
        <link rel="self" href="/configurations/42342" />
    </configuration>

    <configuration id="675675">
        <link rel="self" href="/configurations/675675" />
    </configuration>
    ...
    ...
</configurations>
Please note that configurations collection representation inside device is similar to top-level configurations URI. Only difference is that configurations for a device are only two, so only two configuration items are listed as subresource under device.

Single Configuration Resource
Now, single configuration resource representation must have all possible information about this resource – including relevant links.

<configuration id="42342">
    <link rel="self" href="/configurations/42342" />
    <content><![CDATA[...]]></content>
    <status>active</status>
    <link  rel="raw configuration content" href="/configurations/42342/raw" />
</configuration>
Configuration Resource Collection Under Single Device
This resource collection of configurations will be a subset of primary collection of configurations, and will be specific a device only. As it is the subset of primary collection, DO NOT create a different representation data fields than primary collection. Use same presentation fields as primary collection.

<configurations size="2">
    <link rel="self" href="/devices/12345/configurations" />

    <configuration id="53324">
        <link rel="self" href="/devices/12345/configurations/53324" />
        <link rel="detail" href="/configurations/53324" />
    </configuration>

    <configuration id="333443">
        <link rel="self" href="/devices/12345/configurations/333443" />
        <link rel="detail" href="/configurations/333443" />
    </configuration>
</configurations>
Notice that this subresource collection has two links. One for its direct representation inside sub-collection i.e. /devices/12345/configurations/333443 and other pointing to its location in primary collection i.e. /configurations/333443.

Having two links is important as you can provide access to a device specific configuration in more unique manner, and you will have ability to mask some fields (if design require it) which shall not be visible in a secondary collection.

Single Configuration Resource Under Single Device
This representation should have either exactly similar representation as of Configuration representation from primary collection; OR you may mask few fields.

This subresource representation will also have an additional link to its primary presentation.

<configuration id="11223344">
    <link rel="self" href="/devices/12345/configurations/11223344" />
    <link rel="detail" href="/configurations/11223344" />
    <content><![CDATA[...]]></content>
    <status>active</status>
    <link rel="raw configuration content" href="/configurations/11223344/raw" />
</configuration>
Now, before moving forward to next section, let’s note down few observations so you don’t miss them.

Resource URIs are all nouns.
URIs are usually in two forms – collection of resources and singular resource.
Collection may be in two forms primary collection and secondary collection. Secondary collection is sub-collection from a primary collection only.
Each resource/collection contain at least one link i.e. to itself.
Collections contain only most important information about resources.
To get complete information about a resource, you need to access through its specific resource URI only.
Representations can have extra links (i.e. methods in single device). Here method represent a POST method. You can have more attributes or form links in altogether new way also.
We have not talked about operations on these resources yet.

Assign HTTP Methods
So our resource URIs and their representation are fixed now. Let’s decide the possible operations in application and map these operations on resource URIs. A user of network application can perform browse, create, update or delete operations. So let’s map them.

Browse all devices or configurations [Primary Collection]
HTTP GET /devices
HTTP GET /configurations
If the collection size is large, you can apply paging and filtering as well. e.g. Below requests will fetch first 20 records from collection.

HTTP GET /devices?startIndex=0&size=20
HTTP GET /configurations?startIndex=0&size=20
Browse all devices or configurations [Secondary Collection]
HTTP GET /devices/{id}/configurations
It will be mostly a small size collection – so no need to enable filtering or soring here.

Browse single device or configuration [Primary Collection]
To get the complete detail of a device or configuration, use GET operation on singular resource URIs.

HTTP GET /devices/{id}
HTTP GET /configurations/{id}
Browse single device or configuration [Secondary Collection]
HTTP GET /devices/{id}/configurations/{id}
Subresource representation will be either same as or subset of primary presentation.

Create a device or configuration
Create is not idempotent operation, and in HTTP protocol – POST is also not idempotent. So use POST.

HTTP POST /devices
HTTP POST /configurations
Please note that request payload will not contain any id attribute, as server is responsible for deciding it. Response of create request will look like this:

HTTP/1.1 201 Created
Content-Type: application/xml
Location: http://example.com/network-app/configurations/678678

<configuration id="678678">
    <link rel="self" href="/configurations/678678" />
    <content><![CDATA[...]]></content>
    <status>active</status>
    <link  rel="raw configuration content" href="/configurations/678678/raw" />
</configuration>
Update a device or configuration
Update operation is an idempotent operation and HTTP PUT is also is idempotent method. So we can use PUT method for update operations.

HTTP PUT /devices/{id}
HTTP PUT /configurations/{id}
PUT response may look like this.

HTTP/1.1 200 OK
Content-Type: application/xml

<configuration id="678678">
    <link rel="self" href="/configurations/678678" />
    <content><![CDATA[. updated content here .]]></content>
    <status>active</status>
    <link  rel="raw configuration content" href="/configurations/678678/raw" />
</configuration>
Remove a device or configuration
Removing is always a DELETE operation.

HTTP DELETE /devices/{id}
HTTP DELETE /configurations/{id}
A successful response SHOULD be 202 (Accepted) if resource has been queues for deletion (async operation), or 200 (OK) / 204 (No Content) if resource has been deleted permanently (sync operation).

In case of async operation, application shall return a task id which can be tracked for success/failure status.

Please note that you should put enough analysis in deciding the behavior when a subresource is deleted from system. Normally, you may want to SOFT DELETE a resource in these requests – in other words, set their status INACTIVE. By following this approach, you will not need to find and remove its references from other places as well.

Applying or Removing a configuration from a device
In real application, you will need to apply the configuration on device – OR you may want to remove the configuration from device (not from primary collection). You shall use PUT and DELETE methods in this case, because of its idempotent nature.

//Apply Configuration on a device
HTTP PUT /devices/{id}/configurations     

//Remove Configuration on a device 
HTTP DELETE /devices/{id}/configurations/{id}     

More Actions
So far we have designed only object model, URIs and then decided HTTP methods or operations on them. You need to work on other aspects of the application as well:

1) Logging
2) Security
3) Discovery etc.

In next article, we will create this application in java to get more detailed understanding.