Friday 15 April 2022

Spring: openAPI: Document api responses

Using @ApiResponses annotation, we can document the API responses.

 

Example

@GetMapping("/by-id/{id}")
@Operation(summary = "Get the user by first or lastName", description = "Get the user by first or lastName")
@ApiResponses(value = {
		@ApiResponse(responseCode = "200", description = "Return the user details", content = {
				@Content(mediaType = "application/json", schema = @Schema(implementation = User.class)) }),
		@ApiResponse(responseCode = "404", description = "User not found for the given id", content = @Content) })

public ResponseEntity<User> infoByName(
		@Parameter(name = "id", in = ParameterIn.PATH, required = true) @PathVariable(name = "id", required = true) Integer id) {

	if (!UserRepository.getUSERS_CACHE().containsKey(id)) {
		return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
	}

	return ResponseEntity.ok(UserRepository.getUSERS_CACHE().get(id));
}

 

Above snippet generate document responses like below.

 


Find the below working application.

 

Step 1: Create new maven project ‘openapi-document-api-response’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>openapi-document-api-response</artifactId>
	<version>1</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.4</version>
	</parent>


	<properties>
		<java.version>1.8</java.version>
		<maven.compiler.source>${java.version}</maven.compiler.source>
		<maven.compiler.target>${java.version}</maven.compiler.target>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.report.outputEncoding>UTF-8</project.report.outputEncoding>
	</properties>
	
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>


		<dependency>
			<groupId>org.springdoc</groupId>
			<artifactId>springdoc-openapi-ui</artifactId>
			<version>1.6.6</version>
		</dependency>


	</dependencies>
</project>

 

Step 3: Define User model class.

 

User.java

 

package com.sample.app.model;

public class User {

	private Integer id;
	private String firstName;
	private String lastName;

	public User() {
	}

	public User(Integer id, String firstName, String lastName) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer 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;
	}

}

 

Step 4: Define UserRepository.

 

UserRepository.java

 

package com.sample.app.repository;

import java.util.HashMap;
import java.util.Map;

import com.sample.app.model.User;

public class UserRepository {

	private static Map<Integer, User> USERS_CACHE = new HashMap<>();

	static {
		for (int i = 1; i < 10; i++) {
			User user = new User(i, "firstName" + i, "lastName" + i);
			USERS_CACHE.put(i, user);
		}
	}

	public static Map<Integer, User> getUSERS_CACHE() {
		return USERS_CACHE;
	}

}

 

Step 5: Define UserController class.

 

UserController.java

 

package com.sample.app.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sample.app.model.User;
import com.sample.app.repository.UserRepository;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping(value = "/api/v1/users")
@Tag(name = "user", description = "User REST APIs")
@CrossOrigin("*")
public class UserController {

	@GetMapping("/by-id/{id}")
	@Operation(summary = "Get the user by first or lastName", description = "Get the user by first or lastName")
	@ApiResponses(value = {
			@ApiResponse(responseCode = "200", description = "Return the user details", content = {
					@Content(mediaType = "application/json", schema = @Schema(implementation = User.class)) }),
			@ApiResponse(responseCode = "404", description = "User not found for the given id", content = @Content) })

	public ResponseEntity<User> infoByName(
			@Parameter(name = "id", in = ParameterIn.PATH, required = true) @PathVariable(name = "id", required = true) Integer id) {

		if (!UserRepository.getUSERS_CACHE().containsKey(id)) {
			return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
		}

		return ResponseEntity.ok(UserRepository.getUSERS_CACHE().get(id));
	}

}

 

Step 6: Define main application class.

 

App.java
package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
	public static void main(String[] args) {

		SpringApplication.run(App.class, args);

	}
}

 

Total project structure looks like below.


Run App.java and open the url  ‘http://localhost:8080/swagger-ui/index.html’ to experiment with the swagger ui.

 

You can download the complete working application from this link.


 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment