Home > Java > javaTutorial > body text

Detailed introduction to using Swagger in Java API development

WBOY
Release: 2023-06-17 23:38:37
Original
1372 people have browsed it

In Java API development, Swagger is a very useful tool. Swagger is an open source API framework for describing, designing and generating RESTful web services. It provides a set of annotations to help developers describe APIs and parameters. In this article, I will detail how to use Swagger in Java API development.

  1. Installing Swagger

Swagger can be integrated into Java projects using Maven. You can add Swagger to your project using the following Maven dependencies:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
Copy after login

Additionally, you need to add the following dependencies for generating the Swagger UI:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
Copy after login
  1. Configuring Swagger

In your Java application, you need to configure Swagger. To do this, you can create a configuration class to initialize Swagger:

@Configuration
@EnableSwagger2
public class SwaggerConfig {    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                          
    }
}
Copy after login

In the above code, we define a Docket bean, which is the main interface of Swagger. We use this to specify the type of Swagger API and map it with the application's URL.

  1. Add Swagger annotations

Now you can add Swagger annotations in the Java API. The following are some commonly used Swagger annotations and their uses:

  • @Api: used to describe the entire API.
  • @ApiOperation: used to describe API operations.
  • @ApiParam: used to describe operation parameters.
  • @ApiModel: Model attributes used to provide APIs.
  • @ApiModelProperty: Properties used to describe the API model.

These annotations can be placed on classes, methods, fields, and method parameters, and can provide information about API comments by using the value and notes attributes.

For example, if you have the following code snippet:

@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        // code to get user
    }
}
Copy after login

You can use Swagger annotations to describe the getUser method:

@RestController
@RequestMapping("/users")
@Api(value="用户管理", tags="用户管理")
public class UserController {
 
    @GetMapping("/{id}")
    @ApiOperation(value="获取用户信息", notes="根据用户ID获取用户信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    public User getUser(@PathVariable Long id) {
        // code to get user
    }
}
Copy after login

In the above code, we used @Api and @ApiOperation annotation. @Api annotation is used to describe the entire API, including name and label. The @ApiOperation annotation is used to describe the name of the operation, as well as some notes about the operation.

  1. Generate Swagger UI

Now that your Java application has been configured with Swagger and Swagger annotations, you can use Swagger UI to display and test the API.

To do this, you can add the following line to the SwaggerConfig class under the @Bean annotation:

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

    @Bean
    public UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
            .docExpansion(DocExpansion.LIST)
            .build();
    }
}
Copy after login

This will add a uiConfig() bean for configuring the Swagger UI. Using the code above, we set DocExpansion to LIST so that all actions are expanded by default in the UI.

  1. Start the application

Now you have configured Swagger and Swagger annotations and generated the Swagger UI in the SwaggerConfig class. You can launch the application using the following command:

$ mvn spring-boot:run
Copy after login

As per Swagger's default settings, you can access the Swagger UI from a browser. Navigate to http://localhost:8080/swagger-ui.html and you will see that Swagger UI already displays your API.

  1. Testing the API

Finally, you can use Swagger UI to test the API. By clicking the "Try it" button, Swagger UI will automatically send a request to your API and you will see the response in the UI.

In this article, I introduced how to use Swagger in Java API development. Using Swagger, you can easily describe and test your API, and you can generate documentation that is easy to read and use. If you are a Java developer, I encourage you to try Swagger to simplify API development and testing.

The above is the detailed content of Detailed introduction to using Swagger in Java API development. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!