📖 2413MJCT302 • Unit VI • 10 Hrs

Unit VI - The REST Architectural style

Comprehensive University Exam Preparation Notes, Model Question Answers & Comparison Matrices

🔍
📑 Quick Jump Navigation

📌 Syllabus Topics Covered

10 Hrs Weightage

📖 Comprehensive Theoretical Notes

Exam-Oriented Theory

6.1 & 6.2 HTTP Fundamentals & Architectural Constraints of REST

REST (Representational State Transfer) is an architectural style formulated by Roy Fielding (2000) for distributed hypermedia systems. It treats every component as a Resource identified by a uniform URI and manipulated via standard HTTP verbs.

Six Guiding Architectural Constraints of REST:

  • 1. Client-Server Separation: Decouples user interface concerns from data storage concerns, improving portability and scalability.
  • 2. Statelessness: Every request from client to server must contain all information necessary to understand and process the request; server stores no client session context.
  • 3. Cacheability: Responses must explicitly define themselves as cacheable or non-cacheable (via Cache-Control, ETag) to reduce network latency.
  • 4. Uniform Interface: The cornerstone constraint consisting of: Resource identification in requests (URIs), Resource manipulation through representations (JSON/XML), Self-descriptive messages (MIME types), and HATEOAS (Hypermedia as the Engine of Application State).
  • 5. Layered System: Architecture allows intermediaries (proxies, load balancers, API gateways, security firewalls) without client awareness.
  • 6. Code-on-Demand (Optional): Servers can extend client functionality by transmitting executable code (e.g., JavaScript).

6.4 - 6.6 Building RESTful Web Services in Java (JAX-RS & JSON Frameworks)

JAX-RS (Java API for RESTful Web Services) Annotations:

  • @Path("/employees"): Defines the relative URI path for a resource class or method.
  • @GET, @POST, @PUT, @DELETE, @PATCH: Maps HTTP methods to Java methods.
  • @Produces(MediaType.APPLICATION_JSON): Specifies the response MIME media type returned.
  • @Consumes(MediaType.APPLICATION_JSON): Specifies the incoming request body payload format accepted.
  • @PathParam("id"): Binds a URI path parameter (e.g., /employees/{id}) to a method variable.
  • @QueryParam("dept"): Binds URL query string parameters (e.g., /employees?dept=IT).
  • @HeaderParam & @CookieParam: Extract HTTP headers and cookies.

JSON Processing Frameworks: Jackson (ObjectMapper), Google Gson, JSON-B (Java API for JSON Binding) for high-speed serialization and deserialization.

6.7 - 6.9 API Description, Design Best Practices, and Security

REST Description: Documented using OpenAPI Specification (OAS / Swagger) and legacy WADL (Web Application Description Language).

RESTful Design Guidelines:

  • Use nouns for URIs, never verbs (e.g., GET /api/v1/orders, NOT /api/v1/getOrders).
  • Use plural nouns for collections (/users, /products).
  • Maintain correct HTTP status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Error.
  • Ensure Idempotency: GET, PUT, and DELETE are idempotent; POST is non-idempotent.

Security Mechanisms: Transport Layer Security (HTTPS/TLS 1.3), OAuth 2.0 & OpenID Connect for delegated token authorization, JSON Web Tokens (JWT) for stateless bearer authentication, API Key rate limiting, and CORS headers.

🔑 Key Concepts & Examination Keywords

Quick Terminology
Resource & URI
Any conceptual entity exposed by a RESTful system identified by a unique Uniform Resource Identifier.
HATEOAS
Hypermedia As The Engine Of Application State; clients dynamically navigate resources via hypermedia links embedded in responses.
Idempotency
Property where executing an HTTP method multiple identical times produces the exact same server resource state (GET, PUT, DELETE).
JSON Web Token (JWT)
A compact, URL-safe means of representing signed claims between two parties for stateless REST authentication.

🎯 High-Yield Important Examination Questions

8–10 Descriptive Points Each

Q1. Explain the 6 core architectural constraints of REST formulated by Roy Fielding and discuss how they ensure web scalability.

10 MarksREST Architectural ConstraintsCore
📝 Detailed Examination Answer (10-Point Model):
  1. Origins of REST Architecture: Formulated by Roy Fielding in his 2000 doctoral dissertation, REST is an architectural style governing distributed hypermedia systems over HTTP.
  2. Constraint 1: Client-Server Architecture: Separates user interface concerns on clients from data storage and business logic on servers, enabling independent evolution of mobile/web clients.
  3. Constraint 2: Statelessness: Every HTTP request must contain all authentication credentials and context necessary for execution; server holds no session state between calls, enabling effortless horizontal scaling.
  4. Constraint 3: Cacheability: Responses must explicitly declare caching directives (`Cache-Control`, `max-age`, `ETag`) allowing clients and intermediate proxies to cache responses, drastically reducing latency.
  5. Constraint 4: Uniform Interface: Provides a standard contract across all resources consisting of 4 sub-principles: resource identification (URIs), manipulation via representations, self-describing messages, and HATEOAS.
  6. Constraint 5: Layered System: Allows intermediate architectural tiers (load balancers, reverse proxies, API gateways, CDNs) to intercept traffic without client knowledge, enhancing security and caching.
  7. Constraint 6: Code on Demand (Optional): Servers can temporarily extend client functionality by transmitting executable scripts (e.g., JavaScript applets), the only optional constraint.
  8. Scalability and Fault Tolerance: Statelessness combined with standard caching allows RESTful systems to serve billions of requests across globally distributed CDNs.
  9. Simplicity Over Protocols: Leverages existing HTTP infrastructure rather than introducing heavy transport wrapper protocols like SOAP envelopes.
  10. Ubiquitous Adoption in Modern Web: Forms the dominant architecture for public web APIs, microservice ecosystems, and cloud-native mobile backends.

Q2. Explain how to design, develop, and annotate a complete CRUD RESTful Web Service in Java using JAX-RS and Jackson JSON parser.

10 MarksJAX-RS Java Implementation
📝 Detailed Examination Answer (10-Point Model):
  1. Resource Class Architecture (@Path): Annotate root Java class with `@Path('/api/v1/products')` and `@Produces(MediaType.APPLICATION_JSON)` to define the base URI and default media representation.
  2. CREATE Operation (@POST): Implement `@POST` method accepting JSON entity body, persisting data, and returning HTTP `201 Created` with a `Location` header pointing to new resource.
  3. READ Collection Operation (@GET): Implement `@GET` method returning complete list of products with optional query filtering via `@QueryParam('category')` and pagination parameters.
  4. READ Single Resource (@GET with @PathParam): Implement `@GET @Path('/{id}')` method extracting path variable via `@PathParam('id') int id`, returning `200 OK` or `404 Not Found` if missing.
  5. UPDATE Full Resource (@PUT): Implement `@PUT @Path('/{id}')` method replacing the entire product resource idempotently, returning `200 OK` or `204 No Content`.
  6. PARTIAL UPDATE (@PATCH): Implement `@PATCH @Path('/{id}')` method updating specific fields (e.g., price only) without requiring the entire product payload.
  7. DELETE Operation (@DELETE): Implement `@DELETE @Path('/{id}')` method removing resource and returning `204 No Content` (or `200 OK`), ensuring idempotent behavior.
  8. Jackson JSON Serialization Integration: Jackson's `ObjectMapper` automatically marshals Java POJOs into JSON strings and deserializes incoming JSON payloads into strongly-typed Java objects.
  9. Exception Mapping via ExceptionMapper<T>: Implement custom `ExceptionMapper` classes to catch unchecked Java exceptions and convert them into standardized JSON error responses with proper HTTP status codes.
  10. Response Builder & Status Codes: Use `Response.status(Response.Status.CREATED).entity(product).build()` to control HTTP response codes and headers cleanly.

Q3. Discuss RESTful Web Service security: explain HTTPS/TLS, OAuth 2.0 authorization framework, JWT tokens, API Keys, and CORS protection.

10 MarksREST Security
📝 Detailed Examination Answer (10-Point Model):
  1. Transport Layer Security (HTTPS / TLS 1.3): Mandatory foundation for all REST APIs, encrypting request/response payloads, headers, and URI parameters against packet sniffing and Man-in-the-Middle (MitM) attacks.
  2. OAuth 2.0 Delegated Authorization Framework: Industry standard allowing third-party applications to access server resources on behalf of a user without exposing user passwords (using Authorization Code, Client Credentials grants).
  3. JSON Web Token (JWT) Architecture: A compact, cryptographically signed token containing Header (algorithm), Payload (claims/user ID/roles), and Signature (`HMAC-SHA256` or `RSA-256`).
  4. Stateless Bearer Authentication via JWT: Clients pass tokens in HTTP `Authorization: Bearer ` header; servers verify signature mathematically without querying session databases.
  5. API Key Authentication & Limitations: Transmits static unique keys in headers (e.g., `X-API-Key`) for client identification and rate limiting, but unsuitable for user-level delegated authorization.
  6. Cross-Origin Resource Sharing (CORS): Browser security mechanism where servers declare allowed client domains via `Access-Control-Allow-Origin` and handle HTTP `OPTIONS` preflight checks.
  7. Rate Limiting & Throttling: Protects endpoints against Denial of Service (DoS) and brute-force attacks using Token Bucket / Leaky Bucket algorithms returning `429 Too Many Requests`.
  8. Input Validation & Content Security: Strictly validate payload schemas and sanitize inputs to prevent SQL Injection, NoSQL Injection, and Cross-Site Scripting (XSS).
  9. Sensitive Data Exposure in URIs: Never place sensitive credentials or passwords in URL query parameters, as URLs are logged in plain text in browser histories, proxy caches, and server access logs.
  10. Role-Based Access Control (RBAC) in JAX-RS: Enforce endpoint authorization using security annotations like `@RolesAllowed('ADMIN')` to restrict privileged endpoints.

⚖️ Comprehensive Comparison & Difference Tables

8+ Comparison Criteria

📊 SOAP Web Services vs RESTful Web Services

Comparison ParameterSOAP Web ServicesRESTful Web Services
Architectural ParadigmStrict protocol specification with rigid XML standards.Lightweight architectural style based on HTTP principles.
Data Payload FormatsExclusively XML (strict SOAP envelope format).Polyglot: JSON (predominant), XML, YAML, Plain Text, HTML.
Transport ProtocolTransport agnostic (HTTP, HTTPS, SMTP, JMS, TCP).Tightly bound to HTTP / HTTPS.
Interface ContractStrict contract defined via machine-readable WSDL.Described via OpenAPI / Swagger or self-descriptive HATEOAS.
Message Footprint & OverheadHeavy footprint due to XML tags and envelope nesting.Lightweight payload footprint; compact JSON consumes less bandwidth.
Caching CapabilityCannot be cached by standard HTTP caches (uses POST).Highly cacheable; fully utilizes HTTP caching headers (`Cache-Control`, `ETag`).
Security StandardsWS-Security (message-level encryption and digital signatures).HTTPS/TLS (transport level), OAuth 2.0, JWT, and API Keys.
Error HandlingStandardized XML `` structure.Standard HTTP response status codes (404, 401, 500) + custom JSON.
Performance & LatencyLower performance due to heavy XML DOM parsing.High performance; fast JSON serialization and low network latency.
Ideal Application DomainEnterprise banking, financial transactions, legacy B2B.Modern web apps, mobile backends, public APIs, cloud microservices.

📊 XML vs JSON Data Interchange Formats

Comparison ParameterXML (Extensible Markup Language)JSON (JavaScript Object Notation)
Syntax StructureTag-based markup syntax (`Value`).Key-Value pairs and array data structures (`{"name": "Value"}`).
Verbosity & Payload SizeHigh verbosity with repetitive closing tags; larger payload.Compact and concise; significantly smaller payload size.
Parsing Speed in BrowsersSlower; requires XML DOM Parser or SAX parser.Native JavaScript parsing via ultra-fast `JSON.parse()`.
Data Typing SupportAll content is text; requires XSD for data typing.Native primitive data types (String, Number, Boolean, Array, Object, Null).
Schema ValidationExtremely rich schema validation (XML Schema / XSD, DTD).JSON Schema exists but is less formally integrated into early standards.
Namespaces SupportRobust support for XML Namespaces to avoid tag collisions.No native namespace support.
Human ReadabilityModerate readability; cluttered by extensive nested tags.High readability; clean, clean, and intuitive object notation.
Tooling EcosystemXPath, XSLT transformations, XQuery.JSONPath, jq, Jackson, Gson, native browser engines.

⚡ Quick Pre-Exam Revision Summary

5-Minute Recap
💡 Core Takeaways & High-Yield Summary
  • REST is an architectural style based on 6 constraints: Client-Server, Stateless, Cacheable, Uniform Interface, Layered, Code-on-Demand.
  • HTTP methods: GET (read), POST (create), PUT (replace), PATCH (partial update), DELETE (remove).
  • GET, PUT, DELETE are Idempotent; POST is non-idempotent.
  • JAX-RS annotations: `@Path`, `@GET`, `@POST`, `@PUT`, `@DELETE`, `@Produces`, `@Consumes`, `@PathParam`, `@QueryParam`.
  • REST security: HTTPS/TLS, OAuth 2.0, JWT Bearer tokens, API Keys, and CORS headers.
  • REST APIs are documented using OpenAPI / Swagger specifications.