DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Spring Microservices RESTFul API Documentation With Swagger Part 1
  • Micronaut vs Spring Boot: A Detailed Comparison
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Spring Boot 3.2: Replace Your RestTemplate With RestClient

Trending

  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Documenting a Spring REST API Using Smart-doc

Documenting a Spring REST API Using Smart-doc

Documentation is essential. In this article, we will explore how to use Smart-doc to generate documentation for a Spring Boot REST API.

By 
sun yu user avatar
sun yu
·
Jun. 26, 24 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
12.0K Views

Join the DZone community and get the full member experience.

Join For Free

If you are developing a RESTful API with Spring Boot, you want to make it as easy as possible for other developers to understand and use your API. Documentation is essential because it provides a reference for future updates and helps other developers integrate with your API. For a long time, the way to document REST APIs was to use Swagger, an open-source software framework that enables developers to design, build, document, and consume RESTful Web services. In 2018, to address the issues of code invasiveness and dependency associated with traditional API documentation tools like Swagger, we developed smart-doc and open-sourced it to the community.

In this article, we will explore how to use Smart-doc to generate documentation for a Spring Boot REST API.

What Is Smart-doc?

Smart-doc is an interface documentation generation tool for Java projects. It primarily analyzes and extracts comments from Java source code to produce API documentation. Smart-doc scans standard Java comments in the code, eliminating the need for specialized annotations like those used in Swagger, thus maintaining the simplicity and non-invasiveness of the code. It supports multiple formats for document output, including Markdown, HTML5, Postman Collection, OpenAPI 3.0, etc. This flexibility allows developers to choose the appropriate documentation format based on their needs. Additionally, Smart-doc can scan code to generate JMeter performance testing scripts.

For more features, please refer to the official documentation.

Steps To Use Smart-doc for Documenting APIs

Step 1: Maven Project

  • Create a Maven project with the latest version of Spring Boot
  • Add the Web dependencies to the project

Maven Project

Step 2: Add Smart-doc Into the Project

  • Add smart-doc-maven-plugin to the project's pom.xml
XML
 
<plugin>
     <groupId>com.ly.smart-doc</groupId>
     <artifactId>smart-doc-maven-plugin</artifactId>
     <version>[latest version]</version>
     <configuration>
         <configFile>./src/main/resources/smart-doc.json</configFile>
         <projectName>${project.description}</projectName>
     </configuration>
</plugin>


  • Create the smart-doc.json file in the resources directory of the module where the project startup class is located.
JSON
 
{
     "outPath": "/path/to/userdir"
}


Step 3: Create a Rest Controller

Now let's create a controller class that will handle HTTP requests and return responses.

  • Create a controller class that will be sent as a JSON response.
Java
 
public class User {

    /**
     * user id
     * 
     */
    private long id;

    /**
     * first name
     */
    private String firstName;

    /**
     * last name
     */
    private String lastName;

    /**
     * email address
     */
    private String email;


    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


  • Now create a service class
Java
 
@Repository
public class UserRepository {

    private static final Map<Long, User> users = new ConcurrentHashMap<>();

    static {
        User user = new User();
        user.setId(1);
        user.setEmail("123@gmail.com");
        user.setFirstName("Tom");
        user.setLastName("King");
        users.put(1L,user);
    }

    public Optional<User> findById(long id) {
        return Optional.ofNullable(users.get(id));
    }

    public void add(User book) {
        users.put(book.getId(), book);
    }

    public List<User> getUsers() {
        return users.values().stream().collect(Collectors.toList());
    }

    public boolean delete(User user) {
        return users.remove(user.getId(),user);
    }
}


  • Create the RestController Class.
Java
 
/**
 * The type User controller.
 *
 * @author yu 2020/12/27.
 */
@RestController
@RequestMapping("/api/v1")
public class UserController {

    @Resource
    private UserRepository userRepository;

    /**
     * Create user.
     *
     * @param user the user
     * @return the user
     */
    @PostMapping("/users")
    public ResponseResult<User> createUser(@Valid @RequestBody User user) {
        userRepository.add(user);
        return ResponseResult.ok(user);
    }

    /**
     * Get all users list.
     *
     * @return the list
     */
    @GetMapping("/users")
    public ResponseResult<List<User>> getAllUsers() {
        return ResponseResult.ok().setResultData(userRepository.getUsers());
    }

    /**
     * Gets users by id.
     *
     * @param userId the user id|1
     * @return the users by id
     */
    @GetMapping("/users/{id}")
    public ResponseResult<User> getUsersById(@PathVariable(value = "id") Long userId) {
        User user = userRepository.findById(userId).
                orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId));
        return ResponseResult.ok().setResultData(user);
    }


    /**
     * Update user response entity.
     *
     * @param userId      the user id|1
     * @param userDetails the user details
     * @return the response entity
     */
    @PutMapping("/users/{id}")
    public ResponseResult<User> updateUser(@PathVariable(value = "id") Long userId, @Valid @RequestBody User userDetails) {
        User user = userRepository.findById(userId).
                orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId));
        user.setEmail(userDetails.getEmail());
        user.setLastName(userDetails.getLastName());
        user.setFirstName(userDetails.getFirstName());
        userRepository.add(user);
        return ResponseResult.ok().setResultData(user);
    }

    /**
     * Delete user.
     *
     * @param userId the user id|1
     * @return the map
     */
    @DeleteMapping("/user/{id}")
    public ResponseResult<Boolean> deleteUser(@PathVariable(value = "id") Long userId) {
        User user = userRepository.findById(userId).
                orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + userId));
        return ResponseResult.ok().setResultData(userRepository.delete(user));
    }
}


Step 4: Generate a Document

You can use the Smart-doc plugin in IntelliJ IDEA to generate the desired documentation, such as OpenAPI, Markdown, etc.

Generate a Document

Of course, you can also use the Maven command to generate:

Shell
 
mvn smart-doc:html
//  Generate document output to Markdown
mvn smart-doc:markdown
// Generate document output to Adoc
mvn smart-doc:adoc
// Generate Postman.
mvn smart-doc:postman
// Generate OpenAPI 3.0+
mvn smart-doc:openapi


Step 4: Import to Postman

Here we use Smart-doc to generate a Postman.json, then import it into Postman to see the effect.

Import to Postman

Since smart-doc supports generating documentation in multiple formats, you can choose to generate OpenAPI and then display it using Swagger UI or import it into some professional API documentation systems.

Conclusion

From the previous examples, it can be seen that Smart-doc generates documentation by scanning standard Java comments in the code, without the need for specialized annotations like Swagger, thus maintaining the simplicity and non-invasiveness of the code, and also not affecting the size of the service Jar package. It supports multiple formats for document output, including Markdown, HTML5, Postman Collection,OpenAPI 3.0, etc. This flexibility allows developers to choose the appropriate document format for output based on their needs. The Maven or Gradle plugins provided by smart-doc also facilitate users in integrating document generation in Devops pipelines.

Currently, Swagger also has its advantages, such as more powerful UI features, and better support for Springboot Webflux.

API Documentation REST Spring Boot

Published at DZone with permission of sun yu. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Microservices RESTFul API Documentation With Swagger Part 1
  • Micronaut vs Spring Boot: A Detailed Comparison
  • High-Performance Reactive REST API and Reactive DB Connection Using Java Spring Boot WebFlux R2DBC Example
  • Spring Boot 3.2: Replace Your RestTemplate With RestClient

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!