0% found this document useful (0 votes)
4 views19 pages

Spring Boot Rest API Notes

This document provides comprehensive notes on Spring Boot and REST API, focusing on key concepts, architecture, core annotations, and implementation details. It covers essential terms, principles of REST, HTTP methods, status codes, and best practices for designing REST APIs. Additionally, it includes practical examples of creating a Spring Boot application and REST controllers for CRUD operations.

Uploaded by

azadshukla40
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)
4 views19 pages

Spring Boot Rest API Notes

This document provides comprehensive notes on Spring Boot and REST API, focusing on key concepts, architecture, core annotations, and implementation details. It covers essential terms, principles of REST, HTTP methods, status codes, and best practices for designing REST APIs. Additionally, it includes practical examples of creating a Spring Boot application and REST controllers for CRUD operations.

Uploaded by

azadshukla40
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

Spring Boot and REST API Complete Notes for

Placement Preparation
Table of Contents
1. Spring Boot Complete Notes
2. REST API Complete Notes

Spring Boot Complete Notes

Basic Terminology and Full Forms


Spring Boot
Full Form: Spring Boot (Framework for building Spring-based applications)
Definition: An extension of the Spring Framework that simplifies the setup and development
of new Spring applications with minimal configuration
IOC
Full Form: Inversion of Control
Definition: A design principle where the framework controls object creation and
dependency management
DI
Full Form: Dependency Injection
Definition: A design pattern that implements IoC by injecting dependencies into objects
rather than objects creating their own dependencies
JPA
Full Form: Java Persistence API
Definition: A specification for accessing, persisting, and managing data between Java
objects/classes and relational databases
ORM
Full Form: Object-Relational Mapping
Definition: A programming technique for converting data between incompatible type
systems using object-oriented programming languages
MVC
Full Form: Model-View-Controller
Definition: A software architectural pattern commonly used for developing user interfaces
that divides the related program logic into three interconnected elements
YAML
Full Form: Yet Another Markup Language / YAML Ain't Markup Language
Definition: A human-readable data-serialization standard commonly used for configuration
files

Important Concepts with Working

1. Spring Boot Architecture Layers


1.1 Presentation Layer
Definition: The topmost layer that handles HTTP requests and user interactions
Components: REST Controllers, Request Mappings, Authentication handlers
Working:
Receives HTTP requests from clients
Converts JSON to Java objects and vice versa
Handles authentication and authorization
Forwards processed requests to Business Layer
Annotations: @RestController, @Controller, @RequestMapping, @GetMapping, @PostMapping
1.2 Business Layer (Service Layer)
Definition: Contains all business logic and rules of the application
Components: Service classes, Business validation, Transaction management
Working:
Processes business rules and validation
Manages transactions using @Transactional
Communicates with Persistence Layer for data operations
Applies authorization and business constraints
Annotations: @Service, @Transactional, @Validated
1.3 Persistence Layer (Data Access Layer)
Definition: Manages database operations and data access logic
Components: Repository interfaces, JPA entities, Query methods
Working:
Handles CRUD operations
Translates between Java objects and database rows
Manages database connections and transactions
Provides data abstraction layer
Annotations: @Repository, @Entity, @Query, @Modifying
1.4 Database Layer
Definition: The actual database where application data is stored
Components: Tables, Indexes, Constraints, Stored procedures
Working:
Stores persistent data
Ensures data integrity and consistency
Handles concurrent access
Provides ACID properties

2. Spring Boot Core Annotations


2.1 @SpringBootApplication
Definition: Main annotation that bootstraps a Spring Boot application
Working: Combines three annotations:
@Configuration: Indicates source of bean definitions
@EnableAutoConfiguration: Enables Spring Boot's auto-configuration
@ComponentScan: Enables component scanning
Usage: Applied to main application class
2.2 @RestController
Definition: Combines @Controller and @ResponseBody
Working:
Marks class as web controller
Automatically serializes return objects to JSON/XML
Handles RESTful web service requests
Usage: Applied to controller classes
2.3 @Service
Definition: Indicates that an annotated class is a service component
Working:
Marks class for component scanning
Indicates business logic layer
Enables transaction management
Usage: Applied to service layer classes
2.4 @Repository
Definition: Indicates that an annotated class is a repository
Working:
Marks class for component scanning
Enables exception translation
Indicates data access layer
Usage: Applied to data access classes
2.5 @Autowired
Definition: Enables automatic dependency injection
Working:
Spring container automatically injects required dependencies
Can be used on constructors, fields, or setter methods
Resolves dependencies by type
Usage: Applied to fields, constructors, or methods

3. Dependency Injection (DI)


3.1 Constructor Injection
Definition: Dependencies are provided through class constructor
Working:
@Service
public class UserService {
private final UserRepository userRepository;

@Autowired
public UserService(UserRepository userRepository) {
[Link] = userRepository;
}
}

Advantages: Ensures immutability, required dependencies, easier testing


3.2 Setter Injection
Definition: Dependencies are provided through setter methods
Working:
@Service
public class UserService {
private UserRepository userRepository;

@Autowired
public void setUserRepository(UserRepository userRepository) {
[Link] = userRepository;
}
}

Advantages: Optional dependencies, flexibility


3.3 Field Injection
Definition: Dependencies are directly injected into fields
Working:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}

Disadvantages: Hidden dependencies, harder to test

4. Spring Boot Configuration


4.1 Application Properties vs YAML
Properties Format:
[Link]=8080
[Link]=jdbc:mysql://localhost:3306/mydb
[Link]=root

YAML Format:
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root

4.2 @ConfigurationProperties
Definition: Binds external properties to Java objects
Working:
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int timeout;
// getters and setters
}
Basic Use and Implementation

1. Creating a Spring Boot Application


Step 1: Main Application Class

@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}

Step 2: Controller Layer

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

@Autowired
private UserService userService;

@GetMapping
public List<User> getAllUsers() {
return [Link]();
}

@PostMapping
public User createUser(@RequestBody User user) {
return [Link](user);
}
}

Step 3: Service Layer

@Service
@Transactional
public class UserService {

@Autowired
private UserRepository userRepository;

public List<User> findAllUsers() {


return [Link]();
}

public User saveUser(User user) {


return [Link](user);
}
}
Step 4: Repository Layer

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);

@Query("SELECT u FROM User u WHERE [Link] = ?1")


User findByEmail(String email);
}

Step 5: Entity Layer

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = [Link])
private Long id;

@Column(nullable = false)
private String name;

@Column(unique = true)
private String email;

// constructors, getters, setters


}

2. Configuration Setup
Database Configuration ([Link])

spring:
datasource:
url: jdbc:mysql://localhost:3306/myapp
username: root
password: password
driver-class-name: [Link]

jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
dialect: [Link]
format_sql: true

server:
port: 8080
3. Advanced Features
3.1 Exception Handling

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
ErrorResponse error = new ErrorResponse("USER_NOT_FOUND", [Link]());
return [Link](HttpStatus.NOT_FOUND).body(error);
}
}

3.2 Validation

@Entity
public class User {
@NotBlank(message = "Name is required")
private String name;

@Email(message = "Invalid email format")


@NotBlank(message = "Email is required")
private String email;
}

@RestController
public class UserController {
@PostMapping
public User createUser(@Valid @RequestBody User user) {
return [Link](user);
}
}

3.3 Profiles

# [Link]
spring:
datasource:
url: jdbc:h2:mem:devdb
h2:
console:
enabled: true

# [Link]
spring:
datasource:
url: jdbc:mysql://prod-server:3306/proddb
REST API Complete Notes

Basic Terminology and Full Forms


REST
Full Form: Representational State Transfer
Definition: An architectural style for designing networked applications, particularly web
services
API
Full Form: Application Programming Interface
Definition: A set of protocols, routines, and tools for building software applications
HTTP
Full Form: Hypertext Transfer Protocol
Definition: An application protocol for distributed, collaborative, hypermedia information
systems
URI
Full Form: Uniform Resource Identifier
Definition: A string that unambiguously identifies a particular resource
URL
Full Form: Uniform Resource Locator
Definition: A reference to a web resource that specifies its location on a computer network
JSON
Full Form: JavaScript Object Notation
Definition: A lightweight data-interchange format that is easy for humans to read and write
XML
Full Form: eXtensible Markup Language
Definition: A markup language that defines a set of rules for encoding documents
CRUD
Full Form: Create, Read, Update, Delete
Definition: Four basic operations of persistent storage
Important Concepts with Working

1. REST Principles
1.1 Stateless
Definition: Each request must contain all information needed to process it
Working: Server doesn't store client context between requests
Benefits: Scalability, reliability, simplified server design
1.2 Client-Server Architecture
Definition: Separation of concerns between client and server
Working: Client handles user interface, server handles data storage
Benefits: Portability, scalability, independent evolution
1.3 Uniform Interface
Definition: Standardized way of communicating between components
Working: Uses standard HTTP methods and status codes
Components:
Resource identification through URIs
Resource manipulation through representations
Self-descriptive messages
Hypermedia as the engine of application state (HATEOAS)
1.4 Cacheable
Definition: Responses can be cached to improve performance
Working: HTTP headers control caching behavior
Benefits: Reduced network traffic, improved performance
1.5 Layered System
Definition: Architecture composed of hierarchical layers
Working: Each layer only knows about immediate adjacent layers
Benefits: Encapsulation, load balancing, security
1.6 Code on Demand (Optional)
Definition: Server can extend client functionality by sending executable code
Working: JavaScript sent to browsers is an example
Benefits: Simplified clients, extended functionality
2. HTTP Methods and Their Usage
2.1 GET
Purpose: Retrieve data from server
Characteristics: Safe, idempotent, cacheable
Usage: Read operations
Example: GET /api/users/123

Response Codes: 200 (OK), 404 (Not Found)


2.2 POST
Purpose: Create new resources
Characteristics: Not safe, not idempotent
Usage: Create operations
Example: POST /api/users

Response Codes: 201 (Created), 400 (Bad Request)


2.3 PUT
Purpose: Update/replace entire resource
Characteristics: Not safe, idempotent
Usage: Update operations (complete replacement)
Example: PUT /api/users/123

Response Codes: 200 (OK), 204 (No Content)


2.4 PATCH
Purpose: Partial update of resource
Characteristics: Not safe, not idempotent
Usage: Update operations (partial modification)
Example: PATCH /api/users/123

Response Codes: 200 (OK), 204 (No Content)


2.5 DELETE
Purpose: Remove resources
Characteristics: Not safe, idempotent
Usage: Delete operations
Example: DELETE /api/users/123

Response Codes: 204 (No Content), 404 (Not Found)


3. HTTP Status Codes
3.1 1xx - Informational
100 Continue: Client should continue with request
101 Switching Protocols: Server switching protocols
3.2 2xx - Success
200 OK: Successful request
201 Created: Resource successfully created
202 Accepted: Request accepted for processing
204 No Content: Successful request, no content returned
3.3 3xx - Redirection
301 Moved Permanently: Resource permanently moved
302 Found: Resource temporarily moved
304 Not Modified: Resource not modified since last request
3.4 4xx - Client Errors
400 Bad Request: Invalid request syntax
401 Unauthorized: Authentication required
403 Forbidden: Access forbidden
404 Not Found: Resource not found
405 Method Not Allowed: HTTP method not supported
409 Conflict: Conflict with current state
422 Unprocessable Entity: Request well-formed but unable to process
3.5 5xx - Server Errors
500 Internal Server Error: Generic server error
501 Not Implemented: Functionality not implemented
502 Bad Gateway: Invalid response from upstream server
503 Service Unavailable: Server temporarily unavailable

4. REST API Design Best Practices


4.1 URI Design
Use Nouns: Resources should be nouns, not verbs
Good: /api/users
Bad: /api/getUsers
Hierarchical Structure: Show resource relationships
/api/users/123/orders/456

Consistent Naming: Use consistent conventions


Plural nouns for collections: /api/users
Singular nouns for documents: /api/users/profile
4.2 HTTP Methods Usage
GET: Safe and idempotent
POST: For creation and non-idempotent operations
PUT: For updates (complete replacement)
PATCH: For partial updates
DELETE: For resource deletion
4.3 Status Code Usage
Use Appropriate Codes: Return correct status for each operation
Consistent Mapping: Same operation should return same codes
Meaningful Errors: Provide detailed error information

Basic Use and Implementation

1. REST Controller Implementation


Basic CRUD Controller

@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserController {

@Autowired
private UserService userService;

// GET - Retrieve all users


@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = [Link]();
return [Link](users);
}

// GET - Retrieve user by ID


@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = [Link](id);
if (user != null) {
return [Link](user);
}
return [Link]().build();
}
// POST - Create new user
@PostMapping
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
User savedUser = [Link](user);
URI location = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand([Link]())
.toUri();
return [Link](location).body(savedUser);
}

// PUT - Update user


@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @Valid @RequestBody Use
User existingUser = [Link](id);
if (existingUser == null) {
return [Link]().build();
}
[Link](id);
User updatedUser = [Link](user);
return [Link](updatedUser);
}

// PATCH - Partial update


@PatchMapping("/{id}")
public ResponseEntity<User> partialUpdateUser(@PathVariable Long id, @RequestBody Map
User user = [Link](id, updates);
if (user == null) {
return [Link]().build();
}
return [Link](user);
}

// DELETE - Delete user


@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
if ([Link](id)) {
[Link](id);
return [Link]().build();
}
return [Link]().build();
}
}

2. Request/Response Handling
Request Parameters

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

// Query Parameters
@GetMapping
public ResponseEntity<List<User>> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(required = false) String name) {
// Implementation
}

// Path Variables
@GetMapping("/{userId}/orders/{orderId}")
public ResponseEntity<Order> getUserOrder(
@PathVariable Long userId,
@PathVariable Long orderId) {
// Implementation
}

// Request Headers
@GetMapping
public ResponseEntity<List<User>> getUsers(
@RequestHeader("Accept-Language") String language) {
// Implementation
}
}

Response Handling

@RestController
public class UserController {

// Simple Response
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return [Link](id);
}

// ResponseEntity for more control


@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = [Link](id);
if (user != null) {
return ResponseEntity
.ok()
.header("Custom-Header", "value")
.body(user);
}
return [Link]().build();
}

// Custom Response Structure


@GetMapping
public ResponseEntity<ApiResponse<List<User>>> getUsers() {
List<User> users = [Link]();
ApiResponse<List<User>> response = new ApiResponse<>(
"success",
"Users retrieved successfully",
users
);
return [Link](response);
}
}

3. Error Handling
Global Exception Handler

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException
ErrorResponse error = [Link]()
.status(HttpStatus.NOT_FOUND.value())
.error("RESOURCE_NOT_FOUND")
.message([Link]())
.timestamp([Link]())
.path(getRequestPath())
.build();
return [Link](HttpStatus.NOT_FOUND).body(error);
}

@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleValidation(ValidationException ex) {
ErrorResponse error = [Link]()
.status(HttpStatus.BAD_REQUEST.value())
.error("VALIDATION_ERROR")
.message([Link]())
.timestamp([Link]())
.build();
return [Link]().body(error);
}

@ExceptionHandler([Link])
public ResponseEntity<ValidationErrorResponse> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex) {
ValidationErrorResponse response = new ValidationErrorResponse();
[Link](HttpStatus.BAD_REQUEST.value());
[Link]("VALIDATION_FAILED");
[Link]("Request validation failed");

Map<String, String> fieldErrors = new HashMap<>();


[Link]().getFieldErrors().forEach(error ->
[Link]([Link](), [Link]())
);
[Link](fieldErrors);

return [Link]().body(response);
}

@ExceptionHandler([Link])
public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
ErrorResponse error = [Link]()
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.error("INTERNAL_SERVER_ERROR")
.message("An unexpected error occurred")
.timestamp([Link]())
.build();
return [Link](HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}

4. Advanced REST Features


4.1 Pagination and Sorting

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

@GetMapping
public ResponseEntity<Page<User>> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(defaultValue = "id") String sortBy,
@RequestParam(defaultValue = "asc") String sortDir) {

Sort sort = [Link]("desc")


? [Link](sortBy).descending()
: [Link](sortBy).ascending();

Pageable pageable = [Link](page, size, sort);


Page<User> users = [Link](pageable);

return [Link](users);
}
}

4.2 Filtering and Searching

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

@GetMapping("/search")
public ResponseEntity<List<User>> searchUsers(
@RequestParam(required = false) String name,
@RequestParam(required = false) String email,
@RequestParam(required = false) String city) {

UserSearchCriteria criteria = [Link]()


.name(name)
.email(email)
.city(city)
.build();
List<User> users = [Link](criteria);
return [Link](users);
}
}

4.3 Content Negotiation

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

@GetMapping(value = "/{id}", produces = {


MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE
})
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = [Link](id);
if (user != null) {
return [Link](user);
}
return [Link]().build();
}

@PostMapping(consumes = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE
})
public ResponseEntity<User> createUser(@RequestBody User user) {
User savedUser = [Link](user);
return [Link]([Link]).body(savedUser);
}
}

5. API Documentation and Testing


Swagger/OpenAPI Integration

@RestController
@RequestMapping("/api/users")
@Tag(name = "User Management", description = "APIs for managing users")
public class UserController {

@Operation(summary = "Get user by ID", description = "Retrieves a user by their uniqu


@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "User found"),
@ApiResponse(responseCode = "404", description = "User not found")
})
@GetMapping("/{id}")
public ResponseEntity<User> getUser(
@Parameter(description = "User ID", required = true) @PathVariable Long id) {
// Implementation
}
}

Security Considerations
1. Authentication and Authorization

@RestController
@RequestMapping("/api/secure")
@PreAuthorize("hasRole('ADMIN')")
public class SecureController {

@GetMapping("/users")
@PreAuthorize("hasAuthority('READ_USERS')")
public ResponseEntity<List<User>> getUsers() {
// Implementation
}

@PostMapping("/users")
@PreAuthorize("hasAuthority('CREATE_USERS')")
public ResponseEntity<User> createUser(@RequestBody User user) {
// Implementation
}
}

2. Input Validation

@Entity
public class User {
@NotNull(message = "Name cannot be null")
@Size(min = 2, max = 50, message = "Name must be between 2 and 50 characters")
private String name;

@Email(message = "Email should be valid")


@NotBlank(message = "Email cannot be blank")
private String email;

@Pattern(regexp = "^\\+?[1-9]\\d{1,14}$", message = "Invalid phone number")


private String phone;
}

This comprehensive guide covers all essential aspects of Spring Boot and REST API
development needed for placement preparation. Practice implementing these concepts with
hands-on projects to reinforce your understanding.

You might also like