76220

Advice about Swagger API

Question:

I'm building an API using SpringBoot and Spring REST services using Java 8. I've just discovered Swagger API and now I would like to make my API Swagger compliant.

As far I read, Swagger is a tool to document your APIS, but also provides functionalities to generate the client and server code from an specification (swagger.json in v2), besides of a nice web interface to interact with your API.

Now, I would like some recommendations about how to proceed, given that I already have an existing API with at least 15 controllers. Should I write the whole spec from scratch (the swagger.json file) and then use codegen to generate the server code (controllers and objects)? Or would be better to annotate the existing controllers with Swagger-core annotations, and then generate a json spec from there?

The second choice makes more sense to me but I don't know how we generate the swagger.json spec from the existing API (if possible).

Could you please give me some recommendations about it?

Thanks

Answer1:

<h2>Integrating swagger with spring boot or spring cloud is very easy.</h2>

Only a few annotations to your existing REST APIs and it will generate whole swagger specification for you automatically. Swagger is definitely one of the most popular REST API documentation frameworks.

<h3>pom.xml dependencies</h3> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> <scope>compile</scope> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> <scope>compile</scope> </dependency> <h3>define api info in your springboot application</h3> @Bean public Docket newsApi() { return new Docket(DocumentationType.SWAGGER_2) .groupName("springboot") .apiInfo(apiInfo()) .select() .paths(regex("/.*")) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("SpringBoot REST API with Swagger") .description("SpringBoot REST API with Swagger") .termsOfServiceUrl("http://www-03.ibm.com/software/sla/sladb.nsf/sla/bm?Open") .contact("sanket**@au1.ibm.com") .license("Apache License Version 2.0") .licenseUrl("https://github.com/IBM-Bluemix/news-aggregator/blob/master/LICENSE") .version("2.0") .build(); } <h3>Annotations</h3>

@EnableSwagger2 for your Application class

<h3>Annotate your REST APIs</h3>

Something like this

@RequestMapping(value = "/operate/add/{left}/{right}", method = RequestMethod.GET, produces = "application/json") @ApiOperation(value = "addNumbers", nickname = "addNumbers") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = Result.class), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 500, message = "Failure") }) public Result add(@PathVariable("left") int left, @PathVariable("right") int right) {

You are done. The Swagger UI is included by default and you can also access the swagger specs in JSON format. Access http://localhost:12001/swagger-ui.html#/

Refer to this code base for more details: <a href="https://github.com/sanketsw/SpringBoot_REST_API" rel="nofollow">https://github.com/sanketsw/SpringBoot_REST_API</a>

Answer2:

I realise this is late in coming, but here's an alternative for you to consider: instead of generating the OpenAPI API description from your implementation, you could hand-write the OpenAPI API description, then have your implementation read it at startup time and automatically configure its URL routing, response types etc accordingly.

Ie generate the implementation from the documentation, rather than generating documentation from the implementation.

I've no idea how feasible this would be in Spring (sorry). It wasn't difficult with Python and WSGI.

Whether this is a good idea or not is a judgement call only you can make.

Recommend

  • Springfox - Is it possible to document a POJO via annotation if it's not used in a controller
  • Swagger API Operations Ordering
  • How to check Facetime Support in ios devices (harware check)
  • Infinispan custom cache command factory not installed
  • How do I fix 'Source not found' error when debugging in Eclipse, using Selenium WebDriver?
  • response time is higher, when I call procedure in oracle through simple Jdbc call compared to the lo
  • UItextField data disappears when I scroll through the TableView — Swift
  • PowerShell + AD: Return users from within any groups in a specific OU, plus count
  • Exception while loading assemblies: Could not load assembly 'Microsoft.Data.Sqlite'
  • Block scroll in ScrollView when touch on android.gesture.GestureOverlayView
  • openOptionsMenu() across android versions
  • Chaining Requests using BlueBird/ Request-Promise
  • How to process future stream to create an instance of class with list property
  • R: Hide dummies output
  • Footer appears next to section instead of below
  • How do I use RestSharp to POST a login and password to an API?
  • Tensorflow transform on beams with flink runner
  • Search image on Google images with the new Custom Search API?
  • How to achieve density/heat map effect in iOS (iPhone/iPad)?
  • Encode string to Base64 in Inno Setup (Unicode Version of Inno Setup)
  • What is need of Assign/Deassign in Verilog?
  • Arc gradients in Flutter?
  • Saving CLLocation error: Mutating method sent to immutable object
  • Opening tel: links from UIWebView
  • Django self join , How to convert this query to ORM query
  • Getting/building the SQL (with parameters) from NHibernate 3.2
  • How to move to lines with the same indentation in Visual Studio Code
  • PowerShell script to pass SecureString to Plink as account and sudo passwords
  • Facebook friend list in Facebook Android SDK 3.14
  • How to find angle formed by the blades of a wind turbine with respect to a horizontal imaginary axis
  • Silverlight Event Log in Isolated Storage
  • How to split wav file into two or more parts using c#
  • Apple Mach-O Linker error (“duplicate symbol”)
  • PHP Permalinks.. how to change?
  • media foundation H264 decoder not working properly
  • Running R's aov() mixed effects model from Python using rpy2
  • What does the “id” field in an Android “Google Play Music” broadcast intent correspond to?
  • Access to a Matlab gui from the web