Skip to content
VirtualLP Virtual Learning Platform

REST, HTTP Methods and JAX-RS

16 min read Topic 6 of 34 1 hands-on lab

An app may ask a service to show a student record or save a new one. It sends an HTTP (Hypertext Transfer Protocol) request to a web address and receives a reply.

REST (Representational State Transfer) gives rules for designing services around resources, such as student records. JAX-RS (Java API for RESTful Web Services) helps you build these services in Java. You will learn the request methods, addresses and reply codes.

library

Every book in a library has a shelf number (that is a URI (Uniform Resource Identifier), like /books/101). You can look at a book (GET), donate a new book (POST), replace a damaged copy (PUT), correct one page (PATCH) or remove it (DELETE). REST works exactly like this: things have addresses, and a small set of standard actions is used on them.

REST

REST (Representational State Transfer) is a set of design principles for services. It describes resources and how clients interact with them. Web APIs (Application Programming Interfaces) apply these ideas using HTTP. A service that follows the REST rules is called RESTful.

Core concepts

Concept Meaning Example
Resource Any named "thing" the API offers a student, an order, a virtual machine
URI The unique address of a resource /api/students/101
Representation The format in which the resource is sent JSON (JavaScript Object Notation), XML (Extensible Markup Language), HTML (Hypertext Markup Language)
HTTP method The action to perform GET, POST, PUT, DELETE
State transfer The client changes a resource by sending a new representation PUT a new JSON body

The six REST constraints

  1. Client–server – the screen (client) and the data storage (server) are kept separate, so each can change on its own. Like a restaurant: the dining hall and the kitchen are separate.
  2. Stateless – every request carries all the information needed; the server does not remember previous requests (no session stored on the server). Login proof such as a JWT (JSON Web Token) token is sent with each request. Like showing your ticket at every gate instead of the guard remembering your face.
  3. Cacheable – responses say whether they may be saved and reused (Cache-Control, ETag). Like keeping a printed timetable instead of asking every time.
  4. Uniform interface – every resource is used the same way: identified by URIs, changed through representations, messages describe themselves, and HATEOAS (Hypermedia As The Engine Of Application State) – responses include links to related actions, like "next page" links on a website.
  5. Layered system – the client cannot tell if it is talking to the server directly or through load balancers, caches and gateways.
  6. Code on demand (optional) – the server may send code (JavaScript) for the client to run.
Remember “

Client Stateless Cache Uniform Layered Code” Statelessness is asked most often. It is what lets a cloud add or remove servers behind a load balancer freely – because any server can handle any request, since no server remembers anything special about you.

HTTP methods

Method Purpose Request body Safe Idempotent Typical response
GET Read a resource or a list No ✔ ✔ 200 OK
POST Create a new resource / start some processing Yes ✘ ✘ 201 Created + Location header
PUT Replace a resource completely (or create it at a known URI) Yes ✘ ✔ 200 OK / 204 No Content
PATCH Change part of a resource Yes ✘ ✘* 200 OK
DELETE Remove a resource Optional ✘ ✔ 204 No Content
HEAD Like GET, but only the headers, no body No ✔ ✔ 200 OK
OPTIONS Ask which methods are allowed (used in CORS (Cross-Origin Resource Sharing) pre-flight checks by browsers) No ✔ ✔ 204 + Allow header
  • Safe – the client does not ask to change resource state. The server may still record logs or usage.
  • Idempotent – repeating an identical request has the same intended effect as sending it once. Replies may differ: a second DELETE may return 404 because the first already removed the record. POST and PATCH are not guaranteed to be idempotent.

Designing resource URIs

Action Method + URI
List all students GET /api/students
Filter / show page 2 GET /api/students?course=cloud&page=2
Get one student GET /api/students/101
Create a student POST /api/students
Replace a student PUT /api/students/101
Update only the phone number PATCH /api/students/101
Delete a student DELETE /api/students/101
Marks of a student GET /api/students/101/marks

Good URI rules:

  • use nouns, not verbs – /students, not /getStudents (the HTTP method is already the verb),
  • use plural names for collections,
  • use lowercase with hyphens,
  • add a version, for example /api/v1/.

HTTP status codes

The first digit tells you the type of result:

Class Codes Meaning
2xx Success 200 OK · 201 Created · 202 Accepted · 204 No Content It worked
3xx Redirection 301 Moved Permanently · 304 Not Modified Go somewhere else / use your saved copy
4xx Client error 400 Bad Request · 401 Unauthorized (not logged in) · 403 Forbidden (logged in but not allowed) · 404 Not Found · 405 Method Not Allowed · 409 Conflict · 422 Unprocessable · 429 Too Many Requests You (the client) did something wrong
5xx Server error 500 Internal Server Error · 502 Bad Gateway · 503 Service Unavailable · 504 Gateway Timeout The server failed
Remember this

4xx means the server cannot fulfil the request as sent. 5xx means a server-side failure. Read the error details: a 500 response does not always mean the whole server crashed.

A complete request and response

The client creates a student:

POST /api/students HTTP/1.1
Host: api.virtuallp.com
Content-Type: application/json
Accept: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...

{ "rollNo": "101", "name": "Priya Sharma", "course": "Cloud Computing" }

The server replies 201 Created, gives the new address in Location, and includes HATEOAS links:

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

{ "rollNo": "101", "name": "Priya Sharma", "course": "Cloud Computing",
  "links": [ { "rel": "self", "href": "/api/students/101" },
             { "rel": "marks", "href": "/api/students/101/marks" } ] }

SOAP vs REST

SOAP means Simple Object Access Protocol.

Basis SOAP REST
Type Protocol (strict rules) Architectural style (design guidelines)
Message format XML only (inside an Envelope) JSON, XML, HTML, plain text
Transport HTTP, SMTP, JMS… HTTP
Interface description WSDL (Web Services Description Language) (required) OpenAPI/Swagger (optional), WADL
Operations Named operations (getStudent) HTTP methods on resources
State Can remember state Stateless
Caching Not possible (always POST) Uses normal HTTP caching
Security WS-Security (inside the message) HTTPS (Hypertext Transfer Protocol Secure) + OAuth 2.0 / JWT (on the connection)
Performance Heavier Lightweight, faster
Best for Company-to-company integrations needing strict contracts and transactions Web, mobile, cloud and public APIs
Java API JAX-WS (Java API for XML Web Services) JAX-RS

JAX-RS – RESTful services in Java

JAX-RS

JAX-RS (Java API for RESTful Web Services) defines how to build REST services in Java. Labels such as @Path and @GET link HTTP requests to Java methods. Jersey, RESTEasy and Apache CXF implement it.

Key annotations

Annotation Purpose
@Path("/students") The URI path of a class or method; can have placeholders like {id}
@GET, @POST, @PUT, @DELETE, @PATCH, @HEAD, @OPTIONS Which HTTP method the Java method handles
@Produces(MediaType.APPLICATION_JSON) The format of the response (for example JSON)
@Consumes(MediaType.APPLICATION_JSON) The format of the request body it accepts
@PathParam("id") Gives you the value from the URI placeholder (/students/101 → 101)
@QueryParam("page") Gives you a value from the query string (?page=2 → 2)
@FormParam, @HeaderParam, @CookieParam Give you form fields, headers, cookies
@DefaultValue("1") A default when a parameter is missing
@ApplicationPath("/api") The base path of the whole application

Example: a Student resource

package com.virtuallp.rest;

import jakarta.ws.rs.*;
import jakarta.ws.rs.core.*;
import java.net.URI;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

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

    private static final Map<String, Student> DB = new ConcurrentHashMap<>();

    @GET
    public Collection<Student> list(@QueryParam("course") String course) {
        return course == null ? DB.values()
             : DB.values().stream().filter(s -> course.equals(s.getCourse())).toList();
    }

    @GET
    @Path("/{rollNo}")
    public Response get(@PathParam("rollNo") String rollNo) {
        Student s = DB.get(rollNo);
        return s == null ? Response.status(Response.Status.NOT_FOUND).build()
                         : Response.ok(s).build();
    }

    @POST
    public Response create(Student s, @Context UriInfo uri) {
        if (DB.containsKey(s.getRollNo())) {
            return Response.status(Response.Status.CONFLICT).build();   // 409
        }
        DB.put(s.getRollNo(), s);
        URI location = uri.getAbsolutePathBuilder().path(s.getRollNo()).build();
        return Response.created(location).entity(s).build();          // 201
    }

    @PUT
    @Path("/{rollNo}")
    public Response replace(@PathParam("rollNo") String rollNo, Student s) {
        s.setRollNo(rollNo);
        DB.put(rollNo, s);
        return Response.ok(s).build();
    }

    @DELETE
    @Path("/{rollNo}")
    public Response delete(@PathParam("rollNo") String rollNo) {
        return DB.remove(rollNo) == null ? Response.status(404).build()
                                         : Response.noContent().build(); // 204
    }
}

What each method does:

  • list – GET /students (optionally ?course=…) returns all students.
  • get – GET /students/101 returns one student, or 404 if not found.
  • create – POST /students adds a student and returns 201 with its address; 409 if the roll number already exists.
  • replace – PUT /students/101 replaces the student.
  • delete – DELETE /students/101 removes it and returns 204, or 404 if it was not there.
@ApplicationPath("/api")
public class RestApplication extends jakarta.ws.rs.core.Application { }

Deployed on Tomcat or GlassFish with Jersey, the resource is available at http://localhost:8080/app/api/students.

Testing with curl

curl is a command-line tool that sends HTTP requests:

curl -X POST http://localhost:8080/app/api/students \
     -H "Content-Type: application/json" \
     -d '{"rollNo":"101","name":"Priya","course":"Cloud Computing"}' -i

curl http://localhost:8080/app/api/students/101
curl -X DELETE http://localhost:8080/app/api/students/101 -i

(-X chooses the method, -H adds a header, -d sends a body, -i shows the status line and headers.)

JAX-RS client API

You can also call a REST service from Java code:

Client client = ClientBuilder.newClient();
Student s = client.target("http://localhost:8080/app/api")
                  .path("students/{id}").resolveTemplate("id", "101")
                  .request(MediaType.APPLICATION_JSON)
                  .get(Student.class);

Virtual lab · Web Services · 30 min

Call a SOAP service and a REST API from a client

Import the TemperatureService WSDL into SoapUI, send a SOAP envelope and provoke a SOAP Fault, then use Postman to perform full CRUD on the Students REST API and compare status codes, headers and payloads.

Open lab
In the real world

When you run aws ec2 describe-instances, the AWS (Amazon Web Services) CLI (Command-Line Interface) signs and sends an HTTPS request to https://ec2.ap-south-1.amazonaws.com/. OpenStack's Nova API is pure REST: GET /v2.1/servers, POST /v2.1/servers, DELETE /v2.1/servers/{id}. Cloud consoles are just friendly screens on top of these APIs.

Summary

  • REST is a design style built on resources, URIs, representations and HTTP methods.
  • Six constraints: client-server, stateless, cacheable, uniform interface (including HATEOAS), layered system, code-on-demand (optional).
  • GET/HEAD/OPTIONS are safe; GET/PUT/DELETE are idempotent; POST is neither.
  • Status codes: 2xx success, 3xx redirect, 4xx client error, 5xx server error.
  • JAX-RS maps classes and methods to resources with @Path, @GET, @POST, @PathParam, @Produces, @Consumes.

Practice questions

  1. What is REST? Explain its architectural constraints.
  2. Explain the HTTP methods used in RESTful services. Which are safe and which are idempotent?
  3. Differentiate between SOAP and REST (any eight points).
  4. List common HTTP status codes used in REST APIs with meanings.
  5. Explain JAX-RS annotations with an example resource class.
  6. Design RESTful URIs for a library system (books, members, loans).
  7. What is HATEOAS? Give an example response.

Practise this topic

Hands-on virtual lab

Apply what you just read in a realistic, guided simulation. Free with a verified account.

Create a free account to track your progress and unlock virtual labs.