Building REST API with Swagger
Swagger is one of the most popular specifications for developing APIs on the market right now.
There are different ways how to work with it. I’ll describe my practical experience.
Code generation
By this approach, the REST API is described in a human- (YAML) or machine-readable (JSON) way.
The client/server code is generated with Swagger codegen.
Pros:
- You can write YAML API specification befor decision about the implementation language
- additional step to generate source stub + manual copy generated java interfaces to target project
- not possible to rename the class for REST DTO, because it is used for model definition and will cause a lot compile errors in generated clients
YAML generation. Official swagger way
There are several frameworks to generate YAML for Swagger. In Java many of these frameworks rely heavily on annotations. The official swagger library works that way.
Pros:
- todo
-
- more annotations as actual code
1 2 3 4 5 6 7 8 9 10 11 12 |
@GET @Path("/{userName}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Returns user details", notes = "Returns a complete list of users details with 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 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) { ... } |
- documentation / annotation / Javadoc reflects sometimes not to 100% your Java backend code
If you happen to do contract first, it is not a pleasant experience to write the YAML yourself for non-trivial APIs even with the swagger editor.
YAML generation with JAX-RS Analyzer
This is my preferred way to design REST API.
If you use Java JAX-RS for REST backend, the JAX-RS Analyzer would be my recomendation.
It generates an overview of all JAX-RS resources in a project by bytecode analysis (not just by reflection).
Pros:
- Genuine docs. Generated Swagger yaml/json specification reflects your Java backend code and always actual
- Readability. You don’t need additional swagger annotations on your JAX-RS resource methods
- todo
Spelling error report
The following text will be sent to our editors: