# Spring REST API

## 1\. Introduction to Spring REST API

Spring REST API is used to build web services that allow applications to communicate through HTTP requests and responses.

Spring Boot simplifies REST API development using annotations and embedded servers.

## 2\. REST Architecture

**Definition:** REST (Representational State Transfer) is an architectural style used to develop web services.

**Key principles:**

- Client-Server Architecture
- Stateless Communication
- Cacheability
- Uniform Interface
- Layered System

## 3\. REST Controller

**Definition:** `@RestController` creates REST endpoints and returns data directly as JSON or other supported response formats.

**Syntax:**

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

## 4\. Request Mapping

**Definition:** `@RequestMapping` defines the base URL and request mapping for controller methods.

**Example:**

```java
@RequestMapping("/api/users")
public class UserController {
}
```

## 5\. HTTP Methods

**Definition:** HTTP methods define the operations performed on REST resources.

| Method | Purpose | Spring Annotation |
| --- | --- | --- |
| GET | Retrieve data | `@GetMapping` |
| POST | Create data | `@PostMapping` |
| PUT | Replace data | `@PutMapping` |
| PATCH | Partially update data | `@PatchMapping` |
| DELETE | Delete data | `@DeleteMapping` |

## 6\. GET API

**Definition:** Retrieves existing resources from the server.

**Example:**

```java
@GetMapping("/{id}")
public String getUser(@PathVariable Long id) {
    return "User ID: " + id;
}
```

## 7\. POST API

**Definition:** Creates a new resource on the server.

**Example:**

```java
@PostMapping
public String createUser(@RequestBody User user) {
    return "User Created";
}
```

## 8\. PUT API

**Definition:** Replaces an existing resource with updated data.

**Example:**

```java
@PutMapping("/{id}")
public String updateUser(@PathVariable Long id,
                         @RequestBody User user) {
    return "User Updated";
}
```

## 9\. PATCH API

**Definition:** Updates selected fields of an existing resource.

**Example:**

```java
@PatchMapping("/{id}")
public String partialUpdate(@PathVariable Long id) {
    return "User Partially Updated";
}
```

## 10\. DELETE API

**Definition:** Removes an existing resource.

**Example:**

```java
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
    return "User Deleted";
}
```

## 11\. @PathVariable

**Definition:** Extracts values from the URL path.

**Example:**

```java
@GetMapping("/{id}")
public String getUser(@PathVariable Long id) {
    return "ID: " + id;
}
```

**URL:** `/api/users/101`

## 12\. @RequestParam

**Definition:** Extracts query parameters from the request URL.

**Example:**

```java
@GetMapping("/search")
public String searchUser(@RequestParam String name) {
    return "Name: " + name;
}
```

**URL:** `/api/users/search?name=Mani`

## 13\. @RequestBody

**Definition:** Converts incoming JSON request data into a Java object.

**Example:**

```java
@PostMapping
public User createUser(@RequestBody User user) {
    return user;
}
```

## 14\. @ResponseBody

**Definition:** Returns a Java object or value directly in the HTTP response body.

**Example:**

```java
@ResponseBody
@GetMapping("/message")
public String message() {
    return "Welcome";
}
```

## 15\. ResponseEntity

**Definition:** Provides control over the HTTP response body, status code, and headers.

**Example:**

```java
@GetMapping("/{id}")
public ResponseEntity<String> getUser() {
    return ResponseEntity.ok("User Found");
}
```

## 16\. HTTP Status Codes

**Definition:** HTTP status codes indicate the result of an API request.

| Status Code | Meaning |
| --- | --- |
| 200 | OK |
| 201 | Created |
| 204 | No Content |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |

## 17\. DTO (Data Transfer Object)

**Definition:** DTO transfers selected data between application layers without exposing the entity directly.

**Example:**

```java
public class UserDTO {
    private String name;
    private String email;
}
```

## 18\. REST API Validation

**Definition:** Validation checks incoming request data before processing it.

**Example:**

```java
public class UserDTO {

    @NotBlank
    private String name;

    @Email
    private String email;
}
```

Use `@Valid` in the controller:

```java
@PostMapping
public String createUser(@Valid @RequestBody UserDTO user) {
    return "Valid User";
}
```

## 19\. Exception Handling

**Definition:** Handles application errors and returns meaningful error responses.

**Example:**

```java
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return ResponseEntity
                .internalServerError()
                .body(ex.getMessage());
    }
}
```

## 20\. Content Negotiation

**Definition:** Allows REST APIs to support different response formats based on request headers.

**Example:**

```java
@GetMapping(
    value = "/users",
    produces = MediaType.APPLICATION_JSON_VALUE
)
public List<User> getUsers() {
    return userService.getUsers();
}
```

## 21\. REST API Headers

**Definition:** HTTP headers carry additional information about requests and responses.

**Example:**

```java
@GetMapping("/headers")
public String getHeader(
        @RequestHeader("Authorization") String token) {
    return "Token Received";
}
```

## 22\. CORS Configuration

**Definition:** Cross-Origin Resource Sharing controls requests from different origins.

**Example:**

```java
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class UserController {
}
```

## 23\. REST API Pagination and Sorting

**Definition:** Pagination divides large datasets into smaller pages, while sorting arranges records in a particular order.

**Example:**

```java
@GetMapping
public Page<User> getUsers(Pageable pageable) {
    return userRepository.findAll(pageable);
}
```

**URL:**

```text
/api/users?page=0&size=10&sort=name,asc
```

## 24\. REST API Versioning

**Definition:** API versioning maintains different API versions without breaking existing clients.

**Example:**

```java
@GetMapping("/api/v1/users")
public String getUsersV1() {
    return "Version 1";
}
```

```java
@GetMapping("/api/v2/users")
public String getUsersV2() {
    return "Version 2";
}
```

## 25\. REST API Security

**Definition:** Secures REST endpoints through authentication and authorization.

**Common concepts:**

- Spring Security
- JWT Authentication
- OAuth 2.0
- Role-Based Access Control
- Password Encoding

## 26\. REST API Documentation

**Definition:** API documentation describes endpoints, request parameters, response formats, and status codes.

**Common tool:** Springdoc OpenAPI / Swagger UI.

## 27\. REST API Testing

**Definition:** Testing verifies API endpoints, request data, responses, and status codes.

**Common tools:**

- Postman
- JUnit
- Mockito
- MockMvc
- REST Assured

## 28\. REST API Workflow

1. Client sends an HTTP request.
2. Controller receives the request.
3. Service processes business logic.
4. Repository interacts with the database.
5. Database returns the result.
6. Controller sends an HTTP response.

## 29\. Important Spring REST API Annotations

| Annotation | Purpose |
| --- | --- |
| `@RestController` | Creates REST controller |
| `@RequestMapping` | Maps request URLs |
| `@GetMapping` | Handles GET requests |
| `@PostMapping` | Handles POST requests |
| `@PutMapping` | Handles PUT requests |
| `@PatchMapping` | Handles PATCH requests |
| `@DeleteMapping` | Handles DELETE requests |
| `@PathVariable` | Reads URL variables |
| `@RequestParam` | Reads query parameters |
| `@RequestBody` | Reads request body |
| `@ResponseBody` | Returns response body |
| `@Valid` | Enables validation |
| `@RestControllerAdvice` | Global exception handling |

## Conclusion

Spring REST API simplifies communication between frontend and backend applications using HTTP methods, request mappings, response handling, validation, and exception management.

Understanding these concepts helps developers build secure, scalable, and maintainable RESTful web services using Java and Spring Boot.

**Audience Engagement:**

Which Spring REST API concept do you use most in your projects — HTTP methods, ResponseEntity, DTO, validation, or exception handling?

Follow my page at @[Manikandan S](@manikandan4411)

Thanks for Reading
