0% found this document useful (0 votes)
41 views5 pages

Spring Boot REST API Guide for Beginners

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)
41 views5 pages

Spring Boot REST API Guide for Beginners

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

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) {
[Link]([Link], 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: " + [Link]();
}

@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 [Link]([Link]).body("Service is running");
}

5. CRUD Operations

Controller Examples:

@PostMapping("/students")
public Student create(@RequestBody Student s) { return [Link](s); }

@GetMapping("/students/{id}")
public Student read(@PathVariable int id) { return
[Link](id).orElse(null); }

@PutMapping("/students/{id}")
public Student update(@RequestBody Student s, @PathVariable int id) {
[Link](id);
return [Link](s);
}

@DeleteMapping("/students/{id}")
public void delete(@PathVariable int id) { [Link](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 [Link]("Valid student");
}

7. Exception Handling
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler([Link])
public ResponseEntity<String>
handleValidationErrors(MethodArgumentNotValidException ex) {
return [Link]().body("Validation failed");
}
}

8. Logging
@Slf4j
@RestController
public class LoggingExample {
@GetMapping("/log")
public String logTest() {
[Link]("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 [Link] -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:
[Link]
(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.

Common questions

Powered by AI

In a Spring Boot application, input is validated using annotations such as @NotBlank and @Min within the entity classes. Methods can be annotated with @Valid to ensure that the validation process is triggered when handling requests. For example, in a Student class, @NotBlank can be used for a name field, and @Min(5) for an age field .

Testing a REST API endpoint with Postman involves selecting the appropriate HTTP method (GET, POST, etc.), entering the endpoint URL, and setting headers and body if needed. In curl, you specify the method with the -X flag, add headers with -H, and use -d for the request body. For example, to test a POST request, you might use: curl -X POST http://localhost:8080/register -H "Content-Type: application/json" -d '{"name":"Aarav","age":14,"grade":"8th"}' .

In Spring Boot, a global exception handler can manage validation errors by using @ControllerAdvice and @ExceptionHandler annotations. For instance, a method annotated with @ExceptionHandler(MethodArgumentNotValidException.class) can catch validation exceptions and use ResponseEntity to return a bad request status combined with a descriptive error message .

To handle CRUD operations in a Spring Boot application, define a controller with methods mapped to different HTTP verbs: POST for creating (save a student object in the repo), GET for reading (fetch student data by ID or all students), PUT for updating (modify student details), and DELETE for removing (delete by ID). Use repository methods like repo.save() and repo.findById() in these endpoints to interact with the database .

The key HTTP methods used in REST API design include GET, POST, PUT, PATCH, and DELETE. GET is used to retrieve data, POST is to create data, PUT is for updating entire data, PATCH updates partial data, and DELETE removes data .

To set up a basic Spring Boot application for a REST API, use the Spring Initializr to generate a project with the 'spring-boot-starter-web' dependency. Define an application class annotated with @SpringBootApplication, and write the main method to run the application using SpringApplication.run().

ResponseEntity is used in Spring Boot to customize HTTP responses, including status codes, headers, and body. It allows for more control over the response details. For instance, you can use ResponseEntity to send a custom message with a specific status, like 404 Not Found, when an entity is not found in a request. This helps in providing meaningful feedback to the API consumers .

In Spring Boot APIs, logging is implemented using annotations like @Slf4j, which provides methods for different log levels such as info. This is important for tracking application behavior, debugging issues, and maintaining an audit trail of API interactions. For example, an info log can be recorded in a controller method to note significant events like successful data retrieval .

To design an endpoint that returns a custom greeting using a path variable in Spring Boot, create a method annotated with @GetMapping and use the @PathVariable annotation to access the variable from the URL. For example, in the @GetMapping("/greet/{name}") method, use @PathVariable String name to capture the name and return a greeting like "Hello, " + name .

A simple security check in Spring Boot can be implemented by accessing HTTP headers in the controller method. For example, you can use the @RequestHeader annotation to retrieve a token value. The method can then verify this value against a known secret, such as 'abc123', and grant or deny access based on a match .

You might also like