Table of Contents

RESTful Web Services

Week 11 — COIT20259 Enterprise Computing
Jakarta EE & JAX-RS
1.1

1.1 What is REST?

REST (Representational State Transfer) is an architectural style for designing networked applications. It was introduced by Roy Fielding in his 2000 doctoral dissertation.

REST is not a protocol or a standard — it is a set of constraints that, when followed, produce scalable, simple, and maintainable web services.

Core idea: Everything is a resource identified by a URI. Clients interact with resources using standard HTTP methods.
Example — Resource URIs:

GET /api/students — list all students
GET /api/students/42 — get student with ID 42
POST /api/students — create a new student

1.2

1.2 The Six REST Constraints

#ConstraintWhat It Means
1Client–ServerUI and data storage are separated — they evolve independently
2StatelessEach request contains all the information the server needs — no session state stored on the server
3CacheableResponses declare whether they can be cached to improve performance
4Uniform InterfaceResources are identified by URIs; standard HTTP methods apply uniformly
5Layered SystemClient cannot tell if it is talking directly to the server or through a proxy/gateway
6Code on Demand (optional)Server can send executable code (e.g., JavaScript) to the client
Statelessness is the constraint students struggle with most. It means no HttpSession — every request is self-contained.
1.3

1.3 HTTP Methods & CRUD Mapping

REST maps standard HTTP methods to database-style CRUD operations on resources:

HTTP MethodCRUD OperationIdempotent?Example
GETReadYesGET /api/orders/7
POSTCreateNoPOST /api/orders
PUTUpdate (full)YesPUT /api/orders/7
DELETEDeleteYesDELETE /api/orders/7
PATCHUpdate (partial)No*PATCH /api/orders/7
Idempotent means calling the operation multiple times produces the same result as calling it once. GET, PUT, and DELETE are idempotent; POST is not (each call may create a new resource).
1.Q

Knowledge Check — REST Fundamentals

Q1: Which REST constraint requires that each request carry all information needed by the server?
Statelessness means no server-side session — every request must be self-contained with all context the server needs to process it.
Q2: You call POST /api/products three times with the same body. How many new products are likely created?
POST is not idempotent. Each call typically creates a new resource, so three calls produce three products.

Section 2

JAX-RS — Building RESTful Services in Jakarta EE
2.1

2.1 What is JAX-RS?

JAX-RS (Jakarta RESTful Web Services) is the Jakarta EE standard API for building RESTful web services in Java. The reference implementation is Jersey (bundled with GlassFish).

What JAX-RS gives you

  • Annotation-driven — minimal boilerplate
  • Automatic JSON/XML serialisation
  • Built-in parameter injection
  • Integrated with CDI, EJB, JPA

Package change (Java EE → Jakarta EE)

  • javax.ws.rsjakarta.ws.rs
  • Same API, new namespace
  • GlassFish 7 uses the Jakarta namespace
In COIT20259, we deploy JAX-RS resources on GlassFish 7. The server handles JSON binding automatically via JSON-B.
2.2

2.2 Key JAX-RS Annotations

AnnotationPurposeExample
@PathMaps a class or method to a URI path@Path("/students")
@GETHandles HTTP GET requestsRetrieve resource(s)
@POSTHandles HTTP POST requestsCreate a resource
@PUTHandles HTTP PUT requestsUpdate a resource
@DELETEHandles HTTP DELETE requestsDelete a resource
@ProducesSpecifies response media type@Produces("application/json")
@ConsumesSpecifies request media type@Consumes("application/json")
@PathParamExtracts a value from the URI@PathParam("id")
@QueryParamExtracts a query string parameter@QueryParam("page")
2.3

2.3 Building a Simple REST Resource

A complete JAX-RS resource class that returns a list of students as JSON:

@Path("/students")
@Produces(MediaType.APPLICATION_JSON)
public class StudentResource {

    @Inject
    private StudentService service;

    @GET                              // GET /api/students
    public List<Student> getAll() {
        return service.findAll();
    }

    @GET
    @Path("/{id}")                    // GET /api/students/42
    public Student getById(@PathParam("id") Long id) {
        return service.find(id);
    }

    @POST                             // POST /api/students
    @Consumes(MediaType.APPLICATION_JSON)
    public Response create(Student s) {
        service.save(s);
        return Response.status(201).entity(s).build();
    }
}
Notice: no manual JSON parsing. JSON-B automatically converts Java objects to/from JSON.
2.4

2.4 Path Parameters vs. Query Parameters

Path Parameters

Used to identify a specific resource.

// URL: /api/students/42
@GET
@Path("/{id}")
public Student get(
    @PathParam("id") Long id
) { ... }

The {id} in the path is mandatory — the URL won't match without it.

Query Parameters

Used for optional filtering, sorting, pagination.

// URL: /api/students?major=IT&page=2
@GET
public List<Student> search(
    @QueryParam("major") String m,
    @QueryParam("page")
      @DefaultValue("1") int p
) { ... }

Query params are optional — the method still works if omitted.

Rule of thumb: if the parameter identifies which resource → path param. If it filters or modifies the response → query param.
2.Q

Knowledge Check — JAX-RS

Q3: Which annotation maps a Java class to the URI path /api/orders?
@Path maps classes and methods to URI paths. @RequestMapping is a Spring annotation — not Jakarta EE.
Q4: A method is annotated with @GET @Path("/{id}"). What does @PathParam("id") do on the method parameter?
@PathParam binds the {id} template variable in the URI to the Java method parameter.

Section 3

Request & Response Handling
3.1

3.1 JSON, Media Types & Content Negotiation

JSON-B — automatic serialisation

Jakarta JSON Binding (JSON-B) converts Java objects to JSON and back with zero configuration:

// Java object
Student s = new Student();
s.setName("Alice");
s.setGpa(3.8);

// Becomes JSON automatically:
{
  "name": "Alice",
  "gpa": 3.8
}

Content Negotiation

The client tells the server what format it wants via the Accept header:

Accept: application/json
Accept: application/xml

The server responds in the matching format if supported.

@Produces on the resource class declares which media types it supports. In our course, we use JSON exclusively.
3.2

3.2 Response Object & HTTP Status Codes

The Response class gives you fine-grained control over what the server sends back:

@POST
public Response create(Student s) {
    service.save(s);
    URI uri = URI.create("/api/students/" + s.getId());
    return Response.created(uri)       // 201 Created
                   .entity(s)            // response body
                   .build();
}

@DELETE @Path("/{id}")
public Response delete(@PathParam("id") Long id) {
    service.remove(id);
    return Response.noContent().build(); // 204 No Content
}
CodeMeaningWhen to Use
200 OKRequest succeededGET, PUT success
201 CreatedNew resource createdPOST success
204 No ContentSuccess, no bodyDELETE success
400 Bad RequestInvalid inputValidation failure
404 Not FoundResource doesn't existID not in database
500 Internal ErrorServer-side failureUnhandled exception
3.3

3.3 Summary & Key Takeaways

Client (Browser / App) HTTP Request JAX-RS Resource @Path @GET @POST @Produces(JSON) @PathParam @QueryParam → Response + Status Code JPA / EJB Database (MySQL) JSON Response
Figure 3.1: RESTful request flow in a Jakarta EE application
What you should remember from this week:

1. REST is an architectural style — resources + URIs + HTTP methods
2. JAX-RS uses annotations (@Path, @GET, @POST, etc.) to build services with minimal code
3. JSON-B handles serialisation automatically — no manual parsing needed
4. Use the Response class to set proper HTTP status codes (201, 204, 404…)
5. Path params identify resources; query params filter or paginate