Smooth and powerful Swagger integration via JaxRS Analyzer

TL;DR – watch this video:

This post is an update from “Some words on JavaEE, REST and Swagger” and will show the following:

  • Generating Swagger spec file via JaxRS Analyzer
  • Executable API documentation with Swagger UI
  • Automate everything with Swagger Addon

Generating Swagger 2.0 spec based on your REST endpoints

We will start with the most important (and easy) step shown in this post.

Let’s suppose that you have the following (JaxRS) REST endpoint which intends to update a given car:

public class CarEndpoint {

     * @param id The identifier of the car to be updated
     * @param entity the changes to be applied
    public Response update(@PathParam("id") Integer id, Car entity) {
        if (entity == null) {
            return Response.status(Status.BAD_REQUEST).build();
        if (!id.equals(entity.getId())) {
            return Response.status(Status.CONFLICT).entity(entity).build();
        if (carService.crud().eq("id", id).count() == 0) {
            return Response.status(Status.NOT_FOUND).build();
        try {
        } catch (OptimisticLockException e) {
            return Response.status(Status.CONFLICT).entity(e.getEntity()).build();

        return Response.noContent().build();


Now to generate the swagger specification from this endpoint you can use the JaxRS Analyzer. JaxRS Analyzer will use byte code analysis to infer the endpoint payload, response status, response types and so on. It also reads javadoc tags to enrich endpoint and parameters descriptions.

We will use the analyzer maven plugin to generate swagger spec file at build time:



The minimal configuration for the plugin will require a backend which can be swagger, plain text (default) and asciidoc.

The resourcesDir, which defaults to jaxrs-analyzer, is a directory (relative to build directory) where swagger specification file will be generated. Other configuration attributes can be found here.

For our example, after maven build the swagger.json file will be generated at target/cdi-crud/apidocs, here is its content:


                        "description":"The identifier of the car to be updated"
                        "description":"the changes to be applied"
                        "description":"No Content",
                        "description":"Bad Request",
                        "description":"Not Found",

As you can see the analyzer was able to infer all response codes from our endpoint as well as the payload. It also could read the javadoc and added parameters description.

You can paste the above json content into swagger editor to see how it looks like.

Executable API documentation with Swagger UI

A nice way to expose your API documentation is through Swagger UI. It is mainly a javascript library which will read your swagger.json spec file and turn it into a nice executable api documentation. As you are generating the swagger spec at build time it turns out that this documentation is always updated.

The steps to add swagger ui (as documented in the official site) is mainly copy the library to your project. I’ve done that and made a small change to make swagger ui read the swagger.json from within our application instead of a remote URL.

Here is how our sample endpoint is rendered in swagger ui:



You can also browse the API docs live on Openshift here (it may be unavailable on your first access because of my openshift free account [it shuts the app down when there is no access in a day], just wait a few minutes and try again).

Automating everything with JBoss Forge Swagger Addon

All the above steps described can be automated with Swagger Addon as showed in the video on the beginning of this post.


We saw that creating and maintaining an executable API documentation based on JaxRS endpoints is quite easy (thanks to JaxRS analyzer). You can even automate that with the Swagger Addon.

All code is available on github here.


RESTFul Java with JAX-RS 2.0 Book Review

During my vacation i’ve read RESTFul Java with JAX-RS 2.0 second edition by Bill Burk.

This review is just some notes i made while i was visiting each chapter. It is mainly listing the topics i found important and interesting in the book. I’ve also made some comments.

Positive aspects:

  • Very practical with plenty of nice examples using latest JAX-RS version;
  • really easy to ready and understand book;
  • interesting topics were covered.

Negative Aspects:

  • Missing a REST API documentation chapter;
  • not enough attention on testing, maybe a dedicate chapter with best practices;
  • use more json in favor of xml;
  • Jersey was not mentioned.

Overall it is a great book and fully recommended, even for those already working with REST.

Here are my notes on each chapter. A narrative on most important topics covered so you can have an idea on the content of the book:

Chapter 1 – Introduction to REST

Although it is very objective and succinct, this chapter goes directly to the heart of REST. Compares with CORBA, SOAP and WS-* standards. How REST and HTTP are related. A bit of SOA. Refers to Roy Fielding’s PhD thesis[LINK], a must read article. Finally describes the five RESTful architectural principles: Addressability, Constrained Interface, Representation-Oriented, Communicate Statelessly and HATEOAS.
An excellent overview.

Chapter 2 – Designing RESTful Services

This chapter presents a RESTFul Order entry system interface(a.k.a endpoint) of an hypothetical ecommerce. It shows the concepts described on the first chapter explaining it in an HTTP oriented way, no Java code yet. There is an interesting discussion about “State vs Operation” and best practice to model REST resources. The data format chosen(XML) for model was not the best option i think, in my opinion json would be a best approach both for exemplifying as for best practices (i don’t buy that xml is for Java and json is for web related technologies such as Ajax). This chapter accomplishes well it’s objectives which is to illustrate RESTful concepts in practice.

Chapter 3 – Your First JAX-RS Service

It starts talking a bit of servlets then jumps to JAX-RS, it summarizes well the framework for writing RESTFul services in Java.
Next the Order system designed in chapter 2 is implemented in Java using JAX-RS. For the ones already working with REST in Java it does not adds much to the table but it is a necessary step so the application can evolve during the book. Maybe its a personal taste but i have to say again that “application/xml” was not a good choice. In my opinion the examples would be simpler with json, for example

return new StreamingOutput() {
public void write(OutputStream outputStream)
throws IOException, WebApplicationException {
outputCustomer(outputStream, customer);

Maybe introducing JAX-B in this chapter could be an option to avoid “streams”, inner classes and could simplify the client example.

Chapter 4 – HTTP Method and URI Matching

Details @Path annotation and its matching rules, a bit of sub resources and dispatching, matrix x query params and finally some gotchas in request matching.

Chapter 5 – JAX-RS Injection

Interesting hint on field injection versus singleton resources. @PathParam injection is revisited and more examples are presented. PathSegment and UroInfo are introduced. MatrixParam, QueryParam, FormParam, HeaderParam, CookieParam and BeanParam are detailed with nice examples. BeanParam is new and added to JAX-RS 2.0, a very useful feature. Next it talks about automatic type conversion. How JAX-RS can map request Strings to primitives, enums, lists and objects. Later it goes into details about ParamConverter so JAX-RS can convert http request String into Java objects. Finally the chapter ends explaining @Encoded annotation.

Chapter 6 – JAX-RS Content Handlers

The chapter starts with content marshalling and build in providers (maybe here is the motivation of streams in previous chapters). Some byte and File related examples are presented. Next there is an example of posting a form with Multivalued Map<String, String>. Next the chapter focus JAXB. There is a small intro and some examples. There is an interesting section about JAXB and JSON and how they integrate. Later the chapter details JSON objects. Finally it talks about custom marshalling and exemplifies message body reader and writer.

Chapter 7 – Server Responses and Exception Handling

It starts talking about successful and error responses. Next topic is how to create response with ResponseBuilder. A bit on cookies and later status codes. Next GenericEntity is presented to deal with generics. Finally exception handling is detailed by showing WebApplicationException, exception mappers. It ends explaining error codes and build in JAX-RS exceptions.

Chapter 8 – JAX-RS Client API

A very good introduction to the Client API that comes in JAX-RS 2.0. It really do its job in a very practical way with nice examples.

Chapter 9 – HTTP Content Negotiation

A nice overview of how JAX-RS supports the Conneg protocol to easy the integration with heterogeneous clients and evolution of the system. It starts explaining the negotiation protocol with media type examples, language negotiation and encoding. Next, examples with JAX-RS are presented.The chapter ends with Variants (multiple types of response for the same uri), URI negotiation, new media types (for versioning) and flexible schemas using content negotiation.

Chapter 10 – HATEOAS

A little introduction to the concept. How it can be applied to Web Services. Atom links is presented. Next, the advantages of HATEOAS are explained. Later JAX-RS and HATEOAS plus URI builder and URIInfo are presented with examples. Finally building links and link header is presented.

Chapter 11 – Scaling JAX-RS Applications

The chapter begins talking about the web and mechanisms that help it scale. It talks about caching (browser, proxy and CDN). After introducing caching it explores the HTTP caching with JAX-RS examples. Cache revalidation is visited, again with nice examples. Next topic is concurrency with conditional PUT and POST followed by JAX-RS examples.

Chapter 12 – Filters and Interceptors

Server side filter are presented first with Request and Response filter examples like cache control and authorization. Next, reader and writer interceptors with GZIP example. Client Filters are presented using JAX-RS client API. A cache control filter example is explained, it basically caches some requests and manipulates “If-None-Match” and “If-Modified-Since” headers. Deploying (@Provider) and ordering (@Priority) of filters and interceptors are visited. Method filters and interceptors are exemplified with DynamicFeature and NameBinding. Finally there is a note on exception on filters or interceptors.

Chapter 13 – Asynchronous JAX-RS

It first starts with Client API and AsyncInvoker using futures. Next, Callbacks are presented with nice examples. Server side asynchronous response is introduced. The Internet HTTP request/response thread model and its challenges is explained. Next, the AsyncResponse API is presented with JAX-RS examples.
The chapter made clear that asynchronous responses is for specific applications and most of the times “normal” request/response paradigm is sufficient. Later exception handling and response with resume and cancel is explained. Timeouts and response callbacks are explained. Use cases like server push and publish subscribe (chat) are presented and exemplified. A note on WebSockets and Server Sent Events versus pure HTTP server push apps. Finally scheduling using executors is presented.

Chapter 14 – Deployment and Integration

It starts by registering REST resources by extending application class, initializing Singletons and Classes. Difference between Servlet container and JavaEE JAX-RS deployment is explained. Web.xml configuration is presented. Next topics are EJB 3.1 ad Spring integration. Pretty simple but useful chapter.

Chapter 15 – Securing JAX-RS

A small introduction to security in the web and JavaEE like authentication, authorization, and encryption. It dive in servlet authentication and authorization mechanism followed by encryption. Next authorization annotations like @RolesAllowed and @PermitAll is presented. Next topic is programmatic security with SecurityContext. A JAX-RS RequestFilter for authorization is exemplified. Next is Client side security using JAX-RS client API. OAuth is the next topic. The CNN case is presented as an example of OAuth. Signing and encrypting message bodies is next security topic. It is basically concerned with security in intermediary REST services (a.k.a integrations), twitter is used as example. Later Digital signatures is introduced. DKIM and JOSE JSON Signature (JWS) are exemplified. The last topic is the encryption of representations (the message body). JOSE JSON Encryption (JWE) is used as example. The chapter is more conceptual, the majority of security examples are in Chapter 29.

In chapter 29 there is an interesting OTPAuthenticated Request Filter(one time password). @AllowedPerDay is introduced in the security chain, a nice example of limiting number of access to a resource by user. It is also a ContainerRequestFilter by with lower priority meaning that it runs after OTPAuthenticated filter.

Chapter 16 – Alternative Java Clients

Besides JAX-RS client API other clients are presented. It starts with “pure Java” and HttpURLConnection examples. There is a small note on caching and authentication using classes. Standard Java certificate auth using “keytool” command is introduced. Next topic is HttpClient examples. Client authentication with HttpClient is presented. RESTEasy client proxy is introduced.

CHAPTER 17 – Workbook Introduction

This chapter is a step by step tutorial on how to setup your environment with RESTEasy 3.x(an implementation of JAX-RS 2.0 spec). It uses JDK 6, Maven 3, Jetty 8.1 for servlet container and Wildfly 8.0 for examples that require JavaEE 7. It creates the project and illustrates its directory structure.

From chapter 18 to Chapter 29 is reserved to more elaborate and complete examples for each chapter. This is the great thing on this book, it is example oriented and has dedicate chapters for examples. I will not comment the examples but recommend you to try them when you read, it is great for learning.