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 Apidescription
– general description of this classbasePath
– the base path that is prepended to all@Path
elementsposition
– optional explicit ordering of this Api in the resource listingproduces
– content type produced by this Apiconsumes
– media type consumed by this Apiprotocols
– 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 operationnotes
– long description of the operationresponse
– default response class from the operationresponseContainer
– if the response class is within a container, specify it heretags
– currently not implemented in readers, reserved for future usehttpMethod
– theHTTP
method, i.eGET
,PUT
,POST
,DELETE
,PATCH
,OPTIONS
position
– allow explicit ordering of operations inside the Api declarationnickname
– the nickname for the operation, to override what is detected by the annotation scannerproduces
– content type produced by this Apiconsumes
– media type consumed by this Apiprotocols
– 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 parametervalue
– description of the parameterdefaultValue
– default value – if e.g. no JAX-RS@DefaultValue
is givenallowableValues
– description of values this endpoint acceptsrequired
– specifies if the parameter is required or notaccess
– specify an optional access value for filtering in aFilter
implementation. This allows you to hide certain parameters if a user doesn’t have access to themallowMultiple
– 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 describemessage
– human-readable message to accompany the responseresponse
– 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 classdescription
– provide a longer description of the classparent
– provide a superclass for the model to allow describing inheritencediscriminator
– for models with a base class, a discriminator can be provided for polymorphic use casessubTypes
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 propertyallowableValues
– If the values that can be set are restricted, they can be set here. In the form of a comma separated listregistered, active, closed
access
– specify an optional access value for filtering in aFilter
implementation. This allows you to hide certain parameters if a user doesn’t have access to themnotes
– long description of the propertydataType
– 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 constantsrequired
– Whether or not the property is required, defaults to falseposition
– 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!
Reference: | Spring Rest API with Swagger – Creating documentation from our JCG partner Jakub Stas at the Jakub Stas blog. |
Article is mis-labelled. This is not a Spring Rest API, it is a JAX-RS API with Swagger.