REST API with Spring Boot
REST API with Spring Boot
Sample Code
Steps:
Sample Code:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
@RequestParam Example:
@GetMapping("/greet")
public String greet(@RequestParam String name) {
return "Hello, " + name;
}
@PathVariable Example:
@GetMapping("/student/{id}")
public String getStudent(@PathVariable int id) {
return "Student ID: " + id;
}
@RequestBody Example:
@PostMapping("/register")
public String register(@RequestBody Student student) {
return "Registered: " + student.getName();
}
@RequestHeader Example:
@GetMapping("/welcome")
public String welcome(@RequestHeader("X-User-Name") String username) {
return "Welcome, " + username;
}
4. Sending Responses
Return JSON:
@GetMapping("/student")
public Student getStudent() {
return new Student("Aarav", 14, "8th");
}
Using ResponseEntity:
@GetMapping("/status")
public ResponseEntity<String> getStatus() {
return ResponseEntity.status(HttpStatus.OK).body("Service is running");
}
5. CRUD Operations
Controller Examples:
@PostMapping("/students")
public Student create(@RequestBody Student s) { return repo.save(s); }
@GetMapping("/students/{id}")
public Student read(@PathVariable int id) { return
repo.findById(id).orElse(null); }
@PutMapping("/students/{id}")
public Student update(@RequestBody Student s, @PathVariable int id) {
s.setId(id);
return repo.save(s);
}
@DeleteMapping("/students/{id}")
public void delete(@PathVariable int id) { repo.deleteById(id); }
6. Input Validation
With @Valid:
7. Exception Handling
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String>
handleValidationErrors(MethodArgumentNotValidException ex) {
return ResponseEntity.badRequest().body("Validation failed");
}
}
8. Logging
@Slf4j
@RestController
public class LoggingExample {
@GetMapping("/log")
public String logTest() {
log.info("Info log example");
return "Logged!";
}
}
Curl:
1. Write a Spring Boot controller method to greet a user by their name using
@PathVariable.
2. Create an endpoint /sum which accepts two numbers as query parameters and returns
their sum.
3. Define a class Student with fields name and age. Then write a POST method to
accept a student object as JSON and return a success message.
4. Write a method to return the list of all students as JSON. Use a List<Student> as a
return type.
5. Create a REST API that returns "Welcome, Admin" only when the request header
role has the value admin.
6. Write a DELETE method to delete a student from the list using an index value as
@PathVariable.
7. Use ResponseEntity to return a custom message and HTTP status 404 if a student is
not found by index.
8. What will be the output of this URL call:
http://localhost:8080/greet/Ravi
(Assume your method is public String greet(@PathVariable String name))
9. Create a simple REST endpoint that returns current date and time in JSON.
10. Create a controller with the base path /api and two endpoints:
o GET /api/health – returns "UP"
o POST /api/echo – returns whatever string is sent in the request body.
11. Create a REST API to insert a student into the database using SQL INSERT.
12. Get All Students (GET)
Create an endpoint to retrieve all student records using SQL SELECT * FROM
students.
Write a PUT endpoint that updates student details using SQL UPDATE.
15. Delete Student (DELETE)
Write a DELETE endpoint to remove a student from the database using their ID.
Modify your code to return a 404 Not Found if the student ID doesn't exist while
fetching or deleting.