Spring Rest API with Swagger – Creating documentation

The real key to making your REST API easy to use is good documentation. But even if your documentation is done well, you need to set your company processes right to publish it correctly and on time. Ensuring that stakeholders receive it on time is one thing, but you are also responsible for updates in both the API and documentation. Having this process done automatically provides easy way out of trouble, since your documentation is no longer static deliverable and becomes a living thing. In previous post, I discussed how to integrate Swagger with your Spring application with Jersey. Now it’s time to show you how to create documentation and publish it for others to see.

Before I get down to the actual documentation, lets start with a few notes on its form and properties. We will be using annotations to supply metadata to our API which answers question how. But what about why? On one hand we are supplying new annotations to already annotation ridden places like API endpoints or controllers (in case of integration with Spring MVC). But on the other, this approach has a standout advantage in binding release cycle of application, API and documentation in one delivery. Using this approach allows us to create and manage small cohesive units ensuring proper segmentation of documentation and its versioning as well.

Creating endpoint documentation

Everything starts right on top of your endpoint. In order to make Swagger aware of your endpoint, you need to annotate your class with @Api annotation. Basically, all you want to do here is name your endpoint and provide some description for your users. This is exactly what I am doing in the following code snippet. If you feel the need to go into more detail with your API documentation, check out @Api annotation description below.

To verify the results just enter the URL from your basePath variable followed by /api-docs into your browser. This is the place where resource listing for your APIs resides. You can expect something similar to following snippet I received after annotating three of my endpoints and accessing http://[hostname]:[port]/SpringWithSwagger/rest/api-docs/:

However, please note that in order for an API to appear in APIs listing you have to annotate at least one API method with Swagger annotations. If none of your methods is annotated (or you haven’t provided any methods yet), API documentation will not be processed and published.

@Api annotation

Operations documentation

Now, lets move on to the key part of API documentation. There are basically two main parts of operation documentation – operation description and response description. Lets start with operation description. Using annotation @ApiOperation provides detailed description of what certain method does, its response, HTTP method and other useful information presented in annotation description below. Example of operation declaration for Swagger can be seen in the following code sample.

@ApiOperation annotation

You may notice the use of response parameter in @ApiOperation annotation that specifies type of response (return type) from the operation. As you can see this value can be different from method return type, since it serves only for purposes of API documentation.

Next, take a look at the use of @ApiParam. It is always useful to describe to the client what you need in order to fulfill their request. This is the primary aim of @ApiParam annotation. Whether you are working with path or query parameter, you should always provide clarification of what this parameter represents.

@ApiParam annotation

Finally, lets look at the way of documenting the actual method responses in terms of messages and HTTP codes. Swagger comes with @ApiResponse annotation, which can be used multiple times when it’s wrapped using @ApiResponses wrapper. This way you can cover all alternative execution flows of your code and provide full API operation description for clients of your API. Each response can be described in terms of HTTP return code, description of result and type of the result. For more details about @ApiResponse see description below.

@ApiResponse annotation

Using these annotations is pretty simple and provides nicely structured approach to describing features of your API. If you want to check what your documentation looks like just enter the URL pointing to the API documentation of one of your endpoints by appending the value of parameter value from @Api annotation to the URL pointing to resource listing. Be careful no to enter the value of @Path annotation be mistake (unless they have the same value). In case of my example desired URL is http://[hostname]:[port]/SpringWithSwagger/rest/api-docs/users. You should be able to see output similar to following snippet:

Creating model documentation

By supplying User class to the response parameter of several annotations in previous example, I’ve managed to introduce new undocumented element into my API documentation. Swagger was able to pull out all the structural data about User class with no regard for its relevance to the API. To counter this effect, Swagger provides two annotations to provide additional information to the users of your API and restrict visibility of your model. To mark a model class for processing by Swagger just place @ApiModel on top of your class. As usual, you can provide description as well as inheritance configuration. For more information see @ApiModel description below.

@ApiModel annotation

Last thing you need to do is to annotate class members with @ApiModelProperty annotation to provide documentation for each class member. Simple example of this can be seen in the following class.

If you need to provide more details about your model, check following description of @ApiModelProperty:

@ApiModelProperty annotation

If you follow these instructions carefully, you should end up with complete API documentation in json on previously mentioned URL. Following is only model related part of resulting json, now with provided documentation.

What is next?

If you followed all steps you should now have working API documentation that may be published or further processed by automation tools. I will showcase how to present API documentation using Swagger UI module in my next article called Spring Rest API with Swagger – Exposing documentation. The code used in this micro series is published on GitHub and provides examples for all discussed features and tools. Please enjoy! 🙂

Update 06.04.2015: Since some users reported issues with updating the dependencies used in my example project I decided to create a second project for Spring 4 to provide distinct solutions for both Spring 3 and Spring 4.

If you enjoyed this post, then make sure you subscribe to my Newsletter Newsletter and/or Feed Feed

Posted in Spring Tagged with: , , , , , , ,
24 comments on “Spring Rest API with Swagger – Creating documentation
  1. camilo lopes says:

    good post. But I have a question:for @ApiModelProperty the name of property is not informed in documentation? only type? why?

    • jakub says:

      Hi Camilo, thank you. I don’t know if I understood you correctly but when I modify Employee class like this:

      @ApiModelProperty(value = “Property Name”, required = true)
      public String getFirstName() {
      return firstName;
      }

      I end up with following json:

      “properties”:{
      “firstName”:{
      “type”:”string”,
      “description”:”Property Name”
      },
      “surname”:{
      “type”:”string”
      },
      “employeeNumber”:{
      “type”:”integer”,
      “format”:”int32″
      }
      }

      and Swagger UI displays following response model:

      Employee {
      firstName (string): Property Name,
      surname (string),
      employeeNumber (integer)
      }

  2. arockiaraj says:

    Good documentation and examples. Thanks.

  3. Tom says:

    Hi! Nice Documentation! Helped me a lot.
    @ApiResponse(code = 200, message = “A list of found users”, response=List.class)

    But in detail the list is List
    How can I annotate this? So that my api-docs shows me the information about the response that it is a List

    Further on, is it possible to create some kind of object-reference-navigation? For excample in the swagger.io.
    If response is UserBean.class which contains for example an AddressBean.class ?

    • jakub says:

      Hi Tom,

      thank you. Let me start with your List-related question. As far as I know, it is possible to set response type to a collection by using parameter responseContainer of annotation @ApiOperation with possible values: List, Array (no difference between them) and Set. So you can use this to specify response value to be the collection of type specified by the class passed to the response parameter of the very same annotation. The difference in resulting documentation is visible in both the json and Swagger UI. As an example consider following modification to my EmployeeEndpoint class – changing @ApiOperation annotation to following:

      On json level, the old "type":"Employee" will be replaced by something similar to this "type":"array","items":{"$ref":"Employee"}. Let say ‘typed collection’. However, on Swagger UI level, it is much harder to spot the change. Yet, there is one :). If you pay close attention to the response class model schema portion of documentation, you will notice the change from:

      to

      And to answer your second question – there is something, but it is not reference navigation. However, if I create Address.class with a single property and include it in my Employee.class, I will end up with all the model objects documented in Response messages model portion of documentation. Following is the resulting Swagger UI of my experiment with address.

      Hope it helps 🙂

      • Tom says:

        Hi Jakub! Thanks for the fix reply! Sorry, I have not seen that the post get swallowed all my +lt; +gt;
        It reads like a confused text. But you got it.

        It’s a shame that it’s not possible to return more complex Objects like Maps with further information about their input.

        And am I right that there is also no possibility out of the box to create a documentation about all my Beans without using them in special resources as return response?

        Would be nice to give a swagger-project my package tom.java.beans.* and it will document it.

        • jakub says:

          Hi Tom, thanks for pointing out the behavior of comment section. I wasn’t satisfied with it myself so I decided to enable Jetpacks markdown support so you should be able to use markdown without loosing any characters 🙂 Sorry about that.

          I honestly don’t know if there is solution ready, when it comes to the ‘bean related’ documentation. There might be some sort of maven plugin or something that might generate some sort of docs for this case. I encourage you to check with the vendor or at least check available plugins.

  4. Kalyan says:

    An unwanted http status code 200 is displaying in response message section in swagger UI even though i have declared useDefaultResponseMessages(false) for SwaggerSpringMvcPlugin and i have set the API response values as
    @ApiResponses(value = {
    @ApiResponse(code = 204, message = “Asset shared successfully”, response = Response.class),
    @ApiResponse(code = 422, message = “Request is not valid”, response = ErrorResource.class),
    @ApiResponse(code = 500, message = “Internal server error occured”, response = Response.class) })

    I am using swagger 1.0.2

    • jakub says:

      Hi Kalyan, I am afraid I won’t be of any help here since I have not tried Spring MVC plugin integration.

  5. Rentonie says:

    Hey, I can only get the bean config presented:

    {
    "apiVersion": "1.1",
    "swaggerVersion": "1.2",
    "info": {
    "title": "title",
    "description": "descr",
    "contact": "contact"
    }
    }

    but not the classes I annotated. I do set the ResourcePackage correctly and Scan is true, but nothing happens.

    • jakub says:

      What do you see when you crank up the logging level during context initialization? Can you see the classes you annotated being picked up and processed? Unless you can see this (under DEBUG level I believe) you didn’t set your resource scanning properly.

  6. Something is wrong with Annotation parameters in expanding sections in the article. I don’t think that they should look like this: MARKDOWN_HASH2063c1608d6e0baf80249c42e2be5804MARKDOWN_HASH

    • jakub says:

      Hi Mikhail, thanks for pointing that out. It seems like two of the plugins I use clash when <code> tag is being used. Should be fine now.

  7. Zon says:

    Hi Jakub,

    my json:
    {
    "name": "string",
    "wareHouseID": "Integer",
    "company": "string",
    "fullname": "string",
    "address": "string",
    "parentID": "int"
    }

    How to get value of “wareHouseID”:0 , my code:

    private Integer wareHouseID;
    private int parentID;
    private String name;
    private String fullname;
    private String company;
    private String address;

    public Warehouse() {
    }

    @ApiModelProperty(position = 1,required = true, dataType = "java.lang.Integer")
    public Integer getWareHouseID() {
    return wareHouseID;
    }

    public void setWareHouseID(Integer wareHouseID) {
    this.wareHouseID = wareHouseID;
    }

    Thanks 🙂

  8. manjunath says:

    Hello Jakub,

    I am not able to see the methods which I have annotated with Swagger annotation as part of operations within api-docs. Any suggestions? This is how the api-docs json looks like :

  9. Deepak says:

    Hi, I am facing issue where I see duplicates REST API docs are coming. How could we solve this error ?

    • jakub says:

      Hi Deepak, I would recommend increasing logging and checking how are your objects registered and handled. Logs usually show you where to look for the answer.

  10. iconte says:

    Thanks for posting Jakub Stas. I was looking for hours how to add field documentation to swagger. Your post is more detailed than swagger documentation!

  11. Jakub,

    In this line:

    @ApiResponse(code = 200, message = “Successful retrieval of user detail”, response = User.class)

    If the User class contained a Timestamp, say “creationDate,” Swagger displays the response model schema, for that field, as:

    creationDate”: {
    “date”: 0,
    “day”: 0,
    “hours”: 0,
    “minutes”: 0,
    “month”: 0,
    “nanos”: 0,
    “seconds”: 0,
    “time”: 0,
    “timezoneOffset”: 0,
    “year”: 0
    }, …

    How can I prevent that? In other words, my API returns this:

    “creationDate”: 1284736980000

    I’ve looked up some solutions based on “ModelConverters,” but not sure how this can be implemented in Java. Do you or anyone else have a link or feedback regarding this?

    Thanks!

    • Actually, nevermind. 🙂

      I realized I could use the “example” keyword on the ApiModelProperty annotation for that.

      Thanks anyways! And great job on your blog posts!

1 Pings/Trackbacks for "Spring Rest API with Swagger – Creating documentation"
  1. […] >> Spring Rest API with Swagger – Creating documentation […]

Leave a Reply