0% found this document useful (0 votes)
2 views

REST API with Spring Boot

This document provides beginner notes and sample code for creating a REST API using Spring Boot. It covers key concepts such as HTTP methods, setting up Spring Boot, handling requests and responses, CRUD operations, input validation, exception handling, logging, and simple security. Additionally, it includes practical examples and testing instructions with Postman and curl.

Uploaded by

Lokesh Loki
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)
2 views

REST API with Spring Boot

This document provides beginner notes and sample code for creating a REST API using Spring Boot. It covers key concepts such as HTTP methods, setting up Spring Boot, handling requests and responses, CRUD operations, input validation, exception handling, logging, and simple security. Additionally, it includes practical examples and testing instructions with Postman and curl.

Uploaded by

Lokesh Loki
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
You are on page 1/ 5

REST API with Spring Boot - Beginner Student Notes and

Sample Code

1. Introduction to REST API

What is an API? An API (Application Programming Interface) allows different software


systems to communicate.

What is REST? REST (Representational State Transfer) is an architectural style for


designing networked applications.

Key HTTP Methods:

 GET: Retrieve data


 POST: Create data
 PUT: Update entire data
 PATCH: Update partial data
 DELETE: Remove data

2. Setting Up Spring Boot

Steps:

 Use Spring Initializr


 Select: spring-boot-starter-web

Sample Code:

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

3. Handling Request Input

@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:

public class Student {


@NotBlank
private String name;
@Min(5)
private int age;
}
@PostMapping("/validate")
public ResponseEntity<String> validateStudent(@Valid @RequestBody Student
student) {
return ResponseEntity.ok("Valid student");
}

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!";
}
}

9. Simple Security (Header Token)


@GetMapping("/secure")
public String secure(@RequestHeader("token") String token) {
if ("abc123".equals(token)) return "Access granted";
return "Access denied";
}

10. Testing with Postman / curl


Postman:

 Choose method (GET, POST, etc.)


 Add URL and headers
 Use raw body for JSON

Curl:

curl -X POST http://localhost:8080/register -H "Content-Type:


application/json" -d '{"name":"Aarav","age":14,"grade":"8th"}'

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.

13. Get Student by ID (GET)

 Create a GET endpoint /students/{id} that fetches a student by ID.

14. Update Student (PUT)

 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.

16. ✅ Error Handling

 Modify your code to return a 404 Not Found if the student ID doesn't exist while
fetching or deleting.

You might also like