How to Build a REST API With Play Framework in Java
Build a small JSON REST API in Play with routes, controllers that read and return JSON, validation and consistent error responses.

Play's strengths show up in JSON APIs: routes the compiler checks, a quick edit-and-refresh loop and non-blocking I/O underneath. This post builds a small product API with list, get, create and delete on Play 3.0 and Java 25, and then deals with the parts that decide whether the API is pleasant to use: status codes, validation, one error shape and CORS. The design rules apply to any framework and are collected in REST API design rules for Java teams. If you have not created a Play project yet, start with the Play tutorial.
Routes first
GET /api/products controllers.ProductController.list
GET /api/products/:id controllers.ProductController.get(id: Long)
POST /api/products controllers.ProductController.create(request: Request)
DELETE /api/products/:id controllers.ProductController.delete(id: Long)The routes file is the table of contents of the API: every verb and path in one place, with no annotations scattered across classes. Each line names a typed action. The id: Long declaration makes the router reject /api/products/abc with a 400 before your code runs, so you do not write that check yourself. If an action named here does not exist, the project fails to compile, which is the property people mean when they praise Play's type checking.
A model to carry the data
package models;
public class Product {
public Long id;
public String name;
public long priceCents;
}Public fields keep the example short, and Jackson can serialize and deserialize them. In a real project use a class with accessors or a record. Price is a whole number of cents, because a floating-point price eventually prints 24.899999999 and a customer notices.
The controller
package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import models.Product;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Http;
import play.mvc.Result;
public class ProductController extends Controller {
private final ConcurrentHashMap<Long, Product> products = new ConcurrentHashMap<>();
private final AtomicLong ids = new AtomicLong();
public Result list() {
return ok(Json.toJson(products.values()));
}
public Result get(Long id) {
Product product = products.get(id);
return product == null
? notFound(error("No product " + id))
: ok(Json.toJson(product));
}
public Result create(Http.Request request) {
JsonNode json = request.body().asJson();
if (json == null) {
return badRequest(error("Expected a JSON body"));
}
Product product = Json.fromJson(json, Product.class);
if (product.name == null || product.name.isBlank()) {
return badRequest(error("name is required"));
}
product.id = ids.incrementAndGet();
products.put(product.id, product);
return created(Json.toJson(product));
}
public Result delete(Long id) {
return products.remove(id) == null
? notFound(error("No product " + id))
: noContent();
}
private JsonNode error(String message) {
return Json.newObject().put("error", message);
}
}Each action returns a Result built by a helper that names the status: ok for 200, created for 201, noContent for 204, badRequest for 400 and notFound for 404. The names make the intent readable, and the status matches the outcome. A common mistake is to return 200 with an error in the body, which forces every client to inspect the body before knowing whether the call worked.
request.body().asJson() returns null when the request's Content-Type is not JSON, so the null check is not decoration. Without it, a client that forgets the header gets a NullPointerException and a 500. Note also that the map lives in a controller field. Play creates controllers per injection, so state like this is a teaching shortcut, and a real service keeps data in a database through Ebean or JPA.
Try it
curl -i -X POST localhost:9000/api/products \
-H 'Content-Type: application/json' \
-d '{"name":"Espresso machine","priceCents":24900}'
curl -i localhost:9000/api/products/1
curl -i localhost:9000/api/products/99The first call returns 201 and the product with its new id. The second reads it back. The third returns 404 with {"error":"No product 99"}. Change the controller, save, and call again: Play recompiles on the next request, which is the dev loop that makes the framework pleasant for APIs.
Validation, and one error shape
Hand-written checks are fine for two fields. When a payload grows, bind through FormFactory with Jakarta Bean Validation annotations on a form class. It collects the field errors into a map you return as JSON, so a client can show each message beside its field. Whatever you choose, use one error shape across the whole API. A client that has to parse three formats from one server will eventually get one wrong. The problem-details format described in building REST APIs with Spring MVC works in any framework.
CORS for browser clients
A browser app on another origin needs the CORS filter, and it is configuration only:
play.filters.enabled += play.filters.cors.CORSFilter
play.filters.cors.allowedOrigins = ["https://app.example.test"]Without it the browser refuses to hand the response to the script, and the console reports a CORS error although the server answered 200. List the exact origins you trust rather than a wildcard when cookies or credentials are involved. The symptom and the cause are identical in every server, as in CORS errors in Spring Boot.
Testing the API
Play ships a test helper that starts the application and sends requests without a network. A test calls the route, reads the status and parses the body, which checks the routes file, the binding and the JSON in one go:
Result result = route(app, fakeRequest(POST, "/api/products")
.bodyJson(Json.newObject().put("name", "").put("priceCents", 100)));
assertEquals(BAD_REQUEST, result.status());Write one such test per outcome the controller can produce: created, invalid body, not found, deleted. These four cover most of what can break, and they take milliseconds, because there is no browser and no socket. Run them in the same build that deploys the service, so a change to a route cannot reach production unchecked.
Keep the assertions on status codes and the error field. Asserting on the full JSON text makes every harmless rename a test failure, and people stop trusting tests that fail for nothing.
Idempotency and repeated calls
A POST that creates something is not safe to repeat, and a client that times out will repeat it. Decide how the API behaves. One answer is to accept a client-supplied key in a header and return the original result for a repeated key. Another is to make creation a PUT to an id the client chooses. The in-memory example ignores this, and a payment or order API cannot. Deletion is naturally idempotent in effect, but notice that the second DELETE above returns 404, which some clients treat as failure. Returning 204 for an already-deleted resource is a legitimate choice, and it should be a decision you made, not a side effect.
Logging what the API did
Log one line per mutating call with the route, the resulting status and the id of the thing touched. When a client says "a product vanished", that line answers the question in seconds, and without it you are reconstructing events from a database that has already forgotten. Keep request bodies out of the log, since they contain whatever users typed.
One place for errors
The error shape from the validation section is easy to keep when it is produced in one class. Play lets you replace the default handler, so every failure, including ones you did not write a catch for, comes back as JSON:
package handlers;
public class JsonErrorHandler implements HttpErrorHandler {
@Override
public CompletionStage<Result> onClientError(Http.RequestHeader request, int statusCode, String message) {
ObjectNode body = Json.newObject();
body.put("status", statusCode);
body.put("message", message.isEmpty() ? "Request error" : message);
return CompletableFuture.completedFuture(Results.status(statusCode, body));
}
@Override
public CompletionStage<Result> onServerError(Http.RequestHeader request, Throwable exception) {
String id = UUID.randomUUID().toString();
play.Logger.ALogger log = play.Logger.of(JsonErrorHandler.class);
log.error("error " + id + " on " + request.method() + " " + request.path(), exception);
ObjectNode body = Json.newObject();
body.put("status", 500);
body.put("message", "Internal error");
body.put("errorId", id);
return CompletableFuture.completedFuture(Results.internalServerError(body));
}
}# conf/application.conf
play.http.errorHandler = "handlers.JsonErrorHandler"The client gets an errorId and no stack trace, and the same id is in the log line next to the exception, so a user's report leads straight to the cause. A request for an unknown route, a malformed body that Play rejects before your action runs and an exception thrown deep in a service now share one format, which is what a client developer wants from an API.
What changes when this grows
Add a version to the path from the start if the API has several consumers. Moving /api/products to /api/v1/products after clients exist means running both. Database calls are blocking, and Play runs actions on its default dispatcher, so a service with blocking queries needs a separate execution context, as discussed in Play architecture. Return lists in pages, not whole tables. The primary references are the Play JSON documentation and the routing documentation.


