24 Kasım 2020 Salı

Swagger (OpenAPI ) Kullanımı

Giriş
Açıklaması şöyle
- Springfox has evolved from a project originally created by Marty Pitt and was named swagger-springmvc. Much kudos goes to Marty.
- springfox-swagger is an implementation of this specification based on the Spring ecosystem.
- springfox-swagger-ui encapsulates swagger-ui, making it possible to use Spring services.

Maven
Swagger 3 için şu satırı dahil ederiz
<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-boot-starter</artifactId>
  <version>3.0.0</version>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>3.0.0</version>
</dependency>
Adresler
JSON çıktı için şu adrese gideriz
http://localhost:8000/api-doc
YAML çıktı için şu adrese gideriz
http://localhost:8000/api-doc/swagger.yaml
Swagger 3 UI için şu adrese gideriz
http://localhost:8080/swagger-ui/index.html
Swagger UI
GET, POST işlemleri farklı renklerde. Şeklen şöyle
Her işlemin detayı şöyle


Bir örnek burada.

Select a Definition
Açıklaması burada. Eğer hiç bir ayar yapmazsak "default" olarak gelir. Docket.groupName() ile yeni bir definition eklenir.

OAS3
Specification v3 olduğunu gösterir Şeklen şöyle

Şeklen şöyle



Docket Sınıfı
Şu satırı dahil ederiz
import springfox.documentation.spring.web.plugins.Docket;
apis metodu
Örnek
Şöyle yaparız
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SpringFoxConfig {
  @Bean
  public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build();
  }
}
globalRequestParameters metodu
Örnek
Şöyle yaparız. Böylece GET isteğine limit ve pages parametreleri geçilmeli diye belirtiyoruz.
import springfox.documentation.service.ParameterType;
import springfox.documentation.service.RequestParameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Bean
public Docket getDocketInstanceEx1() {
  final Set<String> produces = new HashSet<String>();
  produces.add(MediaType.APPLICATION_JSON_VALUE);
  produces.add(MediaType.APPLICATION_XML_VALUE);
		
  List<RequestParameter> listRequestParamters = new ArrayList<>();
  RequestParameter limitParameter = new RequestParameterBuilder()
    .name("limit") 
    .required(false)
    .query(q -> q.model(modelSpecificationBuilder -> modelSpecificationBuilder.scalarModel(ScalarType.STRING)))
    .in(ParameterType.QUERY)
    .build();
  RequestParameter pagesParameter = new RequestParameterBuilder()
    .name("pages")
    .required(false)
    .query(q -> q.model(modelSpecificationBuilder -> modelSpecificationBuilder.scalarModel(ScalarType.STRING)))
    .in(ParameterType.QUERY)
    .build();
  listRequestParamters.add(limitParameter);
  listRequestParamters.add(pagesParameter);
		
  return new Docket(DocumentationType.SWAGGER_2)
    .produces(produces)
    .consumes(produces)
    .globalRequestParameters(listRequestParamters)
    .select()
    .apis(RequestHandlerSelectors.basePackage("ro.stefan.controller"))
    .paths(PathSelectors.any())
    .build();
}	

produces metodu
Bu alana girilen değer API Documentation sayfasında Response Content Type alanında görülebiliyor. Açıklaması şöyle
Because as mentioned already an API can accept and return data in different formats (json, xml, etc.) so we can use consumes and produces to specify the MIME types understood by your API. To set the consumes and produces type is easy and just represents an array of MIME type.
This modification as presented in the examples are done globally so that means that all controllers from that spring boot project will render this but you can override this value at API level (method from the controller) if you have exceptions.
Örnek - global olarak kullanım
Şöyle yaparız
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SpringFoxConfig {
 
 @Bean
 public Docket getDocketInstance() {
  final Set<String> produces = new HashSet<String>();
  produces.add(MediaType.APPLICATION_JSON_VALUE);
  produces.add(MediaType.APPLICATION_XML_VALUE);
  
  return new Docket(DocumentationType.SWAGGER_2)
    .produces(produces)
    .select()
    .apis(RequestHandlerSelectors.basePackage("ro.stefan.controller"))
    .paths(PathSelectors.any())
    .build();
 }
}
select metodu
Örnek
Şu bean'i yaratmak gerekir.
@Configuration
public class SwaggerConfig {
  @Bean
  public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
      .select()
      // .apis(RequestHandlerSelectors.any())
      .apis(RequestHandlerSelectors.basePackage("com.tahaburak.atem.controller"))
      .paths(PathSelectors.any())
      .build();
  }
}
ApiInfo  Sınıfı
Şu satırı dahil ederiz
import io.swagger.model.ApiInfo;
Örnek
Şöyle yaparız
@Configuration
public class SwaggerConfiguration {

  @Bean
  public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
      .select()
      .apis(RequestHandlerSelectors.any())
      .paths(PathSelectors.any())
      .build()
      .apiInfo(apiInfo());
  }

  private ApiInfo apiInfo() {
    return new ApiInfo(
      "Spring Boot Simple REST API",
      "Spring Boot Simple REST API Swagger Documentation",
      "Version 1",
      "urn:tos",
      new Contact("Admin", "www.datamify.com", "info@datamify.com"),
        "Apache 2.0",
        "https://www.apache.org/licenses/LICENSE-2.0",
        new ArrayList<>());
  }
}

Hiç yorum yok:

Yorum Gönder