0% found this document useful (0 votes)
7 views2 pages

Spring Boot ApiResponse for Users

The document outlines a reusable ApiResponse class for handling success and error responses in a Spring Boot application. It includes a UserController example demonstrating how to create an admin user and retrieve a user by ID, with appropriate success and error response structures. The document emphasizes consistency in response format and provides example JSON responses for various scenarios.

Uploaded by

Pratik Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Spring Boot ApiResponse for Users

The document outlines a reusable ApiResponse class for handling success and error responses in a Spring Boot application. It includes a UserController example demonstrating how to create an admin user and retrieve a user by ID, with appropriate success and error response structures. The document emphasizes consistency in response format and provides example JSON responses for various scenarios.

Uploaded by

Pratik Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Title:

Reusable ApiResponse for Success & Error in Spring Boot

Step 1: Common Response Wrapper

package [Link];

public class ApiResponse<T> {


private String status;
private String message;
private T data;

public ApiResponse(String status, String message, T data) {


[Link] = status;
[Link] = message;
[Link] = data;
}

// Getters & Setters


}

Step 2: Controller Example With Success & Error

@RestController
@RequestMapping("/api/users")
public class UserController {

@Autowired
private UserService userService;

// Create Admin User


@PostMapping("/admin")
public ResponseEntity<ApiResponse<User>> createAdmin(@RequestBody User
user) {
try {
User savedUser = [Link](user);

ApiResponse<User> response = new ApiResponse<>(


"success",
" Admin " + [Link]() + " has been
created successfully!",
savedUser
);

return
[Link]([Link]).body(response);
} catch (Exception e) {
ApiResponse<User> errorResponse = new ApiResponse<>(
"error",
" Failed to create admin: " + [Link](),
null
);
return
[Link](HttpStatus.BAD_REQUEST).body(errorResponse);
}
}

// Get User by Id
@GetMapping("/{id}")
public ResponseEntity<ApiResponse<User>> getUser(@PathVariable String
id) {
return [Link](id)
.map(user -> [Link](new ApiResponse<>(
"success",
"User found",
user
)))
.orElse([Link](HttpStatus.NOT_FOUND)
.body(new ApiResponse<>(
"error",
" User with id " + id + " not found",
null
)));
}
}

Step 3: Example JSON Responses in Postman

Success (Admin Created)


Status: 201 Created
{
"status": "success",
"message": " Admin pratik has been created successfully!",
"data": {
"id": "66f3b0...",
"username": "pratik",
"roles": ["User", "Admin"]
}
}

Error (User Not Found)


Status: 404 Not Found
{
"status": "error",
"message": " User with id 123 not found",
"data": null
}

Error (Bad Request)


Status: 400 Bad Request
{
"status": "error",
"message": " Failed to create admin: password cannot be null",
"data": null
}

Notes to Remember:

• Always return ApiResponse<T> for consistency.


• Success responses include the created/fetched object.
• Error responses return null data but meaningful messages.
• Clients (Postman, Angular, React) can easily parse status, message, and data.

You might also like