Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Streamlining API Documentation Using Postman
Next article icon

Spring Boot - REST API Documentation using OpenAPI

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of the API documentation in both JSON/YAML and HTML format. In this article, we'll create a Spring boot application and use springdoc-openapi to document the REST APIs.

Setting up the Project

for this article, we'll be using openAPI 2.0.4 and Spring Boot 3.0.6. To have springdoc-openapi generate API documentation, add the below dependency to your pom.xml.

XML
<dependency>    <groupId>org.springdoc</groupId>    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>    <version>2.0.2</version>  </dependency> 

If you don't have the validation dependency, you may face some errors; therefore, to avoid errors, include the below dependency if you don't have it.

XML
<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-validation</artifactId>  </dependency> 
  • Now, the documentation will be available in JSON format at http://localhost:8080/v3/api-docs
  • The documentation will be available in YAML format at http://localhost:8080/v3/api-docs.yaml
  • The swagger UI will be available at http://localhost:8080/swagger-ui.html

You can also customize the URL of the API documentation. Add the lines below to the application.properties file.

springdoc-swagger-ui.path=/swagger-ui.html  springdoc.api-docs.path=/api-docs

Controller Class

Here we're creating an employee management application, and below are the REST APIs associated with it.

Java
@RestController @RequestMapping("/employee") public class EmployeeController {        @Autowired     private Employee employeeService;      @PostMapping("/addEmployee")     public ResponseEntity<Employee> addEmployee(@RequestBody Employee employee){         return ResponseEntity.ok(employeeService.saveEmployee(employee));     }        @PutMapping("/updateEmployee")     public ResponseEntity<Employee> updateEmployee(@RequestBody Employee employee){         return ResponseEntity.ok(employeeService.updateEmployee(employee));     }        @DeleteMapping("/deleteEmployee/{id}")     public ResponseEntity<Employee> deleteEmployee(@PathVariable int id){         return ResponseEntity.ok(employeeService.deleteEmployee(id));     }        @GetMapping("/getEmployees")     public ResponseEntity<List<Employee>> getEmployees(){         return ResponseEntity.ok(employeeService.getEmployees());     }    } 

After running the application navigate to http://localhost:8080/swagger-ui.html to view the swagger documentation.

Swagger-UI API documentation
Swagger-UI API documentation

You can expand a particular API to look at it in detail. The request and response of the GET API look like

GET API
GET API

Schema Validation Constraints Documentation

There may be several fields in a model class that requires validations. For this, we annotate the corresponding fields with JSR-303 bean validation annotations like @NotEmpty, @NotNull, @Size, @Min, @Max, etc. The springdoc-openapi automatically generates documentation for these validation constraints. Consider the Employee model class.

Java
@Table @Entity public class Employee {        @Id     @Column     @NotNull     private int id;        @Column     @NotEmpty     private String first_name;        @Column     private String last_name;        @Column     @Min(value = 18)     @Max(value = 55)     private int age;        @Column     @NotNull     private double salary;    } 

The automatic generated for this Employee bean looks like

Validation constraints documentation
Validation constraints documentation

Response Codes Documentation

As you can see that there are a few response codes that are by default generated for us. For example, for a GET request, the documentation for response code 200 is already generated. But you can also document other response codes as well. To automatically generate documentation for response codes annotate the global exception handler class with @RestControllerAdvice annotation and annotate each exception handler method with @ResponseStatus annotation.

Java
@RestControllerAdvice public class GlobalExceptionHandler {        @ExceptionHandler(EmployeeNotFoundException.class)     @ResponseStatus(HttpStatus.NOT_FOUND)     public ResponseEntity<String> handleEmployeeNotFoundException(EmployeeNotFoundException employeeNotFoundException){         return new ResponseEntity<>(employeeNotFoundException.getMessage(), HttpStatus.NOT_FOUND);     }        @ExceptionHandler(EmployeeAlreadyExistsException.class)     @ResponseStatus(HttpStatus.CONFLICT)     public ResponseEntity<String> handleEmployeeAlreadyExistsException(EmployeeAlreadyExistsException employeeAlreadyExistsException){         return new ResponseEntity<>(employeeAlreadyExistsException.getMessage(),HttpStatus.CONFLICT);     }    } 

The documentation generated looks like

Response codes documentation
Response codes documentation

Customizing API Documentation using @Operation and @ApiResponses

We can add some descriptions to our API by using @Operation and @ApiResponses annotations. We'll annotate the controller class with these annotations and customize the API description.

Java
@Operation(summary = "Delete an employee by its id") @ApiResponses(value = {         @ApiResponse(responseCode = "200", description = "Deleted an employee", content = {@Content(mediaType = "application/json",schema = @Schema(implementation = Employee.class))}), @ApiResponse(responseCode = "401",description = "Unauthorized user",content = @Content),         @ApiResponse(responseCode = "404",description = "Employee not found",content = @Content),         @ApiResponse(responseCode = "400",description = "Invalid employee id",content = @Content)}) @DeleteMapping("/deleteEmployee/{id}") public ResponseEntity<Employee> deleteEmployee(@PathVariable int id){     return ResponseEntity.ok(employeeService.deleteEmployee(id)); } 

After running the application, the documentation looks like

Customized delete API
Customized delete API

Conclusion

In this article, we have learned how to document the REST APIs using Spring Boot 3 and Springdoc Open API. At the start, we learned how to set up a project for a particular use case. Then we saw how we could customize the documentation URL. Then we saw how documentation for schema validation constraints is generated for us. Then, we saw how we can document response codes. In the end, we saw how to use @Operation and @ApiResponses annotations to add descriptions to the APIs.


Next Article
Streamlining API Documentation Using Postman

H

himanshusharma11199
Improve
Article Tags :
  • Java
  • Java-Spring-Boot
Practice Tags :
  • Java

Similar Reads

  • Easiest Way to Create REST API using Spring Boot
    Spring Boot is a powerful framework that makes it easy to create RESTful APIs. Creating a REST API using Spring Boot is one of the fastest and simplest ways to develop scalable and production-ready web services. Spring Boot simplifies REST API development by providing built-in features such as autom
    11 min read
  • How to Create a REST API using Java Spring Boot?
    Representational State Transfer (REST) is a software architectural style that defines a set of constraints for creating web services. RESTful web services allow systems to access and manipulate web resources through a uniform and predefined set of stateless operations. Unlike SOAP, which exposes its
    4 min read
  • Streamlining API Documentation Using Postman
    APIs (Application Programming Interfaces) are the backbone of interconnected software, enabling different applications to work together. As developers build more APIs, the need for clear and accessible documentation becomes more important. Good documentation ensures that others can easily understand
    5 min read
  • JSON using Jackson in REST API Implementation with Spring Boot
    When we build REST APIs with Spring Boot, we need to exclude NULL values from the JSON responses. This is useful when we want to optimize the data being transferred, making the response more compact and easier to process for the client. In this article, we are going to learn the approach that is use
    4 min read
  • Spring Boot API Call using OkHttp
    OkHttp is pretty smart when it comes to dealing with tricky network situations. It quietly bounces back from common connection hiccups and even tries different addresses if the first attempt doesn't work. This becomes crucial when you're dealing with situations that use both IPv4 and IPv6 or when yo
    5 min read
  • Spring Boot - CRUD Operations Using Redis Database
    Redis is an in-memory data structure that is used for faster access to data. It is used to store data that needs to be accessed frequently and fast. It is not used for storing large amounts of data. If you want to store and retrieve large amounts of data you need to use a traditional database such a
    8 min read
  • How to generate API documentation using Postman?
    Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge between two software applications which enables them to communicate and share data. In this article, you will learn how to generate API
    2 min read
  • Spring MVC - Getting Cryptocurrency Details using REST API
    Cryptocurrencies are a hot topic throughout the world. Trading with cryptocurrency got both pros and cons. Nowadays REST APIs are very useful to get much information including cryptocurrencies. In this article, we are going to see about one such REST API call to get cryptocurrency detail. We are goi
    5 min read
  • Spring Boot – Building REST APIs with HATEOAS
    In this article, we will explore how to build RESTful APIs using the Spring Boot with HATEOAS (Hypermedia as the Engine of Application State). HATEOAS is the key component of the REST application architecture, where each resource not only provides the data but also includes links to other actions th
    5 min read
  • Implementing Secure API Communication in Spring Boot
    In modern web applications, securing API communication is important to protect sensitive data and ensuring the integrity of interactions between clients and servers. In this article, we will learn how to implement secure API communication in a Spring Boot application. Securing API communication is c
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences