3

Java 8 を使用して、SpringBoot および Spring REST サービスを使用して API を構築しています。Swagger API を発見したばかりで、API Swagger に準拠させたいと考えています。

私が読んだ限りでは、Swagger は API を文書化するためのツールですが、API とやり取りするための優れた Web インターフェイスに加えて、仕様 (v2 の swagger.json) からクライアントとサーバーのコードを生成する機能も提供します。

ここで、少なくとも 15 個のコントローラーを備えた既存の API を既に持っていることを考慮して、続行する方法についていくつかの推奨事項を希望します。仕様全体 (swagger.json ファイル) を最初から作成してから、codegen を使用してサーバー コード (コントローラーとオブジェクト) を生成する必要がありますか? または、既存のコントローラーに Swagger-core アノテーションを付けて、そこから json 仕様を生成するほうがよいでしょうか?

2 番目の選択肢の方が理にかなっていますが、既存の API から swagger.json 仕様を生成する方法がわかりません (可能な場合)。

それについていくつかの推奨事項を教えてください。

ありがとう

4

2 に答える 2

8

Integrating swagger with spring boot or spring cloud is very easy.

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.

pom.xml dependencies

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

define api info in your springboot application

@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();
}

Annotations

@EnableSwagger2 for your Application class

Annotate your REST APIs

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: https://github.com/sanketsw/SpringBoot_REST_API

于 2016-03-10T05:01:42.990 に答える