Sunday, November 10, 2013

Web API(s) and HTTP Protocols

Having being through many API(s) and code reviews, one thing which comes to front is the invalid use of http methods to perform web api calls. In this article I am going to focus on standard practices of when to use which http method while implementing web api(s).

At first, I'll be focusing on http's different request methods. You might find this information everywhere over the web but I am just putting things together here, after that I'll jump right into http methods with respect to web api(s).

HTTP Methods (specification 1.1)

GET
   As the word itself says, GET should always and only be used to request a particular representation of a resource. 

HEAD
   Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content

POST 
    Requests that the server accept the entity enclosed in the request as a new subordinate of the web resource identified by the URI. The data POSTed might be, as examples, an annotation for existing resources; a message for a bulletin board, newsgroup, mailing list, or comment thread; a block of data that is the result of submitting a web form to a data-handling process; or an item to add to a database.

PUT
    Requests that the enclosed entity be stored under the supplied URI. If the URI refers to an already existing resource, it is modified; if the URI does not point to an existing resource, then the server can create the resource with that URI.

DELETE
    Deletes the specified resource.

TRACE
    Echoes back the received request so that a client can see what (if any) changes or additions have been made by intermediate servers.  
  
OPTIONS
    Returns the HTTP methods that the server supports for the specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource.

CONNECT
    Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy.

PATCH
    Is used to apply partial modifications to a resource

Now we understand what is the purpose of each method from HTTP. Lets now jump into web api(s) and when to use which HTTP method:

GET:
    GET supports very efficient and sophisticated caching and its primary purpose is to get resource. Caching used in GET ensures that you might not have send request to server. GET is also idempotent, which means if you send a request to server and you dont get result you simply dont know whether your resource has reached the server or not and you can simply issue another request, whereas purpose of.

POST
    POST is "create a new resource", so it should not be used to get resource representation. Normally it is seen that POST is always used to get resources which can easily done using GET, doing it this way also decrease application performance as we explicitly ignore cache used by GET to fetch resources.

PUT
     Purpose of PUT is to update a particular resource and if it does not exist create that resource. Common practice which is wrongly followed is PUT is sometimes never used, developers use POST for both update and create purpose which is wrong as per HTTP specification.

DELETE
     DELETE is used to delete a particular resource(s). But it has been observed that POST/GET are used interchangeably to achieve this purpose which violation of HTTP specification.


I hope this little article will help in clearing concept of HTTP methods and their use in web api(s).

References:



  








Thursday, August 8, 2013

Pursuit of Technical Freedom: Configure Logback for Web Applications

Pursuit of Technical Freedom: Configure Logback for Web Applications: This is step by step guide to configure Logback as logging framework for your application Step 1: Adding Dependencies        &l...

Configure Logback for Web Applications



This is step by step guide to configure Logback as logging framework for your application

Step 1: Adding Dependencies

       <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>0.9.30</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>0.9.30</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.2</version>
        </dependency>

 Step 2: Placing logback.xml file for web applications

  Logback.xml file either can be placed at class-path or in resources folder of web application



 Step 3:  Configuration to write logs in console/File

Console

<?xml version="1.0"?>
<configuration>
     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
              <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} -                        %msg%n</pattern>
       </encoder>
     </appender>
     <root level="debug">
       <appender-ref ref="STDOUT" />
    </root>
</configuration>

* Log level can be setup to debug, info, error and warning depending on the need.

File

<?xml version="1.0"?>
<configuration>
       <appender name="FILE" class="ch.qos.logback.core.FileAppender">
              <file>C:\log4j\log.out</file>
              <append>true</append>     
              <encoder>
                     <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n
                     </pattern>
              </encoder>
       </appender>
       <root level="INFO">
              <appender-ref ref="FILE" />
       </root>
</configuration>

Writing to both File and Console simultaneously with different log level

Best way of achieving this functionality is by configuring root to print everything by setting log level to "trace", then apply filters at each appender level. This just works perfect

Here is the configuration file

<?xml version="1.0"?>
<configuration>
       <appender name="FILE" class="ch.qos.logback.core.FileAppender">
              <file>C:\log4j\log.out</file>
              <append>true</append>
              <filter class="ch.qos.logback.classic.filter.LevelFilter">
                     <level>ERROR</level>
                     <onMatch>ACCEPT</onMatch>
                     <onMismatch>DENY</onMismatch>
              </filter>
              <encoder>
                     <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n
                     </pattern>
              </encoder>
       </appender>
       <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
              <filter class="ch.qos.logback.classic.filter.LevelFilter">
                     <level>DEBUG</level>
                     <onMatch>ACCEPT</onMatch>
                     <onMismatch>DENY</onMismatch>
              </filter>
              <encoder>
                     <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
                     </pattern>
              </encoder>
       </appender>
      

       <root level="trace">
              <appender-ref ref="FILE" />
              <appender-ref ref="STDOUT" />
       </root>
</configuration>

if project is log intensive then custom filters can also be written and class of custom filter then can be added to logback.xml file.

Step 4: Logging
Logger logger = (Logger) LoggerFactory.getLogger(Sample.class);

Thats It!



Steps to Setup Playframework Build Jobs using Jenkins

Steps to Setup Playframework Build Jobs using Jenkins

1. Download playframework 2.x version, unzip and place it some directory:

               Download path: http://www.playframework.com/download

2. Add play path to system variable e.g C:/play

3. Download Jenkins:

              Download path: http://jenkins-ci.org/node/296

4. After installation is complete, go to manage Jenkins:





5. Download play-auto-test plugin:

             Download path: http://updates.jenkins-ci.org/download/plugins/play-autotest-plugin/

6. Go to Manage plugins, and install downloaded plug in
7. Open configure System, select JDK and give JAVA_HOME path:


8. Give path to play framework script.


9. Go to New Job, give build job name, select “Build a free-style software project”

10. Press OK, in next screen select source code management system and give path to repository:

11. In “Build”, select “Play” and give play commands, in post build actions, select play! Auto-test reports:

12. Save it, build job is ready.