Skip to content
VirtualLP Virtual Learning Platform

Practical 3: RESTful Web Service with CRUD APIs

15 min read Topic 27 of 34 1 hands-on lab

Aim

Build a Student REST (Representational State Transfer) API (Application Programming Interface) with Java and JAX-RS (Java API for RESTful Web Services). Add, read, change and delete student records. These four actions are called CRUD (Create, Read, Update and Delete). Test each action with Postman and cURL. Check the reply data and status code.

Theory

A REST API gives each resource, such as a student record, an address. A client sends an HTTP (Hypertext Transfer Protocol) request to that address. The HTTP method tells the service what action to take.

This example uses JSON (JavaScript Object Notation), a text format for data. A status code is a number in the reply that tells you whether the request worked. Each request must carry the information needed to process it. This is called stateless communication.

class register

The register is the resource /students. You add a new student's name (POST), read the whole list or one name (GET), correct a student's details (PUT) and strike off a student who left (DELETE).

flowchart LR
    C[Client: Postman / cURL] -->|"POST /students {json}"| R[StudentResource]
    C -->|"GET /students, GET /students/1"| R
    C -->|"PUT /students/1 {json}"| R
    C -->|"DELETE /students/1"| R
    R --> M[("Map<Integer, Student>")]
Operation HTTP method & URI (Uniform Resource Identifier) Success status Error statuses
Create POST /students 201 Created + the new student 400 wrong data, 415 wrong content type
Read all GET /students 200 OK – a JSON list –
Read one GET /students/{id} 200 OK 404 Not Found
Update PUT /students/{id} 200 OK 404
Delete DELETE /students/{id} 204 No Content 404

JAX-RS annotations

Annotation Purpose
@ApplicationPath("/api") The base path for all resources
@Path("/students"), @Path("/{id}") The URI of the resource and of one item
@GET @POST @PUT @DELETE Connect each HTTP method to a Java method
@PathParam("id") Takes the {id} part of the URL (Uniform Resource Locator) and passes it to the method
@Produces / @Consumes(MediaType.APPLICATION_JSON) JSON in and out (Jackson converts Java objects ⇄ JSON automatically)
Response.status(…).entity(…).build() Lets you choose the exact status code and body
Key point

Idempotent means repeating an identical request has the same intended effect: GET, PUT and DELETE have this property. The reply can differ on a repeat. POST is not guaranteed to be idempotent; in this example it creates a new student. Use the right status codes: 201 for create, 204 for delete, 404 for a missing resource, 400 for wrong input.

Requirements

JDK (Java Development Kit) 21, Eclipse IDE (Integrated Development Environment) for Enterprise Java, Tomcat 10.1 with Jersey 3 (JAX-RS) and Jackson, an HTTP client (Postman) and cURL.

The resource code below needs a Student data class, an application class and Jersey/Jackson dependencies. Keep the jakarta.ws.rs.* imports consistent with Jersey 3. This example stores records in memory; restarting the app clears them.

Program – StudentResource.java

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

    private static final Map<Integer, Student> store = new HashMap<>();
    private static int nextId = 1;

    @GET
    public List<Student> getAll() {
        return new ArrayList<>(store.values());
    }

    @GET
    @Path("/{id}")
    public Response getOne(@PathParam("id") int id) {
        Student s = store.get(id);
        if (s == null) {
            return Response.status(Response.Status.NOT_FOUND).entity("{\"error\":\"Student not found\"}").build();
        }
        return Response.ok(s).build();
    }

    @POST
    public Response create(Student s) {
        if (s.getName() == null || s.getName().isBlank()) {
            return Response.status(Response.Status.BAD_REQUEST).entity("{\"error\":\"name is required\"}").build();
        }
        s.setId(nextId++);
        store.put(s.getId(), s);
        return Response.status(Response.Status.CREATED).entity(s).build();
    }

    @PUT
    @Path("/{id}")
    public Response update(@PathParam("id") int id, Student s) {
        if (!store.containsKey(id)) return Response.status(404).build();
        s.setId(id);
        store.put(id, s);
        return Response.ok(s).build();
    }

    @DELETE
    @Path("/{id}")
    public Response delete(@PathParam("id") int id) {
        if (store.remove(id) == null) return Response.status(404).build();
        return Response.noContent().build();
    }
}

What each method does:

  • store – a simple in-memory "database" (a map from ID to Student); nextId gives each new student the next number.
  • getAll – GET /students returns everyone.
  • getOne – GET /students/1 returns student 1, or 404 with an error message if there is no such student.
  • create – POST /students first checks that a name was given (else 400), then gives the student an ID, saves it and returns 201.
  • update – PUT /students/1 replaces student 1 (or 404 if not found).
  • delete – DELETE /students/1 removes student 1 and returns 204 (or 404).

Student is a simple Java class (POJO (Plain Old Java Object)) with id, name, email, course, getters/setters and an empty constructor. RestApplication has @ApplicationPath("/api").

Procedure

  1. Create the three classes (StudentResource, Student, RestApplication) in a Dynamic Web Project.

  2. Right-click → Run As → Run on Server.

  3. The base URL is http://localhost:8080/studentapi/api/students.

  4. In the HTTP client, test each request in this order and check the status code:

    1. POST a student with a name → 201
    2. POST a student without a name → 400
    3. GET all students → 200
    4. GET /1 → 200
    5. PUT /1 with a changed course → 200
    6. DELETE /1 → 204
    7. GET /1 again → 404
  5. Repeat with cURL:

    curl -i -X POST http://localhost:8080/studentapi/api/students \
      -H "Content-Type: application/json" \
      -d '{"name":"Ravi","email":"ravi@example.com","course":"IT"}'
    curl -i http://localhost:8080/studentapi/api/students
    

    (-i shows the status line, -X POST chooses the method, -H sets the JSON header, -d sends the body.)

Virtual lab · Web Services · 40 min

Practical 3: RESTful CRUD service with JAX-RS

Complete a Jersey (JAX-RS) Student API with GET, POST, PUT and DELETE, JSON payloads, validation and correct HTTP status codes, then test every endpoint Postman-style and with curl.

Open lab

Output / Observations – endpoint documentation

Example output for the settings in this lesson:

Request Sample body Response
POST /students {"name":"Asha Rao","email":"asha@example.com","course":"Cloud Computing"} 201 {"id":1,"name":"Asha Rao",…}
POST /students {"email":"x@example.com"} 400 {"error":"name is required"}
GET /students/1 – 200 – the student's JSON
PUT /students/1 the full JSON with a new course 200 – the updated JSON
DELETE /students/1 – 204 (empty)
GET /students/1 – 404 {"error":"Student not found"}

Conclusion

Check the results: create 201, read 200, delete 204, missing record 404, and missing name 400.

Viva questions

  1. Which HTTP methods are idempotent? GET, PUT, DELETE and safe methods such as HEAD/OPTIONS. POST is not guaranteed to be idempotent.
  2. What does @PathParam do? It takes a value from the URI (like {id}) and passes it to the method parameter.
  3. Why return 201 for POST? It tells the client that a new resource was created.
  4. What is the difference between PUT and PATCH? PUT replaces the whole resource; PATCH changes only part of it.
  5. What converts the Student object to JSON? A JSON provider such as Jackson, used because of @Produces(APPLICATION_JSON).
  6. Compare REST and SOAP (originally Simple Object Access Protocol). REST: resources + HTTP methods, light JSON, no formal contract needed; SOAP: named operations, XML (Extensible Markup Language) envelopes, WSDL (Web Services Description Language) contract, WS- standards.*

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.