Swagger (OpenAPI 3.0)

Hello!!! This is my first post on Habrรฉ and I want to share with you my experience in researching a new framework for myself.





I had a moment to choose a topic and prepare a presentation for my team. Inspired by the speaker Evgeny Marenkov, I decided to choose this topic. In the process of preparation, I covered many articles and repositories in order to compactly and effectively convey the necessary information.





Now I want to share it in the hope that it will help someone in learning Swagger (OpenApi 3.0)





Introduction

I'm 99% sure many of you have had trouble finding the documentation for the controller you want. If many found it quickly, but in the end it turned out that it does not work as described in the documentation, or it does not exist at all.

Today I will prove to you that there are ways to keep the documentation up to date and in this I will be helped by the Open Source framework from SmartBear called Swagger, and since 2016 it received a new update and became known as the OpenAPI Specification.





Swagger is a framework for the RESTful API specification. Its beauty lies in the fact that it allows you not only to interactively view the specification, but also to send requests - the so-called Swagger UI.





It is also possible to generate a client or server directly according to the Swagger API specification, for this you need the Swagger Codegen.





Basic approaches

Swagger has two approaches to writing documentation:





  • Documentation is written based on your code.





    • This approach is positioned as "very simple". It is enough for us to add several dependencies to the project, add the configuration and we will already have the necessary documentation, although not as described as we wanted.





    • The project code becomes not very readable from the abundance of annotations and descriptions in them.





    • All the documentation will be written in our code (all controllers and models are converted into a kind of Java Swagger Code)





    • The approach is not advised to use if possible, but it is very easy to integrate.





  • The documentation is written separately from the code.





    • This approach requires knowledge of the Swagger Specification syntax.





    • JAML/JSON , Swagger Editor.





Swagger Tools

Swagger OpenAPI framework 4 :





  1. Swagger Core - Java Annotation.





  2. Swagger Codegen - .





  3. Swagger UI - , . , .





  4. Swagger Editor - YAML JSON .





.





Swagger Core

Swagger Code - Java- OpenAPI





Swagger Core , :





  • Java 8





  • Apache Maven 3.0.3





  • Jackson 2.4.5





, :





<dependency>
    <groupId>io.swagger.core.v3</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>2.1.6</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.5.2</version>
</dependency>
      
      



maven , YAML





<plugin>
 <groupId>org.springdoc</groupId>
 <artifactId>springdoc-openapi-maven-plugin</artifactId>
 <version>0.3</version>
 <executions>
   <execution>
   <phase>integration-test</phase>
   <goals>
     <goal>generate</goal>
   </goals>
   </execution>
 </executions>
 <configuration>
   <apiDocsUrl>http://localhost:8080/v3/api-docs</apiDocsUrl>
   <outputFileName>openapi.yaml</outputFileName>
   <outputDir>${project.build.directory}</outputDir>
 </configuration>
</plugin>
      
      



.





Swagger . , API, API





    @Bean
    public GroupedOpenApi publicUserApi() {
        return GroupedOpenApi.builder()
                             .group("Users")
                             .pathsToMatch("/users/**")
                             .build();
    }

    @Bean
    public OpenAPI customOpenApi(@Value("${application-description}")String appDescription,
                                 @Value("${application-version}")String appVersion) {
        return new OpenAPI().info(new Info().title("Application API")
                                            .version(appVersion)
                                            .description(appDescription)
                                            .license(new License().name("Apache 2.0")
                                                                  .url("http://springdoc.org"))
                                            .contact(new Contact().name("username")
                                                                  .email("test@gmail.com")))
                            .servers(List.of(new Server().url("http://localhost:8080")
                                                         .description("Dev service"),
                                             new Server().url("http://localhost:8082")
                                                         .description("Beta service")));
    }
      
      



, .





:





  • @Operation - HTTP .





  • @Parameter - OpenAPI.





  • @RequestBody -





  • @ApiResponse -





  • @Tag - OpenAPI.





  • @Server - OpenAPI.





  • @Callback -





  • @Link - .





  • @Schema - .





  • @ArraySchema - .





  • @Content - .





  • @Hidden - ,





:





@Tag(name = "User", description = "The User API")
@RestController
public class UserController {}
      
      



    @Operation(summary = "Gets all users", tags = "user")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "200",
                    description = "Found the users",
                    content = {
                            @Content(
                                    mediaType = "application/json",
                                    array = @ArraySchema(schema = @Schema(implementation = UserApi.class)))
                    })
    })
    @GetMapping("/users")
    public List<UserApi> getUsers()
      
      



Swagger Codegen

Swagger Codegen - , API ( SDK), OpenAPI.





/ :





  • API clients:





    • Java (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured)





    • Kotlin





    • Scala (akka, http4s, swagger-async-httpclient)





    • Groovy





    • Node.js (ES5, ES6, AngularJS with Google Closure Compiler annotations)





    • Haskell (http-client, Servant)





    • C# (.net 2.0, 3.5 or later)





    • C++ (cpprest, Qt5, Tizen)





    • Bash





  • Server stub:





    • Java (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy, Play Framework, PKMST)





    • Kotlin





    • C# (ASP.NET Core, NancyFx)





    • C++ (Pistache, Restbed)





    • Haskell (Servant)





    • PHP (Lumen, Slim, Silex, Symfony, Zend Expressive)





    • Python (Flask)





    • NodeJS





    • Ruby (Sinatra, Rails5)





    • Rust (rust-server)





    • Scala (Finch, Lagom, Scalatra)





  • API documentation generators:





    • HTML





    • Confluence Wiki





  • Other:





    • JMeter





, , Swagger:





<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.4.18</version>
</dependency>
      
      



OpenApi 3.0, :





<dependency>
    <groupId>io.swagger.codegen.v3</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>3.0.24</version>
</dependency>
      
      



maven , .





      <plugin>
        <groupId>org.openapitools</groupId>
        <artifactId>openapi-generator-maven-plugin</artifactId>
        <version>3.3.4</version>
        <executions>
          <execution>
            <phase>compile</phase>
            <goals>
              <goal>generate</goal>
            </goals>
            <configuration>
              <generatorName>spring</generatorName>
              <inputSpec>${project.basedir}/src/main/resources/api.yaml</inputSpec>
              <output>${project.build.directory}/generated-sources</output>
              <apiPackage>com.api</apiPackage>
              <modelPackage>com.model</modelPackage>
              <supportingFilesToGenerate>
                ApiUtil.java
              </supportingFilesToGenerate>
              <configOptions>
                <groupId>${project.groupId}</groupId>
                <artifactId>${project.artifactId}</artifactId>
                <artifactVersion>${project.version}</artifactVersion>
                <delegatePattern>true</delegatePattern>
                <sourceFolder>swagger</sourceFolder>
                <library>spring-mvc</library>
                <interfaceOnly>true</interfaceOnly>
                <useBeanValidation>true</useBeanValidation>
                <dateLibrary>java8</dateLibrary>
                <java8>true</java8>
              </configOptions>
              <ignoreFileOverride>${project.basedir}/.openapi-generator-ignore</ignoreFileOverride>
            </configuration>
          </execution>
        </executions>
      </plugin>
      
      



.





codegen help , Swagger Codegen:





  • config-help -





  • generate -





  • help - openapi-generator





  • list -





  • meta - Codegen. .





  • validate -





  • version - ,





validate, generate,  Client Java





  • java -jar openapi-generator-cli-4.3.1.jar validate -i openapi.yaml





  •  java -jar openapi-generator-cli-4.3.1.jar generate -i openapi.yaml -g java --library jersey2 -o client-gener-new





Swagger UI

Swagger UI - API - . OpenAPI ( Swagger), .





Swagger UI pet-project:





"Try it out", :





Swagger Editor

Swagger Editor - Swagger API YAML . Swagger JSON Swagger ( , . .).





OpenAPI 3.0 . , :





  1. openapi





  2. info





  3. servers





  4. paths





  5. components





  6. security





  7. tags





  8. externalDocs





- Swagger Swagger : , Swagger UI. Swagger .





Swagger , , . , X- , .





openapi. OpenAPI. Swagger swagger:





 openapi: "3.0.2"
      
      







info API, , , , , . .





info:
  title: "OpenWeatherMap API"
  description: "Get the current weather, daily forecast for 16 days, and a three-hour-interval forecast for 5 days for your city."
  version: "2.5"
  termsOfService: "https://openweathermap.org/terms"
  contact:
  	name: "OpenWeatherMap API"
    url: "https://openweathermap.org/api"
    email: "some_email@gmail.com"
  license:
    name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)"
    url: "https://openweathermap.org/price"
      
      



servers , API. - URL, . servers . URL-:





servers:
  - url: https://api.openweathermap.org/data/2.5/
        description: Production server
  - url: http://beta.api.openweathermap.org/data/2.5/
        description: Beta server
  - url: http://some-other.api.openweathermap.org/data/2.5/
        description: Some other server
      
      



paths - โ€œ โ€ OpenAPI. path operations - GET, POST, PUT, DELETE:





paths:
  /weather:
     get:
      
      



components OpenAPI. components , . API parameters responses components





Conclusions

  • (Swagger UI, Open Specifiation)





  • Java, PHP, .NET, JavaScrypt (Swager Editor, Swagger Codegen)





  • .





  • , ,












All Articles