Building REST API with Swagger

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
Contras:
  • 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
Contras:
    • more annotations as actual code

  • 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
Contras:
  • todo

If you have found a spelling error, please, notify us by selecting that text and pressing Ctrl+Enter.

Spelling error report

The following text will be sent to our editors: