Home Java javaTutorial Use Spring Boot and Swagger to build RESTful API documentation

Use Spring Boot and Swagger to build RESTful API documentation

Jun 23, 2023 pm 01:51 PM
spring boot swagger restful api

In today's web development, RESTful API has become a very popular way for developers to build websites and applications. Using RESTful API, developers can build clear APIs to interact with other applications or services more conveniently. In order to better manage and maintain these APIs, document writing and management have also become a very critical part.

Spring Boot is a framework for quickly building Java applications, which is simple, fast, and easy to expand. Swagger is a tool specifically used to design, build and document RESTful APIs. It can quickly generate RESTful API documents and automatically generate sample flows of API requests and responses.

This article will introduce how to use Spring Boot and Swagger to build RESTful API documents.

1. Create a Spring Boot project

First, we need to use Spring Initializr to create a Spring Boot project, which can be created through https://start.spring.io/. Here, we select the two dependencies Web and Swagger 2. After the creation is completed, we import the project into the integrated development environment and add the Swagger dependency in pom.xml:

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

2. Create a RESTful API

Here we create a simple RESTful API for generating a random number.

We add a method in the Controller:

@RestController
public class NumberController {
 
   @ApiOperation(value = "Generate a random number between 1 and 100")
   @RequestMapping(value = "/generateNumber", method = RequestMethod.GET)
   public ResponseEntity<Integer> generateNumber() {
       Random random = new Random();
       int randomNumber = random.nextInt(100) + 1;
       return ResponseEntity.ok(randomNumber);
   }
}
Copy after login

It should be noted that not only the @RestController annotation needs to be added to the class, but also the @Api annotation needs to be used to describe the role of this Controller.

Decompiled content:

package com.example.demo.controller;

import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@RestController
public class NumberController
{

    public NumberController()
    {
    }

    @ApiOperation(value="Generate a random number between 1 and 100")
    @RequestMapping(value="/generateNumber", method=RequestMethod.GET)
    public ResponseEntity generateNumber()
    {
        Random random = new Random();
        int randomNumber = random.nextInt(100) + 1;
        return ResponseEntity.ok(new Integer(randomNumber));
    }
}
Copy after login

3. Configuring Swagger

After completing the development of the corresponding Controller, we need to configure Swagger. Add Swagger related configuration to the Spring Boot configuration file application.properties.

#指定Swagger API扫描的路径
swagger.basePackage=com.example.demo.controller
 
#应用名称
swagger.title=Spring Boot Swagger Example
 
#版本号
swagger.version=1.0.0
 
#描述信息
swagger.description=This is a demo service for Spring Boot Swagger.
 
#联系人信息
swagger.contact.name=John Doe
swagger.contact.url=http://www.example.com
swagger.contact.email=john.doe@example.com
Copy after login

Annotation description:

@Api: Used to describe the role of Controller, similar to the @Controller and @RequestMapping annotations in Spring MVC.

@ApiIgnore: used for ignored APIs and will not be displayed in the generated API documentation.

@ApiOperation: used to describe specific API operations, including method name, request method, request parameters, return object and other information, which can be placed on the method or class.

@ApiImplicitParam: used to describe request parameters, including parameter name, parameter type, necessity and other information.

@ApiModel: used to describe JavaBean classes.

@ApiParam: used to describe parameter information.

@ApiResponses: Used to describe API responses, including HTTP status code, response data and other information.

@ApiProperty: used to describe the property information of the JavaBean class.

4. View API documentation

After completing the above configuration, we start the Spring Boot application and visit http://localhost:8080/swagger-ui.html. We can view the generated API documentation in the browser. Here we can view the detailed information of the API we just wrote, including request method, request parameters, return results, etc. At the same time, Swagger can also generate a sample stream of requests and responses to facilitate developers to reference and test.

Here, we use Spring Boot and Swagger to build RESTful API documentation. Using this method, developers can build and manage their own API documents more quickly, improving development efficiency and maintainability.

The above is the detailed content of Use Spring Boot and Swagger to build RESTful API documentation. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spring Boot+MyBatis+Atomikos+MySQL (with source code) Spring Boot+MyBatis+Atomikos+MySQL (with source code) Aug 15, 2023 pm 04:12 PM

In actual projects, we try to avoid distributed transactions. However, sometimes it is really necessary to do some service splitting, which will lead to distributed transaction problems. At the same time, distributed transactions are also asked in the market during interviews. You can practice with this case, and you can talk about 123 in the interview.

Achieve multi-language support and international applications through Spring Boot Achieve multi-language support and international applications through Spring Boot Jun 23, 2023 am 09:09 AM

With the development of globalization, more and more websites and applications need to provide multi-language support and internationalization functions. For developers, implementing these functions is not an easy task because it requires consideration of many aspects, such as language translation, date, time and currency formats, etc. However, using the SpringBoot framework, we can easily implement multi-language support and international applications. First, let us understand the LocaleResolver interface provided by SpringBoot. Loc

How to use Spring Boot to build big data processing applications How to use Spring Boot to build big data processing applications Jun 23, 2023 am 09:07 AM

With the advent of the big data era, more and more companies are beginning to understand and recognize the value of big data and apply it to business. The problem that comes with it is how to handle this large flow of data. In this case, big data processing applications have become something that every enterprise must consider. For developers, how to use SpringBoot to build an efficient big data processing application is also a very important issue. SpringBoot is a very popular Java framework that allows

Spring Boot implements MySQL read-write separation technology Spring Boot implements MySQL read-write separation technology Aug 15, 2023 pm 04:52 PM

How to achieve read-write separation, Spring Boot project, the database is MySQL, and the persistence layer uses MyBatis.

Design and development of RESTful API using routing module in PHP Design and development of RESTful API using routing module in PHP Oct 15, 2023 am 11:36 AM

Design and development of RESTfulAPI using routing module in PHP With the continuous development of the Internet, there are more and more Web-based applications, and the REST (RepresentationalStateTransfer) interface has become a common method for designing and developing Web services. In PHP, implementing RESTfulAPI can simplify development and management through routing modules. This article will introduce how to use the routing module in PHP to design and develop RES

Technical practice of Docker and Spring Boot: quickly build high-performance application services Technical practice of Docker and Spring Boot: quickly build high-performance application services Oct 21, 2023 am 08:18 AM

Technical practice of Docker and SpringBoot: quickly build high-performance application services Introduction: In today's information age, the development and deployment of Internet applications have become increasingly important. With the rapid development of cloud computing and virtualization technology, Docker, as a lightweight container technology, has received widespread attention and application. SpringBoot has also been widely recognized as a framework for rapid development and deployment of Java applications. This article will explore how to combine Docker and SpringB

Using WebSocket in Spring Boot to implement push and notification functions Using WebSocket in Spring Boot to implement push and notification functions Jun 23, 2023 am 11:47 AM

In modern web application development, WebSocket is a common technology for instant communication and real-time data transfer. The SpringBoot framework provides support for integrated WebSocket, making it very convenient for developers to implement push and notification functions. This article will introduce how to use WebSocket to implement push and notification functions in SpringBoot, and demonstrate the implementation of a simple real-time online chat room. Create a SpringBoot project First, we need to create a

How to implement integration testing of RESTful API in PHP How to implement integration testing of RESTful API in PHP Sep 06, 2023 pm 03:19 PM

How to implement RESTfulAPI integration testing in PHP With the development of web applications and the popularity of RESTfulAPI, integration testing of APIs has become more and more important. In PHP, we can use some tools and techniques to implement such integration testing. This article will introduce how to implement integration testing of RESTfulAPI in PHP and provide some sample code to help you understand. Integration Testing with PHPUnit PHPUnit is the most popular unit test in PHP

See all articles