Popular Searches
Popular Course Categories
Popular Courses

Understanding Web Services and REST Architecture

Understanding Web Services and REST Architecture

RESTful Web Services and API Development

Understanding Web Services and REST Architecture

Course: Advanced Java Training

Topic: Understanding Web Services and REST Architecture

Course Link: Advanced Java Training – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Web Services

A web service is a software component that allows different applications to communicate and exchange information over a network using standardized protocols and data formats. Web services enable applications built with different programming languages, operating systems, and technologies to interact with one another.

For example, an e-commerce application may use a payment service to process transactions, a shipping service to calculate delivery charges, and an authentication service to verify customers. These services communicate through defined interfaces without requiring the applications to share the same internal implementation.

Why Are Web Services Important?

  • Interoperability: Applications built with Java, Python, JavaScript, or other technologies can communicate.
  • Reusability: A service can be used by multiple applications.
  • Loose coupling: Clients interact with a service interface rather than depending on its internal implementation.
  • Scalability: Services can be deployed and scaled according to application requirements.
  • Integration: Web services connect websites, mobile applications, enterprise systems, and third-party platforms.
  • Maintainability: Services can evolve independently when their interfaces remain compatible.

2. What Is a Web Service?

A web service exposes functionality or data through a network-accessible interface. A client sends a request to the service, the service processes it, and a response is returned.

Example of a Web Service

Consider a student management application. The frontend needs to retrieve the details of a student from a Java backend.

  1. The user opens the student details page.
  2. The frontend sends a request to the backend web service.
  3. The backend validates the request and retrieves student information from the database.
  4. The backend converts the result into an appropriate response format, such as JSON.
  5. The frontend receives the response and displays the student details.

Basic Communication Diagram

Client Application
        |
        | HTTP Request
        v
Web Service / API
        |
        | Business Logic
        v
Database or External Service
        |
        | Result
        v
Web Service / API
        |
        | HTTP Response
        v
Client Application

This request-response pattern is common in web applications. The exact communication flow depends on the service architecture and the operation being performed.

3. Types of Web Services

Web services can be implemented using different architectural approaches and communication standards. SOAP and REST are two widely discussed approaches, while technologies such as XML-RPC and GraphQL address other service communication needs.

Type Description Common Characteristics
SOAP Web Services Use the SOAP messaging protocol for exchanging structured messages. XML envelopes, formal service contracts, and support for WS-* standards.
RESTful Web Services Follow REST architectural constraints and commonly use HTTP. Resource-oriented URLs, standard HTTP methods, and representations such as JSON.
XML-RPC Uses XML to encode remote procedure calls. Procedure-oriented communication with structured XML messages.
GraphQL APIs Allow clients to request specific fields through a query language. Flexible data selection and a defined schema.

REST and SOAP are not identical concepts: REST is an architectural style, whereas SOAP is a messaging protocol. GraphQL is another API approach and is not itself a REST architecture.

4. Understanding REST Architecture

REST stands for Representational State Transfer. It is an architectural style for designing network-based systems. REST was introduced by Roy Fielding and describes constraints that help create scalable, interoperable, and maintainable distributed applications.

In REST, data and functionality are represented as resources. Each resource is identified through a URI, and clients interact with resources using a uniform interface. A representation of a resource may be returned in JSON, XML, or another suitable format.

Example of REST Resources

/api/students
/api/students/101
/api/courses
/api/courses/201
/api/orders/501

These endpoints represent collections or individual resources. HTTP methods determine the intended operation on a resource.

Key Characteristics of REST

  • Resources are identified by URIs.
  • Clients and servers have separate responsibilities.
  • Requests use a uniform interface, commonly standard HTTP methods.
  • Each request contains the information required to process it independently.
  • Responses may be cached when the applicable HTTP caching rules permit it.
  • REST supports multiple representations of resource data.

5. The Six Constraints of REST Architecture

A system is considered RESTful when it follows the applicable architectural constraints defined by REST. These constraints help promote scalability, visibility, portability, and reliability.

5.1 Client-Server Architecture

The client handles the user interface and user interactions, while the server handles business logic, data access, and service responses. Separating these responsibilities allows both sides to evolve independently.

Example: A React frontend communicates with a Java Spring Boot backend through REST API endpoints.

5.2 Statelessness

Each request must contain the information needed to process it. The server does not depend on stored conversational session state from a previous request to understand the current request.

For example, an authenticated API request may include a bearer access token. The server validates the token for the current request instead of relying on an undocumented sequence of earlier requests.

5.3 Cacheability

Responses should indicate whether they can be cached when caching is appropriate. Correct caching can reduce repeated requests, lower server load, and improve response times.

Example: Public course catalogue data may be cached for a limited period when the data is not changing frequently.

5.4 Uniform Interface

REST uses a consistent interface for identifying resources, manipulating them, and communicating their representations. With HTTP-based REST APIs, standard methods such as GET, POST, PUT, PATCH, and DELETE express the intended operation.

5.5 Layered System

A client may communicate with a server through intermediary components such as gateways, proxies, load balancers, and security filters. The client does not need to know the internal structure of these layers.

5.6 Code on Demand (Optional)

REST permits a server to provide executable code to a client when appropriate. This constraint is optional. For example, a web server might deliver JavaScript that runs in a browser.

6. Understanding Resources, URIs, and Representations

A resource is an identifiable item of information or functionality exposed by a service. A URI identifies the resource, while a representation describes its state in a transferable format.

Concept Definition Example
Resource The data or entity being accessed. A student record.
URI The identifier used to locate a resource. /api/students/101
Representation The resource data transferred to the client. A JSON student object.
HTTP Method Indicates the intended operation. GET
HTTP Header Provides request or response metadata. Content-Type: application/json

Example JSON Representation

{
  "id": 101,
  "name": "Rahul Sharma",
  "email": "[email protected]",
  "course": "Advanced Java"
}

This JSON object represents a student resource. The actual fields and data returned by an API depend on its data model and access rules.

7. HTTP Methods Used in REST APIs

HTTP methods communicate the intended action for a request. Correct method selection makes APIs easier to understand and allows clients, proxies, and other infrastructure to apply standard HTTP semantics.

Method Purpose Example Important Property
GET Retrieve a resource or collection. GET /api/students/101 Safe and idempotent.
POST Create a resource or submit data for processing. POST /api/students Not inherently idempotent.
PUT Create or replace the state of a resource at a known URI. PUT /api/students/101 Idempotent by HTTP semantics.
PATCH Apply a partial modification to a resource. PATCH /api/students/101 Idempotency depends on the operation design.
DELETE Request removal of a resource. DELETE /api/students/101 Idempotent by HTTP semantics.
HEAD Retrieve response headers without the response body. HEAD /api/students/101 Safe and idempotent.
OPTIONS Discover supported communication options. OPTIONS /api/students Safe and idempotent.

What Is Idempotency?

An operation is idempotent when repeating the same request has the same intended effect on server state as performing it once. For example, repeating a PUT request with the same replacement representation should leave the resource in the same intended state.

Idempotency does not mean that every response must be identical. For example, the first DELETE request may return a success response while a later request returns a not-found response.

8. HTTP Status Codes in REST Architecture

HTTP status codes communicate the result of a request. Choosing an appropriate status code helps API consumers understand whether an operation succeeded, failed validation, requires authentication, or encountered a server problem.

Status Code Meaning Typical Use
200 OK The request succeeded. Retrieving a student record.
201 Created A resource was created. Creating a student.
202 Accepted The request was accepted for processing. Starting an asynchronous report job.
204 No Content The request succeeded without a response body. Deleting a resource successfully.
400 Bad Request The request is invalid. Malformed JSON or invalid request structure.
401 Unauthorized Valid authentication credentials are missing or invalid. Missing or expired access token.
403 Forbidden The client is not permitted to perform the operation. Insufficient permissions.
404 Not Found The requested resource cannot be found. Unknown student ID.
409 Conflict The request conflicts with the current resource state. Duplicate record or conflicting update.
422 Unprocessable Content The request content is understood but cannot be processed according to the API's validation rules. Business validation failure.
500 Internal Server Error An unexpected server-side error occurred. Unhandled application exception.
503 Service Unavailable The service is temporarily unable to handle the request. Temporary service overload or maintenance.

9. Difference Between REST and SOAP

REST and SOAP are different approaches to building network-accessible services. REST defines architectural constraints, while SOAP defines a structured messaging protocol.

Feature REST SOAP
Nature Architectural style. Messaging protocol.
Communication Commonly uses HTTP. Can use HTTP and other supported transports.
Data Formats Often JSON; can also use XML and other representations. XML-based SOAP messages.
Message Structure Uses standard protocol messages and representations. Uses a SOAP envelope with header and body elements.
Interface Description Can be documented using OpenAPI or other approaches. Often described using WSDL.
Typical Usage Web APIs, mobile backends, microservices. Enterprise integrations requiring SOAP and related standards.
Security Can use TLS, OAuth 2.0, OpenID Connect, and other suitable mechanisms. Can use TLS and WS-Security or other appropriate controls.

Neither approach is universally better. Select an architecture based on integration requirements, existing systems, interoperability needs, security requirements, and operational constraints.

10. REST API Request and Response Structure

An HTTP request usually contains a method, target URI, headers, and optionally a body. The server responds with a status code, headers, and optionally a response body.

Example Request

POST /api/students HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Accept: application/json

{
  "name": "Rahul Sharma",
  "email": "[email protected]",
  "course": "Advanced Java"
}

Example Response

HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/students/101

{
  "id": 101,
  "name": "Rahul Sharma",
  "email": "[email protected]",
  "course": "Advanced Java"
}

The example shows a successful resource-creation response. The actual ID, response body, and headers depend on the API implementation.

Important HTTP Headers

Header Purpose
Content-Type Identifies the format of the request or response body.
Accept Indicates which response media types the client can accept.
Authorization Carries authentication credentials or an access token.
Cache-Control Specifies caching directives.
Location Identifies the location of a created resource or another relevant target.
ETag Provides a validator that can support cache validation and conditional requests.

11. Introduction to RESTful Web Services in Java

Java developers can create RESTful web services using frameworks and APIs such as Spring Boot with Spring MVC or Jakarta REST. These technologies provide annotations and tools for mapping HTTP requests to Java methods.

Common Technologies

  • Java: The programming language used to implement business logic.
  • Spring Boot: Simplifies application setup and configuration.
  • Spring Web: Provides HTTP request mapping and REST controller support.
  • Jakarta REST: Provides standard APIs for building RESTful services.
  • Jackson: Commonly converts Java objects to and from JSON in Spring Boot applications.
  • Maven or Gradle: Manages project dependencies and builds.
  • Postman or curl: Helps test API requests and responses.

12. Creating a REST API Using Spring Boot

Spring Boot makes it straightforward to build REST APIs using annotated controller classes. The following example creates a simple student API. It uses an in-memory collection to demonstrate HTTP operations; it is not a production database implementation.

Step 1: Create a Spring Boot Project

Create a Spring Boot project using Spring Initializr and add the Spring Web dependency. Use a compatible Java and Spring Boot version for your development environment.

Step 2: Create a Student Model

package com.example.demo;

public class Student {
    private Long id;
    private String name;
    private String email;

    public Student() {
    }

    public Student(Long id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

The Student class represents the data transferred through the API. Getters and setters allow the framework to read and populate object properties.

Step 3: Create a REST Controller

package com.example.demo;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/api/students")
public class StudentController {

    private final List<Student> students = new ArrayList<>();
    private final AtomicLong idGenerator = new AtomicLong(100);

    @GetMapping
    public List<Student> getAllStudents() {
        return new ArrayList<>(students);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Student> getStudentById(
            @PathVariable Long id) {

        return students.stream()
                .filter(student -> student.getId().equals(id))
                .findFirst()
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<Student> createStudent(
            @RequestBody Student student) {

        student.setId(idGenerator.incrementAndGet());
        students.add(student);

        return ResponseEntity
                .status(HttpStatus.CREATED)
                .body(student);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Student> updateStudent(
            @PathVariable Long id,
            @RequestBody Student updatedStudent) {

        for (Student student : students) {
            if (student.getId().equals(id)) {
                student.setName(updatedStudent.getName());
                student.setEmail(updatedStudent.getEmail());
                return ResponseEntity.ok(student);
            }
        }

        return ResponseEntity.notFound().build();
    }

    @PatchMapping("/{id}")
    public ResponseEntity<Student> patchStudent(
            @PathVariable Long id,
            @RequestBody Map<String, String> changes) {

        for (Student student : students) {
            if (student.getId().equals(id)) {
                if (changes.containsKey("name")) {
                    student.setName(changes.get("name"));
                }
                if (changes.containsKey("email")) {
                    student.setEmail(changes.get("email"));
                }
                return ResponseEntity.ok(student);
            }
        }

        return ResponseEntity.notFound().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteStudent(
            @PathVariable Long id) {

        boolean removed = students.removeIf(
                student -> student.getId().equals(id));

        if (removed) {
            return ResponseEntity.noContent().build();
        }

        return ResponseEntity.notFound().build();
    }
}

Important: This teaching example stores records in memory, so the data disappears when the application restarts. The collection is also not suitable for concurrent production use. A real application should use a database, repository layer, validation, and appropriate error handling.

13. Understanding Spring REST Annotations

Annotation Purpose Example
@RestController Declares a controller whose handler results are written to the response body by default. StudentController
@RequestMapping Defines a base path or other request-mapping conditions. /api/students
@GetMapping Maps GET requests. Retrieve all students.
@PostMapping Maps POST requests. Create a student.
@PutMapping Maps PUT requests. Replace a student's editable fields.
@PatchMapping Maps PATCH requests. Modify selected fields.
@DeleteMapping Maps DELETE requests. Delete a student.
@PathVariable Reads a value from the URL path. /students/{id}
@RequestParam Reads a query parameter. ?page=0
@RequestBody Converts the request body into a Java object. Student JSON payload.
@ResponseStatus Specifies a response status for a handler or exception. HttpStatus.CREATED

14. Testing REST APIs

REST APIs should be tested to verify that they return the expected status codes, headers, and response bodies. Tools such as Postman, curl, automated integration tests, and browser developer tools can help inspect API behavior.

Example API Tests

Operation Method URL Expected Result
List students GET /api/students 200 OK
Get student GET /api/students/101 200 OK or 404 Not Found
Create student POST /api/students 201 Created
Replace student fields PUT /api/students/101 200 OK or 404 Not Found
Modify student fields PATCH /api/students/101 200 OK or 404 Not Found
Delete student DELETE /api/students/101 204 No Content or 404 Not Found

Example curl Request

curl -i http://localhost:8080/api/students

The -i option displays response headers along with the response body, helping you inspect the HTTP status and content type.

15. REST API Design Best Practices

  • Use resource-oriented URLs: Prefer /api/students/101 over action-based paths such as /getStudentById/101.
  • Use HTTP methods correctly: Select methods based on their standard semantics.
  • Return suitable status codes: Communicate success and failure clearly.
  • Validate input: Reject invalid or incomplete data before processing.
  • Use consistent representations: Define predictable JSON response structures.
  • Handle errors centrally: Return useful error responses without leaking internal stack traces.
  • Support pagination: Avoid returning huge collections in a single response.
  • Document APIs: Describe endpoints, parameters, request bodies, and responses using OpenAPI or equivalent documentation.
  • Version carefully: Use a documented strategy when incompatible API changes are required.
  • Use caching appropriately: Apply HTTP caching and conditional requests when they suit the data.

16. Security in RESTful Web Services

REST APIs frequently expose business data and operations, so security must be considered during design and implementation. HTTPS protects data in transit, while authentication and authorization control who can access particular operations.

Important Security Practices

  • Use HTTPS in production.
  • Implement appropriate authentication, such as OAuth 2.0 or other suitable mechanisms.
  • Enforce authorization on every protected resource and operation.
  • Validate and sanitize input according to the data type and business rules.
  • Protect against SQL injection by using parameterized queries or suitable ORM techniques.
  • Apply rate limits and abuse protection where appropriate.
  • Do not expose passwords, tokens, or sensitive personal data in responses or logs.
  • Use secure CORS policies when browser-based clients need cross-origin access.
  • Keep libraries and framework dependencies updated.
  • Return safe error messages that do not expose implementation details.

Authentication vs Authorization

Concept Meaning Example
Authentication Verifies the identity of a client or user. Validating an access token.
Authorization Determines which operations the authenticated identity may perform. Allowing an administrator to delete a student record.

17. Common REST API Errors and Troubleshooting

Problem Possible Cause Solution
404 Not Found Incorrect endpoint or resource ID. Verify the URL, route mapping, and resource existence.
405 Method Not Allowed The endpoint does not support the requested HTTP method. Check the controller's request mapping and use the correct method.
400 Bad Request Malformed JSON or invalid request data. Check the payload format and validation rules.
415 Unsupported Media Type Unsupported request content type. Set the appropriate Content-Type header.
401 Unauthorized Missing or invalid authentication credentials. Check the authentication mechanism and credentials.
403 Forbidden The client lacks permission. Review authorization rules.
500 Internal Server Error An unexpected application exception occurred. Inspect server logs and exception handling.
Unexpected JSON response Incorrect serialization, data structure, or response mapping. Inspect the model, getters, serializer configuration, and controller return value.

18. Practical Project: Student Management REST API

Build a Student Management REST API using Java and Spring Boot. The API should support creating, retrieving, updating, and deleting student records.

Project Requirements

  • Create a Spring Boot project with Spring Web.
  • Define a Student model containing ID, name, email, and course.
  • Create REST endpoints for CRUD operations.
  • Use suitable HTTP methods and status codes.
  • Validate incoming request data.
  • Add a service layer to separate business logic from the controller.
  • Connect the application to a relational database using Spring Data JPA.
  • Handle missing records and invalid requests consistently.
  • Test each endpoint with Postman or automated tests.
  • Document the API endpoints and expected responses.

Suggested API Endpoints

Method Endpoint Functionality
GET /api/students Retrieve all students.
GET /api/students/{id} Retrieve one student.
POST /api/students Create a student.
PUT /api/students/{id} Replace a student's editable data.
PATCH /api/students/{id} Update selected student fields.
DELETE /api/students/{id} Delete a student.

Expected Learning Outcomes

After completing this project, learners should understand how HTTP requests reach Java controllers, how JSON data is mapped to Java objects, how REST endpoints implement CRUD operations, and how status codes communicate operation results.

19. Interview Questions and Answers

Q1. What is a web service?

Answer: A web service is a network-accessible software component that allows applications to exchange data or invoke functionality through a defined interface.

Q2. What does REST stand for?

Answer: REST stands for Representational State Transfer. It is an architectural style for designing distributed systems around resources and representations.

Q3. What is a REST API?

Answer: A REST API is an interface that follows REST architectural principles, commonly using HTTP methods and resource-oriented URLs to exchange data.

Q4. What is the difference between REST and SOAP?

Answer: REST is an architectural style, while SOAP is a messaging protocol that defines a structured XML-based message format.

Q5. What is a resource in REST?

Answer: A resource is an identifiable item of data or functionality, such as a student, order, product, or employee.

Q6. What is the purpose of a URI?

Answer: A URI identifies a resource that can be accessed through the API.

Q7. What is the difference between PUT and PATCH?

Answer: PUT is generally used to create or replace the state of a resource at a known URI, while PATCH applies a partial modification. The exact update behavior should be documented by the API.

Q8. What is statelessness in REST?

Answer: Each request carries the information needed to process it without depending on conversational state stored from previous requests.

Q9. What is the purpose of HTTP status codes?

Answer: They communicate whether a request succeeded, failed, requires authentication, or encountered another condition.

Q10. What is the difference between 401 and 403?

Answer: A 401 response indicates that valid authentication credentials are missing or invalid. A 403 response indicates that the client is not permitted to perform the requested operation.

Q11. What is JSON?

Answer: JSON is a lightweight data-interchange format commonly used by REST APIs to represent objects, arrays, strings, numbers, booleans, and null values.

Q12. What is the purpose of @RestController?

Answer: In Spring MVC, @RestController combines controller behavior with response-body handling, making it convenient to return objects that are serialized into formats such as JSON.

Q13. What is the purpose of @PathVariable?

Answer: It binds a value from the URL path to a method parameter, such as an ID in /api/students/101.

Q14. What is the purpose of @RequestBody?

Answer: It binds the HTTP request body to a Java object through an appropriate message converter.

Q15. What is idempotency in HTTP?

Answer: Idempotency means that repeating an identical request has the same intended effect on server state as making it once. GET, PUT, and DELETE are defined as idempotent methods, although their responses may differ.

Q16. Why is API validation important?

Answer: Validation prevents invalid or incomplete data from reaching business logic and helps maintain data quality and application reliability.

Q17. What is API versioning?

Answer: API versioning is a strategy for managing interface changes while supporting existing consumers. It can use URL paths, headers, or other documented conventions.

Q18. How can REST APIs be secured?

Answer: Use HTTPS, appropriate authentication and authorization, input validation, rate limiting, secure error handling, and regular dependency updates.

20. Quick Revision Checklist

  • Understand the purpose and benefits of web services.
  • Know the difference between REST and SOAP.
  • Understand REST resources, URIs, and representations.
  • Learn the six REST architectural constraints.
  • Understand GET, POST, PUT, PATCH, and DELETE.
  • Recognize common HTTP status codes.
  • Understand request headers, response headers, and JSON payloads.
  • Know the main Spring REST annotations.
  • Practice implementing CRUD endpoints in Spring Boot.
  • Test APIs with Postman, curl, and automated tests.
  • Apply validation, authentication, authorization, and error handling.
  • Follow resource naming and API documentation best practices.

21. Conclusion

Web services allow applications to exchange data and functionality through standardized interfaces. REST architecture provides a resource-oriented approach to designing distributed systems, commonly using HTTP methods, URIs, and representations such as JSON.

For Java developers, Spring Boot simplifies REST API development through annotations, request mapping, object serialization, and integration with other application components. By understanding REST principles, HTTP semantics, API security, testing, and error handling, developers can create services that are easier to maintain, integrate, and scale.


Learn Advanced Java with JustAcademy

Continue learning Java, Spring Boot, REST API development, and backend application development with JustAcademy.

Explore Advanced Java Training

Register for a Course Demo

Visit JustAcademy Official Website

Previous Next
whatsapp