search
HomeJavajavaTutorialUse 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 bootswaggerrestful 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>

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

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

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

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
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor