Swagger etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Swagger etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

9 Ekim 2023 Pazartesi

Swagger @Hidden Anotasyonu

Giriş
Şu satırı dahil ederiz
import io.swagger.v3.oas.annotations.Hidden;
Örnek
Şöyle yaparız
@RestController
@Hidden
public class HiddenController {
    @GetMapping("/hiddenEndpoint")
    public String hiddenEndpoint() {
        return "This endpoint will be hidden.";
    }
}
Örnek
Şöyle yaparız
@RestController
public class MixedVisibilityController {
    @GetMapping("/publicEndpoint")
    public String publicEndpoint() {
        return "This is a public endpoint.";
    }

    @Hidden
    @GetMapping("/privateEndpoint")
    public String privateEndpoint() {
        return "This is a private endpoint.";
    }
}

8 Kasım 2021 Pazartesi

Swagger @Tag Anotasyonu

Giriş
Şu satırı dahil ederiz
import io.swagger.v3.oas.annotations.tags.Tag;
Açıklaması şöyle
In springfox implementation this tag represents the equivalent of the tag @Api
name Alanı
Örnek
Şöyle yaparız. Burada @Tags içinde @Tag anotasyonları var
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.tags.Tags;

import java.util.Arrays;
import java.util.List;

@RestController
@Tags(value = {@Tag(name = "User")})
public class UserController {

  @GetMapping("/users")
  @Tags(value = {@Tag(name = "User")})
  @Operation(
    summary = "Get Users",
    description = "Get Users",
    responses = {@ApiResponse(
      responseCode = "200",
      content = {@Content(mediaType = "application/json")}
     )}
   )
  public List<User> getUsers() {
    ...
  }
  ...
}

Örnek
Şöyle yaparız. Aynı Tag değeri @Operation içinde kullanılabilir.
@RestController
@RequestMapping("/people")
@Tag(name = "People", description = "Endpoints for managing people")
public class PersonController {
  ...
}

9 Ekim 2021 Cumartesi

Swagger @Operation Anotasyonu - Controller'a Eklenir

Giriş
Şu satırı dahil ederiz
import io.swagger.v3.oas.annotations.Operation;
Açıklaması şöyle
In springfox implementation this tag represents the equivalent of the tag @ApiOperation
Açıklaması şöyle
@Operation - Adds details about what the endpoint does, including some properties to achieve this.

summary - The summary (or title) of an endpoint.
description - The description of the endpoint.
tags - What tags to group the endpoint under. You don’t have to specify an array here if there is a single tag; writing tags = "People" also works.
responses - An array of @ApiResponses that details what the endpoint can return, allowing you to show what happens on successful requests as well as unsuccessful or erroneous requests.
operationId Alanı
Örnek
Şöyle yaparız
@Operation(operationId = "deleteJob", summary = "Delete a scheduled job")
responses Alanı
Örnek
Şöyle yaparız
@GetMapping("/{id}")
@Operation( summary = "Finds a person", description = "Finds a person by their Id.", tags = { "People" }, responses = { @ApiResponse( description = "Success", responseCode = "200", content = @Content(mediaType = "application/json", schema = @Schema(implementation = Person.class)) ), @ApiResponse(description = "Not found", responseCode = "404", content = @Content), @ApiResponse(description = "Internal error", responseCode = "500", content = @Content) } ) public ResponseEntity<Person> get(@PathVariable("id") @Parameter(description = "The Id of the person to find.") UUID id) { return personRepository.findById(id).map(ResponseEntity::ok) .orElseThrow(() -> new NoSuchElementException("Person with id: " + id + " does not exist")); }

summary Alanı
Örnek
Şöyle yaparız
@Operation(summary = "Creates a new book")
@ApiResponses(value = {
  @ApiResponse(responseCode = "201", description = "Created book"),
  @ApiResponse(responseCode = "400", description = "Bad request"),
  @ApiResponse(responseCode = "500", description = "Server Error")
@PostMapping(path = "/books", consumes = {"application/json"})
public ResponseEntity<Void> create(@Valid @RequestBody BookDto bookDto) {
  ...
}

30 Eylül 2021 Perşembe

Swagger @ApiResponse Anotasyonu

Giriş
Şu satırı dahil ederiz
import io.swagger.annotations.ApiResponses;
content Alanı
Örnek
Şöyle yaparız
@GetMapping
@Operation(summary = "Get the universities for a given country")
@ApiResponses(value = {
  @ApiResponse(responseCode = "200", description = "...",
               content = {@Content(mediaType = "application/json",
                                schema = @Schema(implementation = UniversityDTO.class))}),
  @ApiResponse(responseCode = "400", description = "Invalid id ",content = @Content),
  @ApiResponse(responseCode = "404", description = "...", content = @Content)})
  public List<UniversityDTO> getUniversitiesForCountry(@RequestParam String country) {
    ...
  }
}
responseCode Alanı
Örnek 
Şöyle yaparız
@Operation(summary = "Create customer")
@ApiResponses(value = {
  @ApiResponse(responseCode = "201", description = "Successfully created a customer"),
  @ApiResponse(responseCode = "400", description = "Bad Request"),
  @ApiResponse(responseCode = "401", description = "Authorization denied"),
  @ApiResponse(responseCode = "500", description = "Unexpected system exception"),
  @ApiResponse(responseCode = "502", description = "An error has occurred with an upstream service")
})
@PostMapping(consumes = JSON)
public ResponseEntity createCustomer(@Valid @RequestBody CustomerInfo customerInfo, UriComponentsBuilder uriBuilder)
  throws Exception {
  ...
}

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

16 Ocak 2020 Perşembe