DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us tomorrow at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Creating Documented REST APIs With Wildfly Swarm

Creating Documented REST APIs With Wildfly Swarm

Learn how to take advantage of Wildfly Swarm to create self-documenting REST APIs when combining JAX-RS with Swagger.

Matthew Casperson user avatar by
Matthew Casperson
·
Apr. 05, 16 · Tutorial
Like (5)
Save
Tweet
Share
10.89K Views

Join the DZone community and get the full member experience.

Join For Free

REST APIs are a natural match for microservices, and using JAX-RS, Swarm provides a simple way deploy RESTFul APIs as standalone applications.

Swarm also provides native integration with Swagger, which is a popular tool for providing documentation and an interactive UI on top of RESTful APIs.

Combining JAX-RS with Swagger gives you a very powerful way to build a self documenting REST API. Let’s take a look at how we can achieve this.

Our build script is very similar to the build scripts from previous Swarm demos. In this case we need the JAX-RS and swagger dependencies to give us the Java EE RESTful API library and the Swagger library that we will use to generate the JSON documentation of our API.

buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
    }

    dependencies {
        classpath "org.wildfly.swarm:wildfly-swarm-plugin:1.0.0.Beta2"
    }
}

group 'com.matthewcasperson'
version '1.0-SNAPSHOT'

apply plugin: 'war'
apply plugin: 'wildfly-swarm'

swarm {
    mainClassName = "com.matthewcasperson.swarmdemo.MyMain"
}

sourceCompatibility = 1.8

def swarmVersionBeta1 = '1.0.0.Beta1'

repositories {
    mavenCentral()
    mavenLocal()
    maven {
        url 'http://repository.jboss.org/nexus/content/groups/public-jboss'
    }
    maven {
        url 'https://maven.repository.redhat.com/nexus/content/repositories/public'
    }
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
    compile 'org.wildfly.swarm:bootstrap:' + swarmVersionBeta1
    compile 'org.wildfly.swarm:jaxrs:' + swarmVersionBeta1
    compile 'org.wildfly.swarm:swagger:' + swarmVersionBeta1
}

JAX-RS implementations need a class that extends the javax.ws.rs.core.Application class. You can use this class to configure the aspects of your RESTful API, but because this is just a simple demo, we rely on the defaults and do nothing more than extend the class.

package com.matthewcasperson.swarmdemo;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

/**
 * JAX-RS entry point
 */
@ApplicationPath("/")
public class MyApplication extends Application {

}

We also need a class to expose our REST API methods. This is all boilerplate JAX-RS, with the exception of the @Api annotation. This annotation provides details that are used to generate the Swagger documentation.

package com.matthewcasperson.swarmdemo;

import io.swagger.annotations.Api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

/**
 * Our REST interface
 */
@Path("/")
@Api(value = "/", description = "Sample REST API")
public class MyRest {
    @GET
    @Path("/helloWorld")
    public String helloWorld() {
        return "Hello World";
    }
}

Pulling this all together is the custom main method. Here we have defined our JAX-RS application, and add support the generation of Swagger documentation. The Swarm documentation details the deployment of JAX-RS applications, and configuring them to support Swagger.

You will also note that we have added a custom filter class called CORSFilter to the deployment. This allows us to make cross origin requests to the REST API and to the Swagger documentation.

package com.matthewcasperson.swarmdemo;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.swagger.SwaggerArchive;

/**
 * Swarm entry point
 */
public class MyMain {
    public static void main(final String... args) throws Exception {

        // Instantiate the container
        final Container container = new Container();

        final JAXRSArchive deployment = ShrinkWrap.create( JAXRSArchive.class );
        deployment.addResource( MyApplication.class );
        deployment.addResource( MyRest.class );
        deployment.addResource( CORSFilter.class );

        // Enable the swagger bits
        final SwaggerArchive archive = deployment.as(SwaggerArchive.class);
        // Tell swagger where our resources are
        archive.setResourcePackages("com.matthewcasperson.swarmdemo");
        archive.setTitle("Swagger Demo");

        container.start();
        container.deploy(deployment);
    }
}

The CORS filter is pretty simple, allowing access from everywhere. Production CORS filters would be a little more discerning, but for our test this is fine.

package com.matthewcasperson.swarmdemo;


import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

/**
 * A CORS filter that will allow remote access to our API and Swagger documentation.
 */
@Provider
public class CORSFilter implements ContainerResponseFilter {
    public void filter(ContainerRequestContext paramContainerRequestContext,
                       ContainerResponseContext paramContainerResponseContext)
            throws IOException {
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        paramContainerResponseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        paramContainerResponseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
    }
}

Once compiled and run, you can open http://localhost:8080/helloWorld to execute the REST API method we exposed. The Swagger documentation is available at http://localhost:8080/swagger.

The Swagger documentation is not actually that easy to read in its raw state, but fortunately there is a UI that can consume this documentation and display it it a much more friendly manner. This UI has been deployed on the Swagger website, and while it shows the documentation of an example pet store by default, you can point the UI to any Swagger documentation file. In our case, entering http://localhost:8080/swagger into the text box at the top and clicking the Explore button will show our Swarm REST API documentation.

Screen Shot 2016-03-27 at 9.21.53 AM.png

Grab the source code for this project from GitHub.

REST Web Protocols swarm WildFly

Published at DZone with permission of Matthew Casperson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Distributed Stateful Edge Platforms
  • 2023 Software Testing Trends: A Look Ahead at the Industry's Future
  • The Top 3 Challenges Facing Engineering Leaders Today—And How to Overcome Them
  • Last Chance To Take the DZone 2023 DevOps Survey and Win $250! [Closes on 1/25 at 8 AM]

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: