Showing posts with label rest. Show all posts
Showing posts with label rest. Show all posts

12 December 2015

RESTful web service In 5 Minutes using DropWizard

These days I am Learning new framework called "Dropwizard".So I thought I want to share what I learn from Dropwizard. Before going to what is Dropwizard I want to tell some difficulties when building rest server application.When I was in university I don't know how to implement Restful webservice and i thought it was difficult task even for  Testing purpose.Then I learn apache CXF web server and the problem was there are lot of dependencies need to create rest server. Ex:-Apache Cxf,Jackson serialization library,log4j for logging ,Junit for Testing And other libraries.So Even for me to hard to remember all the dependency libraries. So the Solution is Dropwizard. Dropwizard is Lightweight framework which have all the dependencies in one place. Dropwizard also support to expand to your project in layered structure such as api/db/client.

What is Drop-wizard

Drop wizard is simply All the listed libraries in one package.



  • metrics
  • jetty
  • jersey
  • jackson
  • jdbi
  • hibernate
  • logback
  • mustache
  • freemarker



Start Using Maven archetype

1
2
mvn archetype:generate -DgroupId=dec.mchoice.tech.talk -DartifactId=Sample-dw-app -Dname=SampleApplication -Dpackage=dev.mchoice.tech.talk
dev.innova.drp -DarchetypeGroupId=io.dropwizard.archetypes -DarchetypeArtifactId=java-simple -DinteractiveMode=false

After creating project it will create this kind of project structure.


Biggest advantage of use maven archetype no need to configure any dependencies or plugin in POM.xml file and it will generate executable jar file .  Next step is create Rest API end point.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Path("/student")

public class StudentManagement {
    @POST

    @Timed

    @Path("/save")

    @Produces(MediaType.APPLICATION_JSON)

    @Consumes({MediaType.APPLICATION_JSON})

    public Response addPerson(Student student) {

        Map<String, Object> response = new HashMap<>();

        response.put("statusCode", "S1000");

        response.put("description", "Successfully added Student");

        return Response.ok(response).build();

    }

}
And then you have to register your rest API in drop wizard configuration.


1
2
3
4
5
6
7
8
@Override
    public void run(final SampleApplicationConfiguration configuration,

                    final Environment environment) {

        environment.jersey().register(new StudentManagement());

    }
And now All the API related stuff are finished.So you need to run your Application.First go to target folder in project and run


1
java -jar Sample-dw-app-1.0-SNAPSHOT.jar server

After running it will start in 8080 port(application port) and there is another port 8081 (Admin port ).
Next tutorial we will discuss how to change the default configurations and what are the usages of admin port.



Then you can use curl request or postmen to send request and check the Rest API.

18 October 2015

API Documentation with Swagger

In this post I will discuss How to document REST API.There are several API documentation tools available.

So In here I will use Swagger as API documentation tool.

Why API Documentation

The Main purpose is Test the API work properly.For Test API normally what we do is using curl or postman send request and Test.So Let's think About Who don't have programming knowledge how to test API.API documentation is to help them to read our API.

Swagger Support user friendly UI to Test the API.For demonstrate behavior of swagger UI I have created sample rest API.

How to use Swagger

First Add these service beans and providers to your server.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<jaxrs:serviceBeans>
     <ref bean="studentManagementListener"/>
     <ref bean="swaggerResourceJSON"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
     <ref bean="jacksonProvider"/>
     <ref bean="resourceWriter"/>
     <ref bean="apiWriter"/>
     <ref bean="corsFilter"/>
</jaxrs:providers>


<bean id="corsFilter" class="org.apache.cxf.rs.security.cors.CrossOriginResourceSharingFilter"/>

    <bean id="swaggerResourceJSON" class="com.wordnik.swagger.jaxrs.listing.ApiListingResourceJSON"/>

    <!-- Swagger writers -->

    <bean id="resourceWriter" class="com.wordnik.swagger.jaxrs.listing.ResourceListingProvider"/>

    <bean id="apiWriter" class="com.wordnik.swagger.jaxrs.listing.ApiDeclarationProvider"/>


And Then Need to Add Swagger Config Bean.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<bean id="swaggerConfig" class="com.wordnik.swagger.jaxrs.config.BeanConfig">

        <property name="resourcePackage" value="dev.innova.rest.server.api"/>

        <property name="version" value="1.0.0"/>

        <property name="basePath" value="${student.management.api.url}"/>

        <property name="title" value="Student Management API"/>

        <property name="description" value="Student Management API Support to Manage Students in library"/>

        <property name="contact" value="sajith.vijesekara@gmail.com"/>

        <property name="license" value="Apache 2.0 License"/>

        <property name="licenseUrl" value="http://www.apache.org/licenses/LICENSE-2.0.html"/>

        <property name="scan" value="true"/>

    </bean>

And The Final Step is define Your API model.It is simple.Using swagger Annotations you can easily  make API visible in swagger UI.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@Path("/")
@ApiModel(value = "Student Management")
@Api(value = "Student Management Server", description = "Student Management")
@CrossOriginResourceSharing(allowAllOrigins = true, allowCredentials = true)
public interface StudentManagement {

    @POST
    @Path("/student/add")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Add Student", response = Response.class, notes = "Add Student")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "Add Student Successful"),
    @ApiResponse(code = 404, message = "Failed to Add Student"),
    @ApiResponse(code = 500, message = "Failed to connect to Server")})
    Response addStudent(Student student);



    @GET
    @Path("/student/search")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Search Student", response = Response.class, notes = "Search Student")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "Search Student Successful"),
    @ApiResponse(code = 404, message = "Failed to Search Student"),
    @ApiResponse(code = 500, message = "Failed to connect to Server")})
    Response searchUser(GetStudent name);



    @DELETE
    @Path("/student/remove")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Delete Student", response = Response.class, notes = "Delete Student")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "Delete Student Successful"),
    @ApiResponse(code = 404, message = "Failed to Delete Student"),
    @ApiResponse(code = 500, message = "Failed to connect to Server")})
    Response removeStudent(GetStudent name);

}

And One Thing I forgot to add what are the dependencies for swagger.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<dependency>
     <groupId>com.wordnik</groupId>
     <artifactId>swagger-jersey2-jaxrs_2.10</artifactId>
     <version>1.3.8</version>
      <exclusions>
         <exclusion>
             <groupId>javax.ws.rs</groupId>
             <artifactId>jsr311-api</artifactId>
         </exclusion>
      </exclusions>
  </dependency>

  <dependency>
       <groupId>org.apache.cxf</groupId>
       <artifactId>cxf-rt-rs-security-cors</artifactId>
       <version>2.6.1</version>
  </dependency>


How to use Swagger UI
Download Swagger UI and deploy in tomcat server.Then open swagger UI and enter API url with api-docs tag at end of URL.

Ex:- http://127.0.0.1:4738/api-docs