Enterprise Java

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.

package com.jakubstas.swagger.rest;

/**
 * REST endpoint for user manipulation.
 */
@Api(value = "users", description = "Endpoint for user management")
@Path("/users")
public class UsersEndpoint {
    ...
}

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/:

{
    "apiVersion":"1.0",
    "swaggerVersion":"1.2",
    "apis":[
        {
            "path":"/users",
            "description":"Endpoint for user management"
        },
        {
            "path":"/products",
            "description":"Endpoint for product management"
        },
        {
            "path":"/employees",
            "description":"Endpoint for employee listing"
        }
    ]
}

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

Describes a top-level api. Classes with @Api annotations will be included in the resource listing.

Annotation parameters:

  • value – Short description of the Api
  • description – general description of this class
  • basePath – the base path that is prepended to all @Path elements
  • position – optional explicit ordering of this Api in the resource listing
  • produces – content type produced by this Api
  • consumes – media type consumed by this Api
  • protocols – protocols that this Api requires (i.e. https)
  • authorizations – authorizations required by this Api

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

Describes an operation or typically a HTTP method against a specific path. Operations with equivalent paths are grouped in an array in the Api declaration.

Annotation parameters:

  • value – brief description of the operation
  • notes – long description of the operation
  • response – default response class from the operation
  • responseContainer – if the response class is within a container, specify it here
  • tags – currently not implemented in readers, reserved for future use
  • httpMethod – the HTTP method, i.e GET, PUT, POST, DELETE, PATCH, OPTIONS
  • position – allow explicit ordering of operations inside the Api declaration
  • nickname – the nickname for the operation, to override what is detected by the annotation scanner
  • produces – content type produced by this Api
  • consumes – media type consumed by this Api
  • protocols – protocols that this Api requires (i.e. https)
  • authorizations – authorizations required by this Api

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.

@GET
@Path("/{userName}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Returns user details", notes = "Returns a complete list of users details with a date of last modification.", response = User.class)
@ApiResponses(value = {
    @ApiResponse(code = 200, message = "Successful retrieval of user detail", response = User.class),
    @ApiResponse(code = 404, message = "User with given username does not exist"),
    @ApiResponse(code = 500, message = "Internal server error")}
)
public Response getUser(@ApiParam(name = "userName", value = "Alphanumeric login to the application", required = true) @PathParam("userName") String userName) {
    ...
}

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

Represents a single parameter in an Api Operation. A parameter is an input to the operation.

Annotation parameters:

  • name – name of the parameter
  • value – description of the parameter
  • defaultValue – default value – if e.g. no JAX-RS @DefaultValue is given
  • allowableValues – description of values this endpoint accepts
  • required – specifies if the parameter is required or not
  • access – specify an optional access value for filtering in a Filter implementation. This allows you to hide certain parameters if a user doesn’t have access to them
  • allowMultiple – specifies whether or not the parameter can have multiple values provided

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

An ApiResponse represents a type of response from a server. This can be used to describe both success codes as well as errors. If your Api has different response classes, you can describe them here by associating a response class with a response code. Note, Swagger does not allow multiple response types for a single response code.

Annotation parameters:

  • code – response code to describe
  • message – human-readable message to accompany the response
  • response – optional response class to describe the payload of the message

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:

{  
    "apiVersion":"1.0",
    "swaggerVersion":"1.2",
    "basePath":"http://[hostname/ip address]:[port]/SpringWithSwagger/rest",
    "resourcePath":"/users",
    "apis":[  
        {  
            "path":"/users/{userName}",
            "operations":[  
                {  
                    "method":"GET",
                    "summary":"Returns user details",
                    "notes":"Returns a complete list of users details with a date of last modification.",
                    "type":"User",
                    "nickname":"getUser",
                    "produces":[  
                        "application/json"
                    ],
                    "authorizations":{  

                    },
                    "parameters":[  
                        {  
                            "name":"userName",
                            "description":"Alphanumeric login to application",
                            "required":true,
                            "type":"string",
                            "paramType":"path",
                            "allowMultiple":false
                        }
                    ],
                    "responseMessages":[  
                        {  
                            "code":200,
                            "message":"Successful retrieval of user detail",
                            "responseModel":"User"
                        },
                        {  
                            "code":404,
                            "message":"User with given username does not exist"
                        },
                        {  
                            "code":500,
                            "message":"Internal server error"
                        }
                    ]
                }
            ]
        }
    ],
    "models":{
        "User":{
            "id":"User",
            "properties": {
                "surname":{"type":"string"},
                "userName":{"type":"string"},
                "lastUpdated":
                    {
                        "type":"string",
                        "format":"date-time"
                    },
                "avatar":{
                    "type":"array",
                    "items":{"type":"byte"}
                },
                "firstName":{"type":"string"},
                "email":{"type":"string"}
            }
        }
    }
}

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

A bean class used in the REST-api. Suppose you have an interface @PUT @ApiOperation(...) void foo(FooBean fooBean), there is no direct way to see what fields FooBean would have. This annotation is meant to give a description of FooBean and then have the fields of it be annotated with @ApiModelProperty.

Annotation parameters:

  • value – provide a synopsis of this class
  • description – provide a longer description of the class
  • parent – provide a superclass for the model to allow describing inheritence
  • discriminator – for models with a base class, a discriminator can be provided for polymorphic use cases
  • subTypes

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.

package com.jakubstas.swagger.model;

@ApiModel
public class User {

    private String userName;

    private String firstName;

    private String surname;

    private String email;

    private byte[] avatar;

    private Date lastUpdated;

    @ApiModelProperty(position = 1, required = true, value = "username containing only lowercase letters or numbers")
    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @ApiModelProperty(position = 2, required = true)
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @ApiModelProperty(position = 3, required = true)
    public String getSurname() {
        return surname;
    }

    public void setSurname(String surname) {
        this.surname = surname;
    }

    @ApiModelProperty(position = 4, required = true)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @JsonIgnore
    public byte[] getAvatar() {
        return avatar;
    }

    public void setAvatar(byte[] avatar) {
        this.avatar = avatar;
    }

    @ApiModelProperty(position = 5, value = "timestamp of last modification")
    public Date getLastUpdated() {
        return lastUpdated;
    }

    public void setLastUpdated(Date lastUpdated) {
        this.lastUpdated = lastUpdated;
    }
}

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

@ApiModelProperty annotation

An ApiModelProperty describes a property inside a model class. The annotations can apply to a method, a property, etc., depending on how the model scanner is configured and used.

Annotation parameters:

  • value – Provide a human readable synopsis of this property
  • allowableValues – If the values that can be set are restricted, they can be set here. In the form of a comma separated list registered, active, closed
  • access – specify an optional access value for filtering in a Filter implementation. This allows you to hide certain parameters if a user doesn’t have access to them
  • notes – long description of the property
  • dataType – The dataType. See the documentation for the supported datatypes. If the data type is a custom object, set it’s name, or nothing. In case of an enum use ‘string’ and allowableValues for the enum constants
  • required – Whether or not the property is required, defaults to false
  • position – allows explicitly ordering the property in the model. Since reflection has no guarantee on ordering, you should specify property order to keep models consistent across different VM implementations and versions

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.

{
    ...
    "models":{  
        "User":{  
            "id":"User",
            "description":"",
            "required":[  
                "userName",
                "firstName",
                "surname",
                "email"
            ],
            "properties":{  
                "userName":{  
                    "type":"string",
                    "description":"username containing only lowercase letters or numbers"
                },
                "firstName":{  
                    "type":"string"
                },
                "surname":{  
                    "type":"string"
                },
                "email":{  
                    "type":"string"
                },
                "lastUpdated":{  
                    "type":"string",
                    "format":"date-time",
                    "description":"timestamp of last modification"
                }
            }
        }
    }
}

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!

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Andrew
Andrew
9 years ago

Article is mis-labelled. This is not a Spring Rest API, it is a JAX-RS API with Swagger.

Back to top button