0
0
Spring Bootframework~30 mins

Returning different status codes in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Returning different status codes in Spring Boot
📖 Scenario: You are building a simple web service that responds to client requests with different HTTP status codes depending on the input.This is common in real-world APIs to indicate success, errors, or other conditions.
🎯 Goal: Create a Spring Boot controller that returns different HTTP status codes based on the request parameter.You will learn how to send 200 OK, 400 Bad Request, and 404 Not Found responses.
📋 What You'll Learn
Create a Spring Boot controller class named StatusController
Add a GET endpoint at /check that accepts a query parameter code
Return 200 OK with body "Success" if code is 200
Return 400 Bad Request with body "Bad Request" if code is 400
Return 404 Not Found with body "Not Found" if code is 404
💡 Why This Matters
🌍 Real World
APIs often need to respond with different HTTP status codes to indicate success or errors clearly to clients.
💼 Career
Understanding how to return proper HTTP status codes is essential for backend developers working with RESTful services.
Progress0 / 4 steps
1
Create the controller class and method
Create a Spring Boot controller class named StatusController with a method checkStatus mapped to GET /check that accepts a query parameter code of type int.
Spring Boot
Need a hint?

Use @RestController on the class and @GetMapping("/check") on the method.

Use @RequestParam int code to get the query parameter.

2
Add variables for response messages
Inside the checkStatus method, create three String variables named successMessage, badRequestMessage, and notFoundMessage with values "Success", "Bad Request", and "Not Found" respectively.
Spring Boot
Need a hint?

Declare three String variables with the exact names and values given.

3
Add logic to return different status codes
Inside the checkStatus method, add an if-else block that returns ResponseEntity with 200 OK and successMessage if code == 200, 400 Bad Request and badRequestMessage if code == 400, and 404 Not Found and notFoundMessage if code == 404.
Spring Boot
Need a hint?

Use ResponseEntity.ok() for 200 OK.

Use ResponseEntity.status(HttpStatus.BAD_REQUEST).body() for 400.

Use ResponseEntity.status(HttpStatus.NOT_FOUND).body() for 404.

4
Add import statements for annotations and classes
Add the necessary import statements for @RestController, @GetMapping, @RequestParam, ResponseEntity, and HttpStatus at the top of the file.
Spring Boot
Need a hint?

Import all required Spring annotations and classes from org.springframework.web.bind.annotation and org.springframework.http.