REST API in Java

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 274 of 306

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.

PrincipleMeaningExample
ResourcesEvery thing has its own URL/api/courses/java
HTTP methodsThe method says what to doGET reads, DELETE removes
RepresentationsClients get a copy of the resource in a formatJSON body
StatelessEach request carries everything needed; no server memory of the clientAuth token in every request
Status codesThe result is in the HTTP status201 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 URLActionSuccess status
GET /api/coursesList courses (with filters)200 OK
GET /api/courses/{code}Read one course200 OK
POST /api/coursesCreate a course201 Created
PUT /api/courses/{code}Replace a course completely200 OK
PATCH /api/courses/{code}Change some fields200 OK
DELETE /api/courses/{code}Delete a course204 No Content
AvoidPrefer
/api/getAllCoursesGET /api/courses
/api/deleteCourse?id=javaDELETE /api/courses/java
/api/course/java/updatePUT /api/courses/java
/api/courses?action=createPOST /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

MethodCRUDSafe (no changes)Idempotent (repeat = same result)Servlet method
GETReadYesYesdoGet
POSTCreateNoNodoPost
PUTReplaceNoYesdoPut
PATCHPartial updateNoNot guaranteeddoPatch (Servlet 6.1)
DELETEDeleteNoYesdoDelete

How it works:

  • Idempotent means sending the same request twice leaves the server in the same state. Clients and proxies may safely retry PUT and DELETE after a timeout, but not POST, which could create a duplicate.
  • Before Servlet 6.1, PATCH required overriding service(). Tomcat 11 calls doPatch directly.

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:

  • ConcurrentHashMap matters because Tomcat calls one servlet instance from many threads at once.
  • Overriding service and calling super.service keeps normal method dispatch, but catches parsing errors in one place and turns them into 400 JSON 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 ConcurrentHashMap alone has no predictable order.
  • Paging uses skip and limit, and X-Total-Count tells the client how many results exist in total, so it can draw page links.
  • The invalid page=abc is caught by the service override and answered with 400.

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:

  • putIfAbsent checks and inserts in one atomic step, so two clients creating the same code at the same moment cannot both succeed.
  • 409 Conflict signals a duplicate, 400 signals invalid fields and 415 signals 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 PATCH body names only feeInr, so title and lessons keep their old values. JsonObject.has tells "field missing" apart from "field set".
  • PUT takes the code from the URL, never from the body, so a client cannot rename a course by accident.
  • Both methods run the same validate method, 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 Content means success with an empty body.
  • The second DELETE returns 404, but the server state is the same after both calls: the course is gone. That is what makes DELETE idempotent.

REST API Status Codes Reference

CodeNameSend it when
200OKA read or update succeeded
201CreatedPOST created a resource (add Location)
204No ContentSuccess with no body, usually DELETE
400Bad RequestInvalid JSON, fields or parameters
401UnauthorizedNo valid credentials
403ForbiddenCredentials valid but not allowed
404Not FoundThe resource does not exist
405Method Not AllowedMethod not supported on that URL
409ConflictDuplicate or conflicting state
415Unsupported Media TypeBody is not in the expected format
500Internal Server ErrorAn unexpected failure on the server

Note: Never return 200 with 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:

  1. One helper for every method. HttpRequest.Builder.method(...) accepts any HTTP verb, including PATCH, which has no shortcut method like GET() or POST(...).
  2. 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.
  3. Status codes drive the logic. The client sees 201 with a Location header for the create, 409 for the duplicate, 200 for both updates, 204 for the delete and 404 for the repeated delete, exactly as designed in the tables above.
  4. Filtering through query parameters. ?maxFee=3000 returns only docker and go, sorted by code. The java course costs more and is filtered out.
  5. Safe retries. Because PUT and DELETE are idempotent, the client could retry them after a timeout without corrupting data. A retried POST would only hit the 409 guard, which is why the create uses an atomic putIfAbsent on the server.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about REST API in Java and get answers drawn from it.

Signed-in readers only.