I'm always excited to take on new projects and collaborate with innovative minds.

Email

contact@niteshsynergy.com

Website

https://www.niteshsynergy.com/

Web Services & RestFull & Rest API Concepts

Web services enable seamless communication between applications over the internet using protocols like HTTP, SOAP, or REST. RESTful services, adhering to REST principles, offer lightweight, stateless interactions for resource management. REST APIs expose resources through structured endpoints using HTTP methods like GET, POST, PUT, and DELETE for integration.

Web Services Concepts

A web service is a standardized way of enabling communication between different applications over the internet. These are platform-independent and language-neutral interfaces that allow systems to interact.
Key features of web services include:

  • Interoperability: Systems can communicate irrespective of the programming languages used.
  • Reusability: Services are reusable across different applications.
  • Protocol-Driven: Most web services rely on protocols like HTTP, SOAP, or REST.

Types of web services:

  1. SOAP Web Services (Simple Object Access Protocol): Uses XML for communication and is highly secure with strict standards.
  2. RESTful Web Services (Representational State Transfer): Lightweight, uses HTTP methods, and supports multiple formats (JSON, XML, etc.).

Lifecycle of a Web Service

  1. Design: Identify the service's purpose, resources, and endpoints.
  2. Development: Implement the service using frameworks like Spring Boot, Django, etc.
  3. Testing: Validate APIs using tools like Postman or Burp Suite.
  4. Deployment: Host the service on a server (cloud or on-premises).
  5. Monitoring: Continuously monitor performance and errors.
  6. Maintenance: Update and patch the service as needed.

RESTful Websites vs Web Services vs REST API

  1. RESTful Website: A web application that uses REST principles, serving pages or content via URLs (e.g., blogs).
  2. Web Service: Any service provided over the web that allows machine-to-machine communication (SOAP or REST-based).
  3. REST API: A specific type of web service that uses REST principles to expose endpoints for client-server interaction.

 

SOAP Principles in Detail

Concepts

SOAP (Simple Object Access Protocol) is a protocol for exchanging structured XML messages between systems. It is protocol-dependent, highly standardized, and designed for complex enterprise scenarios.

Principles and Use Cases

  1. Protocol-Based
    • Concept: SOAP relies on XML for message formatting and operates over multiple transport protocols like HTTP, SMTP, or TCP.
    • Use Case:
      • Banking systems: Reliable and secure communication using HTTP or TCP.
      • Email services: SMTP-based SOAP for sending messages.
  2. Strict Standards
    • Concept: SOAP mandates a specific message structure: envelope, header, and body.
    • Use Case:
      • Financial systems requiring precise and unambiguous messaging standards.
  3. Stateful/Stateless
    • Concept: SOAP supports both stateful (sessions maintained by the server) and stateless operations.
    • Use Case:
      • Stateful: Workflow-based systems, such as order processing with multiple steps.
      • Stateless: Single, independent data retrieval requests.
  4. Security
    • Concept: SOAP has built-in security via WS-Security, supporting encryption and authentication.
    • Use Case:
      • Healthcare: Ensuring HIPAA-compliant secure data transmission.
      • Government services: Secure identity verification and transaction logging.
  5. Extensibility
    • Concept: Supports custom headers and extensions without breaking the service.
    • Use Case:
      • Custom logging and audit tracking using extended headers in SOAP messages.
  6. Service Description
    • Concept: WSDL (Web Services Description Language) describes the service, its operations, and message formats.
    • Use Case:
      • Enterprise integration: Automatically generating client stubs and contracts using WSDL files.

 

REST Principles in Detail (Including PATCH)

1. Statelessness

  • Concept: Every request from the client to the server must contain all the information the server needs to fulfill the request. The server does not store any state between requests, ensuring each request is independent.
  • Use Case:
    • Example: Each API request to update a user's profile (e.g., POST /users/123) includes all the necessary data for the operation. The server doesn't retain any knowledge of previous requests, ensuring scalability.
    • PATCH Example: When sending a partial update request (e.g., PATCH /users/123), the request includes only the fields that need updating, and the server doesn't need to remember past interactions.

2. Client-Server Architecture

  • Concept: RESTful systems are divided into clients (which consume the API) and servers (which provide the resources). The client and server are independent and communicate through stateless interactions.
  • Use Case:
    • Example: A mobile app (client) can communicate with a backend service (server) to retrieve user data or submit forms. The backend doesn't need to worry about how the data is displayed on the client.
    • PATCH Example: The client sends a partial update to a user profile, while the server processes the update and returns a response.

3. Uniform Interface

  • Concept: This principle enforces a consistent, standardized way of interacting with resources, using HTTP methods (GET, POST, PUT, DELETE, PATCH) and URIs. It simplifies the system by adhering to conventions, making the interface easy to use and understand.
  • Use Case:
    • Example: The REST API defines common operations:
      • GET /users retrieves all users,
      • POST /users creates a new user,
      • PUT /users/123 updates the entire user resource,
      • PATCH /users/123 updates specific fields of the user resource (partial update),
      • DELETE /users/123 deletes the user.
    • PATCH Example: The PATCH /users/123 endpoint allows the client to send only the data that needs to be updated, ensuring flexibility in the API design.

4. Cacheability

  • Concept: Responses from the server must explicitly specify whether they can be cached. This helps reduce the load on the server and improves performance by avoiding redundant requests.
  • Use Case:
    • Example: In an e-commerce site, product listing pages might be cacheable to prevent re-fetching the same data for every request.
    • PATCH Example: A partial update, such as changing a user's email, would typically not be cached, as updates should reflect the latest state of the data. However, some responses may indicate cacheability if applicable.

5. Layered System

  • Concept: The architecture can be composed of multiple layers, where each layer has a specific role. The client does not need to know whether it is interacting with an actual server or an intermediary (like a load balancer or gateway).
  • Use Case:
    • Example: A request to the API might go through multiple layers, such as an API gateway for routing, security layers for authentication, and a database layer for data access.
    • PATCH Example: When a PATCH /users/123 request is sent, it could pass through multiple layers like security for authentication, logging, and caching before reaching the backend service that applies the partial update.

6. Code on Demand (Optional)

  • Concept: Servers can send executable code to clients to extend functionality. This is an optional principle and not commonly used in every RESTful service.
  • Use Case:
    • Example: JavaScript sent by the server to the client to enhance the user interface (e.g., for client-side validation or dynamic content loading).
    • PATCH Example: This principle wouldn't typically apply directly to PATCH operations, but it could be used in scenarios where dynamic updates are sent to the client, changing how it interacts with the API.

Statelessness vs. Stateful in Web Services

Statelessness

  • Concept: In a stateless system, each request from the client to the server is independent and contains all the information necessary to understand and process the request. The server does not retain any memory or state between requests, meaning each request is treated as a new and separate interaction.

    Key Characteristics:

    • No session state: The server does not store any information about past requests.
    • Self-contained requests: Each request carries all the necessary data for processing, such as authentication or previous context.
    • Scalability: Stateless services can scale more easily, as each request is isolated and does not require server resources to store state.

    Use Cases:

    • RESTful APIs: Most RESTful APIs are designed to be stateless, where each HTTP request is independent.
    • Microservices: Stateless microservices are highly scalable because they don't rely on session storage.
    • Sessionless authentication: For example, in JWT (JSON Web Token) authentication, the token carries all necessary information for authentication, so the server doesn't need to keep track of user sessions.

    Example:

    • A REST API request to update a user profile (POST /users/123) would include all necessary data (like the user's name, email, etc.) for that update. The server doesn't need to remember the previous state of the user profile from the last request.

Stateful

  • Concept: In a stateful system, the server retains information about each client or session between requests. This means the server remembers the state of interactions, making it possible to maintain context across multiple requests from the same client.

    Key Characteristics:

    • Session state: The server stores state information (such as user data or session context) between requests.
    • Context persistence: The server can remember past interactions and tailor responses accordingly.
    • Resource-heavy: Maintaining state requires more resources on the server side, as it must store data for each user or session.

    Use Cases:

    • Web applications with user sessions: When a user logs in, their session state is stored by the server, and the server "remembers" the user’s state (like logged-in status) across different requests.
    • Database-driven systems: Stateful systems can be used when it’s essential to track ongoing operations or transactions, such as e-commerce checkouts or multi-step forms.
    • SOAP services: SOAP web services can be stateful, where each operation may rely on the previous interactions for consistency (e.g., banking transactions, order workflows).

    Example:

    • In an e-commerce system, once a user logs in, the server maintains the session, so the user’s cart and preferences are remembered across multiple requests.

Key Differences:

AspectStatelessStateful
Session ManagementNo session or memory of past interactions; each request is independent.Session state is maintained between requests; previous interactions are remembered.
ScalabilityMore scalable as each request is independent and doesn't require server memory for session data.Less scalable, as server needs to store session information, which can consume more resources.
ComplexityEasier to manage and simpler to implement; no need to store or track user data.More complex, as the server must manage session state and ensure it is consistent.
PerformanceGenerally better for large, distributed systems due to reduced server load.Can introduce overhead due to session tracking and memory usage.
Use CasesRESTful APIs, Microservices, Stateless authentication (e.g., JWT).Web applications with user sessions, transaction-based services, SOAP web services.

When to Use Stateless vs. Stateful

  • Stateless is ideal for:
    • Scalable web services: APIs where each request is independent.
    • Microservices: Where you want loosely coupled services that do not depend on shared state.
    • Simple operations: Systems that don’t require complex session management, such as public APIs.
  • Stateful is ideal for:
    • Applications requiring user sessions: Such as login systems, e-commerce checkout processes, or multi-step workflows.
    • Complex business processes: Like transactional systems where the state of the transaction needs to be preserved between requests.
    • Legacy systems or SOAP services: Where maintaining state is essential to the operation.

In general, stateless systems are preferred for scalability, performance, and simplicity, while stateful systems are used in scenarios that require maintaining context between requests.

 

 

Idempotent vs Non-Idempotent

Idempotent

  • Definition: An operation is considered idempotent if performing it multiple times produces the same result as performing it once. In other words, making the same request multiple times should have the same effect and produce the same outcome, without causing additional side effects.
  • Key Characteristics:
    • Same Result on Multiple Requests: Whether the operation is performed once or multiple times, the outcome remains unchanged.
    • No Additional Side Effects: Repeating the operation doesn't create unwanted effects (like creating multiple entries or modifying the resource more than necessary).
  • Use Cases:
    • GET: Retrieving data (e.g., GET /users/123), which doesn't alter the resource.
    • PUT: Replacing a resource (e.g., PUT /users/123 with new data). If the same data is sent multiple times, the result (the state of the resource) is the same.
    • DELETE: Removing a resource (e.g., DELETE /users/123). If the resource is already deleted, calling the same DELETE operation again has no further effect.
  • Example:
    • GET /users/123: Fetching the same user data will always return the same result.
    • PUT /users/123 with the same data: Repeating this request with the same user data will not cause any changes after the first request.
  • Why It’s Important: Idempotent operations are crucial in distributed systems and APIs because they can be safely retried without fear of unintended side effects, such as creating duplicate records or performing the same operation multiple times.

Non-Idempotent

  • Definition: A non-idempotent operation is one where repeated execution produces different results or effects. Performing the same request multiple times can lead to changes or side effects beyond the initial request.
  • Key Characteristics:
    • Different Result on Multiple Requests: Performing the operation multiple times may yield different outcomes, like creating new records or modifying a resource.
    • Side Effects: Repeating a non-idempotent operation could have cumulative effects, such as adding multiple items to an order or incrementing a counter.
  • Use Cases:
    • POST: Typically used for creating resources (e.g., POST /users). Repeating the request creates new resources, leading to different outcomes each time.
    • PATCH: While partial updates can be idempotent if the same changes are applied each time, a non-idempotent patch may modify the resource differently with each request (e.g., incrementing a field).
  • Example:
    • POST /users: Every time you make a POST request to create a new user, a new user will be created, resulting in different outcomes each time.
    • PATCH /counter/increment: Each request to increment a counter adds 1, so calling it multiple times results in an increasing value.
  • Why It’s Important: Non-idempotent operations require careful handling, especially in systems where requests might be retried due to network issues or failures. If not managed properly, these operations can cause unintended results like duplicate resources or inconsistent states.

Key Differences:

AspectIdempotentNon-Idempotent
DefinitionSame result on multiple executions of the same request.Different results or side effects with each execution.
Effect on ResourceDoes not alter the resource beyond the initial request.Alters the resource or system state with each request.
ExamplesGET, PUT (with same data), DELETE (if resource exists).POST, PATCH (depending on the operation), PUT (with different data).
Side EffectsNo additional side effects on repeated execution.Additional effects (e.g., duplicates, data changes) on repeated execution.
Safe to RetrySafe to retry without concern for unexpected side effects.Retry may cause undesirable changes or side effects.
Use in Distributed SystemsEssential for fault tolerance and safe retries.Requires careful handling to avoid unintended consequences.

Summary:

  • Idempotent operations are safe to repeat as they will not cause unintended changes, making them ideal for operations like data retrieval or resource replacement.
  • Non-idempotent operations change the state or create new resources with each request, and require special handling to avoid unwanted consequences when retrying requests.

 

 

Complete REST API Terminology with Real-Time Examples and Use Cases

Here's a comprehensive breakdown of the REST API terminology, including HTTP methods (GET, POST, PUT, DELETE, PATCH) with real-time examples and use cases:

 

Complete REST API Terminology with Real-Time Examples and Use Cases

Here's a comprehensive breakdown of the REST API terminology, including HTTP methods (GET, POST, PUT, DELETE, PATCH) with real-time examples and use cases:

 

1. Resource

  • Concept:
    A resource is an object or data that can be accessed or modified via an API.
    Real-Time Example:
    A user or product can be a resource in an e-commerce or user management system.
    Use Case:
    In an e-commerce platform, products are resources. You expose APIs to fetch details about a product, create a new product, or update its information.
    Project Scenario:
    In a shopping app, product, user, and order could all be resources.

2. Endpoint

 

Concept:
An endpoint is the URL where the client interacts with the API to access a resource or perform an action.
Real-Time Example:
/users, /products/{id}
Use Case:
In a banking application, /accounts/{accountId}/transactions could be an endpoint where transactions are fetched for a specific account.
Project Scenario:
In a social media app, /posts/{postId} is an endpoint to retrieve a specific post.

3. HTTP Methods

The following HTTP methods define the actions that can be performed on resources:

GET (Retrieve)

Concept: Used to fetch data from the server.
Real-Time Example:
GET /users: Fetch a list of users.
GET /users/{id}: Retrieve details for a specific user.
Use Case:
In a movie database API, GET /movies/{id} fetches details of a particular movie.
Project Scenario:
In a customer management system, GET /customers fetches all customer data.


POST (Create)

Concept: Sends data to the server to create a new resource.
Real-Time Example:
POST /users: Create a new user.
POST /products: Add a new product.
Use Case:
In an e-commerce app, POST /orders creates a new order.
Project Scenario:
In a restaurant booking system, POST /reservations creates a new reservation.


PUT (Update)

Concept: Replaces an existing resource with new data.
Real-Time Example:
PUT /users/{id}: Update an existing user.
PUT /products/{id}: Replace a product’s details.
Use Case:
In a social media app, PUT /posts/{postId} updates the content of a post.
Project Scenario:
In a task management system, PUT /tasks/{id} updates the status of a task.


DELETE (Remove)

Concept: Removes a resource from the server.
Real-Time Example:
DELETE /users/{id}: Delete a user.
DELETE /products/{id}: Remove a product.
Use Case:
In an admin panel, DELETE /users/{id} deletes a user account.
Project Scenario:
In a blog platform, DELETE /posts/{postId} removes a post from the system.


PATCH (Partial Update)

Concept: Used to partially update a resource. Unlike PUT, it only updates the provided fields.
Real-Time Example:
PATCH /users/{id}: Update specific user fields (e.g., only change the email address).
PATCH /products/{id}: Update only the price or description of a product.
Use Case:
In a CRM system, PATCH /customers/{id} could update a specific field (like the phone number) of a customer.
Project Scenario:
In a task management app, PATCH /tasks/{id} could update only the task description without changing the status or other fields.
 

4. HTTP Status Codes

  • Concept:
    HTTP status codes indicate the result of the server’s attempt to process the request.
    • 200 OK: The request was successful.
    • 400 Bad Request: The request was invalid or malformed.
    • 401 Unauthorized: Authentication is required.
    • 404 Not Found: The requested resource does not exist.
    • 500 Internal Server Error: There was a server-side error.
  • Real-Time Example:
    • 200 OK: Returning a successful response when a user is fetched.
    • 400 Bad Request: Returning an error if a required field is missing in a user creation request.
    • 404 Not Found: Returning an error if a requested product is not found.
  • Use Case:
    In an online store, 404 Not Found could be returned if a user attempts to access a non-existent product.
  • Project Scenario:
    In an e-commerce API, a successful order request returns 200 OK, while an invalid request (e.g., missing items) returns 400 Bad Request.

     

  • Note: For Info about Http methods & Http code visit https://www.niteshsynergy.com/http-methods-status-code

 

  • 5. Request and Response

  • Concept:
    • Request is data sent by the client, while Response is the server’s reply.
    • Request: Contains headers, parameters, body.
    • Response: Contains status code, headers, and body.
  • Real-Time Example:
    • Request: POST /users with JSON body containing user data.
    • Response: 200 OK with a confirmation message.
  • Use Case:
    In a registration API, the request includes user data (name, email, password), and the response confirms user creation.

     

  • 6. URI (Uniform Resource Identifier)

  • Concept:
    A URI identifies a specific resource. It often forms part of the URL.
    Real-Time Example:
    /users/{userId}, /products/{productId}
    Use Case:
    /users/12345 identifies a user by their unique ID.

     

     

    image-195.png

     

  •  
  • Complete REST API Terminology with Real-Time Examples and Use Cases

    Here's a comprehensive breakdown of the REST API terminology, including HTTP methods (GET, POST, PUT, DELETE, PATCH) with real-time examples and use cases:


    1. Resource

    • Concept:
      A resource is an object or data that can be accessed or modified via an API.
    • Real-Time Example:
      A user or product can be a resource in an e-commerce or user management system.
    • Use Case:
      In an e-commerce platform, products are resources. You expose APIs to fetch details about a product, create a new product, or update its information.
    • Project Scenario:
      In a shopping app, product, user, and order could all be resources.

    2. Endpoint

    • Concept:
      An endpoint is the URL where the client interacts with the API to access a resource or perform an action.
    • Real-Time Example:
      /users, /products/{id}
    • Use Case:
      In a banking application, /accounts/{accountId}/transactions could be an endpoint where transactions are fetched for a specific account.
    • Project Scenario:
      In a social media app, /posts/{postId} is an endpoint to retrieve a specific post.

    3. HTTP Methods

    The following HTTP methods define the actions that can be performed on resources:

    • GET (Retrieve)
      • Concept: Used to fetch data from the server.
      • Real-Time Example:
        • GET /users: Fetch a list of users.
        • GET /users/{id}: Retrieve details for a specific user.
      • Use Case:
        In a movie database API, GET /movies/{id} fetches details of a particular movie.
      • Project Scenario:
        In a customer management system, GET /customers fetches all customer data.
    • POST (Create)
      • Concept: Sends data to the server to create a new resource.
      • Real-Time Example:
        • POST /users: Create a new user.
        • POST /products: Add a new product.
      • Use Case:
        In an e-commerce app, POST /orders creates a new order.
      • Project Scenario:
        In a restaurant booking system, POST /reservations creates a new reservation.
    • PUT (Update)
      • Concept: Replaces an existing resource with new data.
      • Real-Time Example:
        • PUT /users/{id}: Update an existing user.
        • PUT /products/{id}: Replace a product’s details.
      • Use Case:
        In a social media app, PUT /posts/{postId} updates the content of a post.
      • Project Scenario:
        In a task management system, PUT /tasks/{id} updates the status of a task.
    • DELETE (Remove)
      • Concept: Removes a resource from the server.
      • Real-Time Example:
        • DELETE /users/{id}: Delete a user.
        • DELETE /products/{id}: Remove a product.
      • Use Case:
        In an admin panel, DELETE /users/{id} deletes a user account.
      • Project Scenario:
        In a blog platform, DELETE /posts/{postId} removes a post from the system.
    • PATCH (Partial Update)
      • Concept: Used to partially update a resource. Unlike PUT, it only updates the provided fields.
      • Real-Time Example:
        • PATCH /users/{id}: Update specific user fields (e.g., only change the email address).
        • PATCH /products/{id}: Update only the price or description of a product.
      • Use Case:
        In a CRM system, PATCH /customers/{id} could update a specific field (like the phone number) of a customer.
      • Project Scenario:
        In a task management app, PATCH /tasks/{id} could update only the task description without changing the status or other fields.

    4. HTTP Status Codes

    • Concept:
      HTTP status codes indicate the result of the server’s attempt to process the request.
      • 200 OK: The request was successful.
      • 400 Bad Request: The request was invalid or malformed.
      • 401 Unauthorized: Authentication is required.
      • 404 Not Found: The requested resource does not exist.
      • 500 Internal Server Error: There was a server-side error.
    • Real-Time Example:
      • 200 OK: Returning a successful response when a user is fetched.
      • 400 Bad Request: Returning an error if a required field is missing in a user creation request.
      • 404 Not Found: Returning an error if a requested product is not found.
    • Use Case:
      In an online store, 404 Not Found could be returned if a user attempts to access a non-existent product.
    • Project Scenario:
      In an e-commerce API, a successful order request returns 200 OK, while an invalid request (e.g., missing items) returns 400 Bad Request.

    5. Request and Response

    • Concept:
      • Request is data sent by the client, while Response is the server’s reply.
      • Request: Contains headers, parameters, body.
      • Response: Contains status code, headers, and body.
    • Real-Time Example:
      • Request: POST /users with JSON body containing user data.
      • Response: 200 OK with a confirmation message.
    • Use Case:
      In a registration API, the request includes user data (name, email, password), and the response confirms user creation.

    6. URI (Uniform Resource Identifier)

    • Concept:
      A URI identifies a specific resource. It often forms part of the URL.
    • Real-Time Example:
      /users/{userId}, /products/{productId}
    • Use Case:
      /users/12345 identifies a user by their unique ID.

    7. Path Parameter

    • Concept:
      Path parameters are used to specify particular resources in the URL.
    • Real-Time Example:
      /users/{userId}, where {userId} is a placeholder for a real value.
    • Use Case:
      /products/{productId} can be used to fetch details about a specific product by its ID.

    8. Query Parameter

    • Concept:
      Query parameters are added to the URL to filter or modify the results.
    • Real-Time Example:
      /products?category=electronics&price=100-500
    • Use Case:
      Filtering products based on category and price.

    9. Request Body

    • Concept:
      The request body is used to send data to the server in POST, PUT, or PATCH requests.
    • Real-Time Example:
      POST /users  with a body containing user details like:
  • {
     "name": "John Doe",
     "email": "john@example.com"
    }
     
  • Use Case:
    Creating a new user account in a user management system.
  •  
  • image-196.png

     

    image-197.png

     

    image-198.png

     

    In REST API development with Spring Boot, annotations are used to define endpoints, handle HTTP requests, and manage various aspects like security, data binding, and response formatting. Below is an overview of key annotations used in Spring Boot for REST APIs, along with use cases and examples.

    image-199.png
    image-200.png

     

    image-201.png

     

    image-202.png

     

    image-203.png

     

    image-204.png

     

    image-205.png
    image-206.png

     

     

    image-207.png

     

    image-208.png

     

    image-209.png

     

    image-210.png
  • Complex Project Example

  • For a complex project like an Employee Management System with features like authentication, user roles (Admin, User), CRUD operations, and file upload, you might use the following annotations:

     

  • User Authentication with JWT:
  • @RequestMapping and @PostMapping for login and token generation endpoints.
    @PreAuthorize for role-based access control in methods.
    CRUD Operations for Employee Data:
  • @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping for handling employee data.
    File Upload:
  • @RequestParam for handling file upload via POST requests.
    Exception Handling:
  • @ExceptionHandler for managing EmployeeNotFoundException and other errors.
    Data Validation:
  • @Valid with @RequestBody for validating incoming JSON.
    CORS:
  • @CrossOrigin for enabling cross-origin requests from a front-end application.
     


Read  https://www.niteshsynergy.com/at-requestparam-vs-at-queryparam-vs-at-pathvariable-vs-at-pathparam

before processing next 

 Next → 

 

  • @RestController is a specialized version of the @Controller annotation in Spring, designed for building RESTful web services. It is part of the Spring Web module, primarily used in Spring Boot applications to handle HTTP requests and return data directly to the client in formats like JSON or XML.
  • Detailed Explanation

  • 1. Combination of @Controller and @ResponseBody

  • @RestController is a convenience annotation that combines the functionality of two annotations:
    • @Controller: Marks the class as a Spring MVC controller, meaning it's capable of handling HTTP requests and responses.
    • @ResponseBody: Ensures that the return values of the controller methods are written directly to the HTTP response body (typically in JSON or XML), instead of being interpreted as view names.
  • 2. Use Case

  • For RESTful APIs: It is specifically used to build REST APIs where the response is typically in the form of data (e.g., JSON) rather than a view (HTML page). It simplifies controller creation for REST-based applications.
  • No Views or Templates: Since @RestController uses @ResponseBody, it eliminates the need for rendering HTML views. You don't need to configure ViewResolvers or use technologies like JSP or Thymeleaf for rendering views.
  • 3. Internal Flow in Spring Framework

  • When a controller is annotated with @RestController, Spring internally applies both @Controller and @ResponseBody annotations. This allows the class to handle HTTP requests and serialize the return values to a response body directly.
  • The methods in the controller can return any object, which Spring will automatically convert into JSON (or XML) using HttpMessageConverters. The default behavior is to use Jackson for JSON conversion, but this can be customized.
  • Spring automatically sets the Content-Type of the response (usually to application/json) if the method returns a type that can be serialized into JSON (like POJOs, collections, etc.).
  • 4. Example

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

   @GetMapping
   public List<Employee> getAllEmployees() {
       // This method will return a list of employees as JSON response
       return employeeService.getAllEmployees();
   }

   @PostMapping
   public ResponseEntity<Employee> createEmployee(@RequestBody Employee employee) {
       // This method will accept a JSON body, process it, and return a created employee
       Employee savedEmployee = employeeService.saveEmployee(employee);
       return new ResponseEntity<>(savedEmployee, HttpStatus.CREATED);
   }
}
 

In the above example:

  • The getAllEmployees() method will return a list of employees in JSON format (due to @RestController).
  • The createEmployee() method will accept a JSON payload via @RequestBody, process it, and return a ResponseEntity containing the created employee as a JSON object.

5. Other Annotations You Can Use with @RestController

  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: To handle specific HTTP methods (GET, POST, PUT, DELETE).
  • @RequestBody: Used to bind the HTTP request body to a method parameter.
  • @PathVariable: Used to bind a URI template variable to a method parameter.
  • @RequestParam: Used to access query parameters in the URL.

6. Benefits

  • Cleaner Code: @RestController removes the need for returning a view or using @ResponseBody on each method, simplifying the controller code.
  • Automatic JSON Conversion: It provides automatic handling of HTTP request and response body serialization and deserialization, saving time on manual conversion.
  • API-First Development: Ideal for developing RESTful web services where responses are meant to be processed by clients (e.g., browsers, mobile apps).

7. Example Scenario

Consider an Employee Management System where users (client applications) want to interact with employee data (add, update, view, delete employees). @RestController can be used to define API endpoints for these operations:

 

@RestController
@RequestMapping("/api/employees")
public class EmployeeController {

   @GetMapping("/{id}")
   public Employee getEmployeeById(@PathVariable Long id) {
       // Logic to fetch employee by ID
       return employeeService.getEmployeeById(id);
   }

   @PutMapping("/{id}")
   public Employee updateEmployee(@PathVariable Long id, @RequestBody Employee employee) {
       // Logic to update employee
       return employeeService.updateEmployee(id, employee);
   }
}
 

 

In this example, @RestController simplifies the controller definition for a typical REST API where the client consumes data in JSON format.

 

 

Difference between PUT and Patch : 
PUT :-- It indicates modify complete (full) data, based on Identity (ID-PK). 
PATCH :-- It indicates modify partial (few data, based on Identity (ID-PK).

1. PUT: Full Update

  • Purpose: The PUT method is used when you need to completely replace a resource or update all fields of a resource. It operates based on the identity of the resource (usually via its unique identifier, such as ID or primary key).
  • Behavior:
    • When a PUT request is sent, the client usually provides a complete set of data that should replace the existing resource.
    • Any fields not included in the request body will not be part of the resource after the update (unless the server’s behavior is explicitly designed to retain them).
    • This is ideal when the client is aware of the entire state of the resource and intends to update all of it.
  • Example Scenario:
    • Scenario: You have a user profile with fields like name, email, phone number, address, etc. If the client sends a PUT request to update the user's profile, it will typically include all the fields of the user. Even if only the phone number is being changed, the client must resend the complete profile (with the unchanged fields like name and email).

PUT /users/123
{
 "name": "John Doe",
 "email": "john@example.com",
 "phone": "1234567890",
 "address": "123 Main St"
}
 

  •  
    • In this case, the whole user profile will be replaced, and if the phone was the only change, it’s still necessary to include the unchanged fields (name, email, address).
  • Example Use Case:
    • Updating a resource when all fields are available and must be updated.
    • E.g. Updating a user's entire profile (address, phone, email, etc.) where all fields are mandatory to avoid data loss.

 

2. PATCH: Partial Update

  • Purpose: The PATCH method is used for partial updates to a resource. It allows the client to modify only the specific fields that need to be changed, leaving the other fields untouched. Like PUT, it operates based on the identity of the resource (e.g., user ID).
  • Behavior:
    • When a PATCH request is sent, only the fields that need to be updated are included in the request body. This means the client can send just the modified fields.
    • The server will merge the changes with the existing resource. If a field is not included in the request, it will remain unchanged.
    • This is ideal for situations where the client doesn't have the entire resource or just needs to make small adjustments.
  • Example Scenario:
    • Scenario: Consider the same user profile. If only the phone number needs to be updated, the client can send a PATCH request that only includes the phone field, leaving the name, email, and address unchanged.
    • Example Request:
    •  
    •  
    •  

PATCH /users/123
{
 "phone": "9876543210"
}
 

  • In this case, only the phone number is updated, and the other fields (name, email, address) remain unchanged.
  • Example Use Case:
    • Modifying just one or a few fields of a resource while keeping the rest intact.
    • E.g. Updating a user's phone number or email address without affecting other fields of the user profile.
    •  
    •  

Complex Scenario Justification:

Let’s justify the use of PUT and PATCH in complex scenarios:

Scenario 1: Updating an Order Status

Imagine an e-commerce platform where an order has the following fields:

  • orderId (ID)
  • customerName
  • items (List of items)
  • totalAmount
  • status
  • If an admin wants to completely update the order details (e.g., change the customerName, items, totalAmount, and status), they would use PUT:
  •  

PUT /orders/123
{
 "orderId": "123",
 "customerName": "Jane Smith",
 "items": ["item1", "item2"],
 "totalAmount": 100.0,
 "status": "Shipped"
}
 

 

  •  
    • This replaces the entire order data.
  • If the admin only wants to update the order status, without changing the items or customerName, they would use PATCH:

    PATCH /orders/123
    {
     "status": "Shipped"
    }
    This only updates the status field and leaves the rest of the order data untouched.

     

    Scenario 2: Profile Management

    In a system where users can update their profiles:

    • A user might use PUT to update their complete profile (e.g., name, email, address, phone, etc.) when they have a full set of new data for all fields.
    •  
    •  
    • PUT /users/123
      {
       "name": "John Doe",
       "email": "john.doe@example.com",
       "phone": "123456789",
       "address": "456 Elm St"
      }
       
    •  

    If the user only wants to update their phone number, they can send a PATCH request:

    PATCH /users/123
    {
     "phone": "987654321"
    }
     

    Summary of Differences in Complex Scenarios:

    • PUT:
      • Replaces the entire resource.
      • Necessary when the client knows the full state of the resource and wants to modify all fields.
      • Example: Replacing a complete user profile or updating an order’s details (not just one field).
    • PATCH:
      • Updates only the specified fields.
      • Used when the client only wants to modify a subset of the resource.
      • Example: Changing just one field (e.g., updating an address or changing a status) without affecting other parts of the resource.
      •  

     

     

     

    Passing Input to RestController:--

    Those are :-- 

    1>Request Header 

    :-- It provides data in key=value format (both are String type). =>Request header also called as Header Parameters. =>These are used to provide instructions to server (application/Controller). Ex:-- Content-Type, Accept, host, Date, Cookies…

     

    2>Request Body *** 

    :-- To send large/bulk data like objects and collections data in the form of JSON/XML. =>Even supported large text (Raw data). =>Spring boot enables JSON conversion by default, but not XML (no JAXB API).

    3>Request Parameter 

    :-- To pass primitive data (like id, name, codes … etc) as input, request parameters are used. =>format looks like url?key=val&key=val… 

    =>Both key and value are String type by default. 

    Request Parameter: 

    Format:-- 

    @RequestParam( value="key", required=true/false, defaultValue="-value-")

     @RestController
     public class 
    AdminRestController {
     @GetMapping("/show") 
    public String showMsg(@RequestParam (value="sname", required=false, defaultValue="NO DATA") String sid) {
     return "Hello:" +sid;
     }
     }

    GET http://localhost:8080/show?
       sname={{$random.alphanumeric(8)}}

    <> 2024-11-24T003752.200.txt


    ###
    GET http://localhost:8080/show?
       sname="NiteshSynergy"
     

    4>Path Variable *** 

    Path Variable [Path Parameters]:-- =>We can send data using URL (path). =>It supports only Primitive Data. 

    Paths are two types:-- 

    a.>Static Path [format:/url] 

    b.>Dynamic Path [format:/{key}]

    =>Static Path indicates URL, where as Dynamic Path indicates Data at runtime.
    =>While sending data using Dynamic Path key should not be used. Only data
    =>Order must be followed in case of sending multiple Parameters.
    =>To read data at controller method, use annotation : @PathVariable.

     

    package org.niteshsynergy.controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RestController;
    @RestController
    public class StudentController {
       @GetMapping("/show/{sid}/{sname}/{sfee}")
       public String show(@PathVariable int sid, @PathVariable String sname, @PathVariable String sfee){
           return "Heloo :" +sid+","+sname+ ","+sfee;
       }
    }

     

    ###
    GET http://localhost:8080/show/12345/niteshsynergy/123.22

    Note: =>To Convert Object to JSON (and JSON to Object) SpringBoot uses JACKSON API.

     

    MediaType Conversion annotations are:--
    =>@RequestBody and @ResponseBody are the MediaType annotations.
    =>Here, @ResponseBody is applied when we write @RestController annotation over
    class (**Not handled by programmer). It converts Class/Collection type to JSON/XML.
    =>@RequestBody should be handled by programmer. It converts JSON/XML Data to
    Object format.

     

    image-216.png

     

    @Transactional:

    • This is a Spring annotation that indicates the method should run within a transaction.
    • If the method completes successfully, the transaction will be committed (i.e., changes are saved to the database).
    • If an exception occurs during the execution of the method, the transaction will be rolled back (i.e., changes are not saved).

     

    Key Points about @Transactional(readOnly = true):
    Read-Only Transaction:

    The readOnly = true attribute tells the Spring framework that the transaction should only be used for reading data (i.e., SELECT operations).
    It can optimize performance by disabling some features related to write operations, such as transaction log writes, and reducing unnecessary overhead.
    It also indicates to the database (if it supports it) that no changes will be made during the transaction, which may allow for optimizations (e.g., locking behavior might differ).
    No Write Operations:

    When a method is annotated with @Transactional(readOnly = true), Spring will not allow any database modifications like INSERT, UPDATE, or DELETE to be executed within the transaction.
    If any write operation is attempted, an exception (typically javax.persistence.TransactionRequiredException) might be thrown.
    Use Case:

    Typically used in read-only operations, such as fetching data or executing queries that do not modify the database.
    Commonly used in getter methods or service methods that only query the database.
     

     

    Enable Swagger UI in Spring Boot ReST Application:--

    Enable Swagger UI in Spring Boot ReST Application:-- =>Compared to all other tools Swagger is a RichSet API provides dynamic UI based on code written for Rest Controller with common Paths.

     

    Step#1:- Add below dependencies in pom.xml
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
    </dependency>
    <dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
    </dependency>
     

     

32 min read
Nov 22, 2024
By Nitesh Synergy
Share