REST API in Java
A REST API in Java is a web service that exposes data as resources at URLs and lets clients read and change them with standard HTTP methods such as GET, POST, PUT, PATCH and DELETE. Mobile apps, single-page web apps and other servers all talk to back ends this way, usually exchanging JSON.
This lesson explains the REST rules and then builds a complete course API with plain servlets on Tomcat 11, so you can see every HTTP detail before frameworks hide it. It ends with a Java client that runs a full create-update-delete session against the API. The examples continue the student-portal app from Java Servlet Basics.
REST API Principles
REST (Representational State Transfer) is a set of design rules, not a library. An API that follows them is called RESTful.
| Principle | Meaning | Example |
|---|---|---|
| Resources | Every thing has its own URL | /api/courses/java |
| HTTP methods | The method says what to do | GET reads, DELETE removes |
| Representations | Clients get a copy of the resource in a format | JSON body |
| Stateless | Each request carries everything needed; no server memory of the client | Auth token in every request |
| Status codes | The result is in the HTTP status | 201 Created, 404 Not Found |
How it works:
- The URL names what, the method says how. That is why REST URLs contain nouns (
/courses), not verbs (/getCourses). - Statelessness lets you run many copies of the server behind a load balancer, since any copy can answer any request.
Design REST Resource URLs
Plan the endpoints before writing code. A collection URL and an item URL cover most needs.
| Method and URL | Action | Success status |
|---|---|---|
GET /api/courses | List courses (with filters) | 200 OK |
GET /api/courses/{code} | Read one course | 200 OK |
POST /api/courses | Create a course | 201 Created |
PUT /api/courses/{code} | Replace a course completely | 200 OK |
PATCH /api/courses/{code} | Change some fields | 200 OK |
DELETE /api/courses/{code} | Delete a course | 204 No Content |
| Avoid | Prefer |
|---|---|
/api/getAllCourses | GET /api/courses |
/api/deleteCourse?id=java | DELETE /api/courses/java |
/api/course/java/update | PUT /api/courses/java |
/api/courses?action=create | POST /api/courses |
How it works:
- Use plural nouns for collections and put the item key in the path.
- Use query parameters only for options on a collection, such as filters, sorting and paging:
/api/courses?maxFee=3000&page=2.
HTTP Methods: Safe and Idempotent
| Method | CRUD | Safe (no changes) | Idempotent (repeat = same result) | Servlet method |
|---|---|---|---|---|
GET | Read | Yes | Yes | doGet |
POST | Create | No | No | doPost |
PUT | Replace | No | Yes | doPut |
PATCH | Partial update | No | Not guaranteed | doPatch (Servlet 6.1) |
DELETE | Delete | No | Yes | doDelete |
How it works:
- Idempotent means sending the same request twice leaves the server in the same state. Clients and proxies may safely retry
PUTandDELETEafter a timeout, but notPOST, which could create a duplicate. - Before Servlet 6.1,
PATCHrequired overridingservice(). Tomcat 11 callsdoPatchdirectly.
Build the REST API: Setup and Shared Helpers
All the endpoints live in one servlet mapped to /api/courses/*. Courses are kept in a thread-safe map so the example runs without a database. In a real project this map becomes a JDBC or JPA repository.
package com.gocourse.portal;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@WebServlet("/api/courses/*")
public class CourseApiServlet extends HttpServlet {
public record Course(String code, String title, int lessons, int feeInr) {}
public record ApiError(int status, String error) {}
private static final Gson GSON = new Gson();
private final Map<String, Course> store = new ConcurrentHashMap<>();
@Override
public void init() {
store.put("java", new Course("java", "Java Programming", 306, 4999));
store.put("go", new Course("go", "Go Language", 120, 2999));
}
// Turn bad numbers and bad JSON anywhere into a 400 response
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
super.service(req, resp);
} catch (NumberFormatException | JsonParseException | IllegalStateException e) {
send(resp, 400, new ApiError(400, "Bad request: " + e.getMessage()));
}
}
// "/api/courses" -> null, "/api/courses/java" -> "java"
private static String codeFrom(HttpServletRequest req) {
String info = req.getPathInfo();
return (info == null || info.equals("/")) ? null : info.substring(1);
}
private static void send(HttpServletResponse resp, int status, Object body) throws IOException {
resp.setStatus(status);
resp.setContentType("application/json;charset=UTF-8");
resp.getWriter().write(GSON.toJson(body));
}
private static boolean isJson(HttpServletRequest req) {
return req.getContentType() != null && req.getContentType().startsWith("application/json");
}
// The handler methods from the next sections go here
}
How it works:
ConcurrentHashMapmatters because Tomcat calls one servlet instance from many threads at once.- Overriding
serviceand callingsuper.servicekeeps normal method dispatch, but catches parsing errors in one place and turns them into400JSON errors. - Every response goes through
send, so status, content type and JSON writing are always consistent. The response techniques are covered in HttpServletResponse in Java.
GET: Read a Collection and a Single Resource
GET without a code lists courses, with optional filtering and paging. GET with a code returns one course or 404.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String code = codeFrom(req);
if (code != null) { // GET /api/courses/{code}
Course course = store.get(code);
if (course == null) {
send(resp, 404, new ApiError(404, "Course " + code + " not found"));
} else {
send(resp, 200, course);
}
return;
}
// GET /api/courses?maxFee=&page=&size=
int maxFee = intParam(req, "maxFee", Integer.MAX_VALUE);
int page = intParam(req, "page", 1);
int size = intParam(req, "size", 10);
List<Course> matches = store.values().stream()
.filter(c -> c.feeInr() <= maxFee)
.sorted(Comparator.comparing(Course::code))
.toList();
List<Course> pageItems = matches.stream().skip((long) (page - 1) * size).limit(size).toList();
resp.setIntHeader("X-Total-Count", matches.size()); // total before paging
send(resp, 200, pageItems);
}
private static int intParam(HttpServletRequest req, String name, int defaultValue) {
String raw = req.getParameter(name);
if (raw == null) return defaultValue;
int value = Integer.parseInt(raw);
if (value < 1) throw new NumberFormatException(name + " must be at least 1");
return value;
}
API=http://localhost:8080/student-portal/api/courses
curl -s $API; echo
curl -s $API/java; echo
curl -s -D - "$API?size=1&page=2" | grep -E "X-Total|^\["; echo
curl -s -w " (%{http_code})\n" $API/php
curl -s -w " (%{http_code})\n" "$API?page=abc"
Output:
[{"code":"go","title":"Go Language","lessons":120,"feeInr":2999},{"code":"java","title":"Java Programming","lessons":306,"feeInr":4999}]
{"code":"java","title":"Java Programming","lessons":306,"feeInr":4999}
X-Total-Count: 2
[{"code":"java","title":"Java Programming","lessons":306,"feeInr":4999}]
{"status":404,"error":"Course php not found"} (404)
{"status":400,"error":"Bad request: For input string: \"abc\""} (400)
How it works:
- Sorting by code gives clients a stable order; a
ConcurrentHashMapalone has no predictable order. - Paging uses
skipandlimit, andX-Total-Counttells the client how many results exist in total, so it can draw page links. - The invalid
page=abcis caught by theserviceoverride and answered with400.
POST: Create a Resource
POST to the collection creates a new course. A successful create answers 201 Created, a Location header with the new URL, and the created resource.
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if (codeFrom(req) != null) {
send(resp, 405, new ApiError(405, "POST to /api/courses, not to a single course"));
return;
}
if (!isJson(req)) {
send(resp, 415, new ApiError(415, "Content-Type must be application/json"));
return;
}
Course course = GSON.fromJson(req.getReader(), Course.class);
String problem = validate(course);
if (problem != null) {
send(resp, 400, new ApiError(400, problem));
return;
}
if (store.putIfAbsent(course.code(), course) != null) { // atomic check-and-insert
send(resp, 409, new ApiError(409, "Course " + course.code() + " already exists"));
return;
}
resp.setHeader("Location", req.getRequestURL() + "/" + course.code());
send(resp, 201, course);
}
private static String validate(Course c) {
if (c == null) return "Request body is empty";
if (c.code() == null || !c.code().matches("[a-z]{2,20}")) return "code must be 2 to 20 lowercase letters";
if (c.title() == null || c.title().isBlank()) return "title is required";
if (c.lessons() < 1) return "lessons must be at least 1";
if (c.feeInr() < 0) return "feeInr cannot be negative";
return null;
}
curl -s -i -H "Content-Type: application/json" \
-d '{"code":"python","title":"Python Programming","lessons":180,"feeInr":3999}' $API \
| grep -E "^HTTP|^Location|^\{"
curl -s -w " (%{http_code})\n" -H "Content-Type: application/json" \
-d '{"code":"python","title":"Duplicate","lessons":1,"feeInr":0}' $API
curl -s -w " (%{http_code})\n" -H "Content-Type: application/json" -d '{"code":"C#","title":""}' $API
curl -s -w " (%{http_code})\n" -d "code=rust" $API
Output:
HTTP/1.1 201
Location: http://localhost:8080/student-portal/api/courses/python
{"code":"python","title":"Python Programming","lessons":180,"feeInr":3999}
{"status":409,"error":"Course python already exists"} (409)
{"status":400,"error":"code must be 2 to 20 lowercase letters"} (400)
{"status":415,"error":"Content-Type must be application/json"} (415)
How it works:
putIfAbsentchecks and inserts in one atomic step, so two clients creating the same code at the same moment cannot both succeed.409 Conflictsignals a duplicate,400signals invalid fields and415signals the wrong body format. Each tells the client exactly what to fix.- Gson maps the JSON fields onto the record components by name. Missing numbers become
0, which the validation then rejects.
PUT and PATCH: Update a Resource
PUT replaces the whole course with the body. PATCH changes only the fields that are present.
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String code = codeFrom(req);
if (code == null || !store.containsKey(code)) {
send(resp, 404, new ApiError(404, "Course " + code + " not found"));
return;
}
Course body = GSON.fromJson(req.getReader(), Course.class);
Course replacement = body == null ? null
: new Course(code, body.title(), body.lessons(), body.feeInr()); // the URL decides the code
String problem = validate(replacement);
if (problem != null) {
send(resp, 400, new ApiError(400, problem));
return;
}
store.put(code, replacement);
send(resp, 200, replacement);
}
@Override
protected void doPatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String code = codeFrom(req);
Course existing = code == null ? null : store.get(code);
if (existing == null) {
send(resp, 404, new ApiError(404, "Course " + code + " not found"));
return;
}
JsonObject changes = JsonParser.parseReader(req.getReader()).getAsJsonObject();
Course updated = new Course(code,
changes.has("title") ? changes.get("title").getAsString() : existing.title(),
changes.has("lessons") ? changes.get("lessons").getAsInt() : existing.lessons(),
changes.has("feeInr") ? changes.get("feeInr").getAsInt() : existing.feeInr());
String problem = validate(updated);
if (problem != null) {
send(resp, 400, new ApiError(400, problem));
return;
}
store.put(code, updated);
send(resp, 200, updated);
}
curl -s -X PATCH -H "Content-Type: application/json" -d '{"feeInr":3499}' $API/python; echo
curl -s -X PUT -H "Content-Type: application/json" \
-d '{"title":"Python for Data Science","lessons":200,"feeInr":4499}' $API/python; echo
curl -s -w " (%{http_code})\n" -X PATCH -H "Content-Type: application/json" -d '{"lessons":0}' $API/python
Output:
{"code":"python","title":"Python Programming","lessons":180,"feeInr":3499}
{"code":"python","title":"Python for Data Science","lessons":200,"feeInr":4499}
{"status":400,"error":"lessons must be at least 1"} (400)
How it works:
- The
PATCHbody names onlyfeeInr, so title and lessons keep their old values.JsonObject.hastells "field missing" apart from "field set". PUTtakes the code from the URL, never from the body, so a client cannot rename a course by accident.- Both methods run the same
validatemethod, so the rules stay identical for every write.
DELETE: Remove a Resource
@Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String code = codeFrom(req);
if (code == null || store.remove(code) == null) {
send(resp, 404, new ApiError(404, "Course " + code + " not found"));
return;
}
resp.setStatus(HttpServletResponse.SC_NO_CONTENT); // success, no body
}
curl -s -o /dev/null -w "%{http_code}\n" -X DELETE $API/python
curl -s -w " (%{http_code})\n" -X DELETE $API/python
Output:
204
{"status":404,"error":"Course python not found"} (404)
How it works:
204 No Contentmeans success with an empty body.- The second
DELETEreturns404, but the server state is the same after both calls: the course is gone. That is what makesDELETEidempotent.
REST API Status Codes Reference
| Code | Name | Send it when |
|---|---|---|
| 200 | OK | A read or update succeeded |
| 201 | Created | POST created a resource (add Location) |
| 204 | No Content | Success with no body, usually DELETE |
| 400 | Bad Request | Invalid JSON, fields or parameters |
| 401 | Unauthorized | No valid credentials |
| 403 | Forbidden | Credentials valid but not allowed |
| 404 | Not Found | The resource does not exist |
| 405 | Method Not Allowed | Method not supported on that URL |
| 409 | Conflict | Duplicate or conflicting state |
| 415 | Unsupported Media Type | Body is not in the expected format |
| 500 | Internal Server Error | An unexpected failure on the server |
Note: Never return
200with an error message inside the body. Clients, proxies and monitoring tools all rely on the status code to tell success from failure.
Real-World Example: Calling the REST API in Java With HttpClient
A course administration tool uses the API from Java. It creates a course, tries a duplicate, applies a discount with PATCH, replaces the details with PUT, lists cheap courses and deletes the course twice. It uses the built-in client from Java HttpClient. Restart Tomcat first so the API starts with only the java and go courses.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class CourseAdminClient {
private static final String BASE = "http://localhost:8080/student-portal/api/courses";
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
public static void main(String[] args) throws Exception {
call("POST", BASE, """
{"code":"docker","title":"Docker Essentials","lessons":40,"feeInr":1999}""");
call("POST", BASE, """
{"code":"docker","title":"Docker Again","lessons":40,"feeInr":1999}""");
call("PATCH", BASE + "/docker", """
{"feeInr":1499}""");
call("PUT", BASE + "/docker", """
{"title":"Docker for Developers","lessons":45,"feeInr":1499}""");
call("GET", BASE + "?maxFee=3000", null);
call("DELETE", BASE + "/docker", null);
call("DELETE", BASE + "/docker", null);
}
private static void call(String method, String url, String json) throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url))
.timeout(Duration.ofSeconds(10))
.header("Accept", "application/json");
if (json != null) {
builder.header("Content-Type", "application/json")
.method(method, HttpRequest.BodyPublishers.ofString(json));
} else {
builder.method(method, HttpRequest.BodyPublishers.noBody());
}
HttpResponse<String> response = CLIENT.send(builder.build(), HttpResponse.BodyHandlers.ofString());
String location = response.headers().firstValue("Location")
.map(value -> " [Location: " + value.replace(BASE, "/api/courses") + "]")
.orElse("");
System.out.printf("%s %s -> %d%s %s%n", method, url.replace(BASE, "/api/courses"),
response.statusCode(), location, response.body());
}
}
java CourseAdminClient.java
Output:
POST /api/courses -> 201 [Location: /api/courses/docker] {"code":"docker","title":"Docker Essentials","lessons":40,"feeInr":1999}
POST /api/courses -> 409 {"status":409,"error":"Course docker already exists"}
PATCH /api/courses/docker -> 200 {"code":"docker","title":"Docker Essentials","lessons":40,"feeInr":1499}
PUT /api/courses/docker -> 200 {"code":"docker","title":"Docker for Developers","lessons":45,"feeInr":1499}
GET /api/courses?maxFee=3000 -> 200 [{"code":"docker","title":"Docker for Developers","lessons":45,"feeInr":1499},{"code":"go","title":"Go Language","lessons":120,"feeInr":2999}]
DELETE /api/courses/docker -> 204
DELETE /api/courses/docker -> 404 {"status":404,"error":"Course docker not found"}
How it works:
- One helper for every method.
HttpRequest.Builder.method(...)accepts any HTTP verb, includingPATCH, which has no shortcut method likeGET()orPOST(...). - JSON bodies from text blocks. Each body is a text block; placing the closing
"""on the content line avoids a trailing newline. Building JSON from objects instead of strings is covered in JSON in Java. - Status codes drive the logic. The client sees
201with aLocationheader for the create,409for the duplicate,200for both updates,204for the delete and404for the repeated delete, exactly as designed in the tables above. - Filtering through query parameters.
?maxFee=3000returns onlydockerandgo, sorted by code. Thejavacourse costs more and is filtered out. - Safe retries. Because
PUTandDELETEare idempotent, the client could retry them after a timeout without corrupting data. A retriedPOSTwould only hit the409guard, which is why the create uses an atomicputIfAbsenton the server.