Three groups of people need this API, one of them is me, and I have fourteen chapters of code. The other two are the developer building the screens and the engineer writing the tests, and what they have is a conversation in which I describe what the responses will look like. That is the normal flow and it is worse than it sounds. It is not that they are blocked, it is that they are not: they start, against what they remember of what I said, and the disagreement surfaces weeks later as a bug report about a field that was always called something else. By then there are three versions of the truth, and mine is the only one that compiles.
What follows is the artifact that replaces the conversation. It is not documentation, and it is not generated from the running service, because a specification that requires a working server cannot exist before the server works. It is a repository of its own, versioned on its own, published to a registry, and declared as a dependency by everything that needs it - including the service that implements it.
A repository of its own
The first decision is the one that looks like overhead, the types and the operation signatures could live in the service, in a module beside the others, and the frontend could read them on GitHub. Instead they live in advanced-spring-api-contract, which is a separate repository with a separate build and a separate version number.
The reason is the version number, and it is easier to see from the other end. Last week's work on this project produced a migration and a mapped column: real changes to the service, worth a release. Nothing in them changed what a caller sends or receives. If the contract were a module of the service, it would have been released too, with a new version, and the two teams downstream would have had to look at it to find out that nothing concerns them. Multiply that by every bug fix for a year and the version number stops carrying information - which is the point at which people stop reading it.
Kept separate, the arithmetic reverses, the contract's version changes when the contract changes, and only then. A bug fixed in the service ships as a new service with the same contract, and the signal downstream is that there is no signal. The repository holds three modules. dto is the types on the wire, rest-api is the operations, and for now the configuration that decides how those types are rendered. events is empty, and exists anyway: a consumer of the HTTP API and a consumer of a topic are two different audiences with two different promises, and neither should have to depend on the other's. An empty module is cheap, discovering later that both promises are in one jar is not.
Two types for one product
A product has two audiences, somebody browsing the catalogue wants a name, a price and a picture of what they might buy. The seller who owns it wants everything, and will change some of it. Those are not the same representation, and the API does not pretend they are. The obvious alternative is one path whose response depends on who asked. It is worse in three ways that are easy to miss until they happen. A shared cache cannot tell the two apart without a correctly set Vary, and the day it gets that wrong it serves the full representation to anonymous callers. A specification cannot describe one path that returns two schemas, so the published contract becomes vaguer exactly where it matters. And a client written against the anonymous response has no way to know that the field it is missing exists for somebody else.
So there are two types, ProductDescriptionDto and ProductDto, and they are siblings rather than one extending the other:
public class ProductDescriptionDto extends AbstractCreatableEntityDto {
private String name;
private String sku;
private BigDecimal price;
private ProductStatusDto status;
}
What they share is a base holding an identifier and a creation time. What the full one adds is an update time and a version, and the reason the public projection does not inherit them is the argument this project has now made three times in three places. The version is a concurrency token: a caller that cannot write has nothing to do with one. The schema put the column on the tables that can be updated, the entity put the field on the class that introduces updating, and the contract hands the number only to the audience that can use it. The same rule, applied at a third boundary.
CategoryAssignmentDto is the other end of that rule, it extends the creatable base and stops there, because an assignment is never updated - it exists or it does not and giving it a version would be giving it a capability it does not have.
What a caller may send
There are two more types per entity, and they are the ones that look redundant in a review.
public class NewProductDto extends AbstractDto { ... }
public class UpdateProductDto extends AbstractDto { ... }
Neither extends the read type, and neither carries an identifier, a timestamp or a version, because none of those belong to a caller. The alternative - one type for all three directions, with documentation explaining which fields apply when - puts the rules in prose, and prose is the one part of a contract that a generated client cannot check. A field that is read-only is a comment, a field that is absent is a compiler error. Two fields are missing on purpose, and both absences carry an argument from earlier chapters.
There is no status on either write type. A status change is a transition with rules: a draft may become active, an archived product may become nothing at all, and the service holds the table of what may follow what. A settable field would describe the column. The operation that replaces it is a separate one, and it is the same reasoning the service layer used when it chose changeStatus() over a setter.
And the measurements are flat on creation - a dimensions string and a weight - rather than a nested specification object. The specification is a thing with its own identity once it exists, and it has its own table and its own version to prove it. But at the moment of creation it does not exist, and asking a caller to post an object with an empty identifier so that the server can fill it in would be describing the storage rather than the request. On the way back it is a nested object, because by then it is one.
No Java in the payload
There is one annotation this base class deliberately does not carry.
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class AbstractDto {
}
The missing one is @JsonTypeInfo, and with it the @class property that writes a Java class name into every payload. It is a useful thing in the right place and the wrong thing here, for a reason that is mechanical rather than aesthetic.
A polymorphic type annotation is not a property of the class. It is an instruction to the mapper, which is why a tool that builds a specification from the Java types cannot see it - not through an oversight, and not in some versions and not others, but by construction. The result is a field that exists in every response and in none of the schemas. A generated client does not have it and works anyway, because generators tolerate what they do not expect. A strict schema validator does not, which is how the test engineer finds out. And the package structure of the service travels to the browser, unofficially, which means somebody will eventually depend on it and a refactoring will break them.
The annotation that remains points the other way, and it is the reason adding a field to this API is not a negotiation. ignoreUnknown means a client compiled against version 1.0 of this jar keeps working when 1.1 adds a property. Without it, every addition is a breaking change and the version number starts to mean something nobody wants it to mean.
Removing the property has a consequence that has to be met somewhere, and it is met in the signature. A deserializer that discovers the type from the payload needs the type to be in the payload, one that is told the type does not. So the reader here takes the target as an argument - process(payload, ProductDto.class) and that is not a workaround. Over HTTP the caller always knows what it asked for, and on the server the framework deserializes into the parameter type the handler declares.
There is one place where a type marker earns its keep, and it is the module that is still empty. A consumer reading from a topic genuinely does not know what it is holding. When events has something in it, it will carry a discriminator - a logical event name, not a class name, because ProductCreated is a contract and a fully qualified Java type is an internal detail that changes meaning during a rename.
A price is not a number
The contract says a product has a price. What it does not say, in any schema language, is what that price looks like when it arrives.
module.addSerializer(BigDecimal.class, ToStringSerializer.instance);
A price goes out as a JSON string. The reason is the client, not the server: a JSON number parsed by a browser becomes a double, and a double is the wrong container for money twice over. The first loss is the scale. 19.90 arrives and becomes 19.9 - the same amount, displayed as something no price list has ever shown and the repair is a formatter on the client that now holds its own opinion about how many decimals a currency has. The second loss is real, add that same 19.90 a hundred times in a double and the total is 1990.0000000000036, and a client that rounds its way out of that will find that round(2.675, 2) is 2.67. Writing the price as a string keeps the scale the server decided on, and makes arithmetic on money something a client has to opt into with a type that can do it rather than something it falls into by parsing.
Which raises the question of where that decision belongs, and the answer is why rest-api depends on databind rather than only on annotations. The mapper lives in the contract, a specification can say that a price is a string - only a configuration makes it one, and if that configuration lives in the service then the contract describes an intention and the service decides the reality. Publishing them together means the artifact that declares the operations also declares how their values are rendered, and the tests that exercise it are testing the published contract rather than a local approximation of it.
That holds on one condition, and it is worth stating now because it is the first thing chapter seventeen has to get right. A service that lets the framework configure its own mapper has two configurations. The tests prove one of them, the requests are served by the other, and they agree until somebody changes one - at which point the tests still pass. The application module will take its mapper from here rather than from autoconfiguration, and that line is what makes everything in this section true in production rather than only in a test.
One shape for an instant
The same question, asked about time, has a less obvious answer. Jackson's handling of java.time is correct ISO-8601, and correct ISO-8601 is not one format. The fractional part is dropped when it is zero and printed to three, six or nine digits otherwise, depending on the value. Every one of those strings is valid and they are not interchangeable to a consumer that compares them, slices them by position, or uses one as a cache key. The bug that produces is the worst kind: it appears only for the request that happened to land on a whole second.
So the format is pinned, in one place, because the same string is needed by the serializer, by the examples in the specification and by the tests.
public static final String PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
Always UTC, always three digits, always a trailing Z.
The deserializer is deliberately more forgiving than the serializer, and the asymmetry is the point. What this API writes is one exact shape. What it accepts is any ISO-8601 instant: with a fractional part or without one, and with an offset other than UTC. A client that sends 2026-11-03T16:15:00+02:00 has named a moment in time correctly, and rejecting it would be pedantry dressed up as rigour. Strict on the way out, so that nobody downstream has to handle variation, tolerant on the way in, so that nobody upstream has to guess.
What the mapper does not do
The mapper is built once, in a static initialiser, and handed out as a single instance. That is not thrift for its own sake: building one is expensive and a built one is immutable and safe to share, so the alternative is paying for the same object on every request and giving each copy its own chance to be configured slightly differently. One instance is also what makes the configuration a fact about the contract rather than a habit of whoever constructed it last.
There is no activateDefaultTyping. It is the switch that puts the @class property back, and a mapper is where somebody would reasonably turn it on to solve a different problem - deserializing a field declared as Object, for example. Leaving it off is the same decision as leaving @JsonTypeInfo off the base class, made in the second place it can be made.
There is no INDENT_OUTPUT either, pretty-printed JSON is a convenience for whoever is reading a response by eye, which is nobody in production, and the whitespace is paid for on every byte of every response.
The one addition is stranger than either, and it is a character escape:
private static final char[] CHARS_TO_ESCAPE = { '\u2028', '\u2029' };
Those two are a line separator and a paragraph separator. They are legal inside a JSON string, and in JavaScript they used to be line terminators even inside a string literal, which meant a product name containing one produced valid JSON that became a syntax error the moment a page embedded it in a script. ES2019 removed them by allowing them in string literals, so the classic version of this bug is now historical, but it's not gone, though. The two characters are still line terminators elsewhere in the JavaScript grammar, so a payload that lands somewhere other than a string literal - inside a comment, for instance, still behaves differently from what it looks like. Escaping them costs one class and removes a whole category of question about where a consumer is allowed to put the bytes. That is the kind of trade I will take without thinking about it, and the kind that is impossible to retrofit once somebody is parsing responses in anger.
What the tests prove
Fifteen tests is not much of a test suite, and they are the most valuable thing in this repository. They exist because everything in the two sections above is a claim. The serializer writes money as a string: that is a claim until something reads the output and checks. Instants carry three digits even when the fourth would be a zero: a claim, and the one most likely to be true on a developer's machine and false at the moment it matters. No Java class name travels to a client: a claim, and an easy one to break by adding an annotation to a base class in a hurry.
So there is a test for a price of 20.00, which exists to prove the trailing zero survives. One for 0.0000000001, which exists because a small enough number tempts a mapper into scientific notation. One for an instant on a whole second, which is the case the default format gets wrong and the case nobody writes a test for. One for nine digits of precision, to establish that they are truncated rather than rounded. One asserting that neither @class nor com.pe.advanced appears in the output, which is how a future change to AbstractDto fails loudly rather than quietly. And one for a payload containing a field this version has never heard of, because forward compatibility is a promise and an unverified promise is a hope.
That is what makes this a contract rather than a document. A document describes, this compiles, runs, and fails the build when the description and the behaviour disagree.
What this part settled
There is a jar now, it has a version number that moves when the API moves and stays still when the service merely improves. It holds twenty-six types that say what a product, a category and an assignment look like in both directions, with the audiences separated rather than merged. It renders money and time in exactly one way, and proves it.
What it cannot do is tell anybody which URL to call. There is not a path, not a verb, not an operation anywhere in it. The types describe what a response contains - nothing yet describes what to ask for, and a frontend developer holding this jar still cannot write a request.
What's Next?
Chapter 16 adds the operations, and the interesting part is not the interfaces - it is that declaring the path and the verb in exactly one place is what makes a specification generable at all. Swagger annotations describe an operation, they do not say where it lives. Something has to, and whichever file it is becomes the one that cannot disagree with anything. Then the module that turns all of it into an OpenAPI document at build time, without a running service and without a single implemented endpoint, so that the file reaches the registry before the first controller exists. That is the whole reason for the separation this chapter argued for, and it is the point at which the frontend and the tests stop waiting.
Two small disagreements surfaced while writing these types and belong to that chapter or the one after it. A product's weight is a double in the domain and an integer in the schema, and grams in floating point mean nothing. A category has a description column and no such field in the domain type. Both are the same shape of bug this project keeps finding: two descriptions of one thing, each defensible alone.
Codebase & Architecture Blueprint
The entire evolutionary architecture of this project is tracked using strict Git tags. From this chapter on there are two repositories: the service, and the API contract it implements. This chapter is entirely in the second one.
-
API contract (Tag:
chapter-15-api-contract): advanced-spring-api-contract -
Service (unchanged since Chapter 14, Tag:
chapter-14-schema): advanced-spring-multimodule
That second line is the chapter's argument rather than a formality: the service has not moved, so its tag has not moved either.
Note: All core modules are configured with strict compilation-level boundaries. Compile and run mvn clean install to see the structure in action. Maven version 3.9.* and Java 25 are required.
◀️ Read Chapter 14: The Schema Three Chapters Were Already Relying On
▶️ Read Chapter 16: Generating the Specification (Coming soon)
Join the Masterclass Journey
This article is part of an ongoing weekly series. If you want to receive every upcoming chapter directly in your inbox, alongside deep-dives, infrastructure architecture diagrams, and premium insights before anyone else, subscribe to my Substack Newsletter here!
Recommended Resources for Java & Spring Boot Engineers
Disclosure: I earn a commission if you purchase through the links below, at no additional cost to you.
If you are preparing for Senior/Lead Java interviews or looking to solidify your Spring Boot & Architecture skills, check out these highly-rated resources from the Javarevisited publication (Use promo code friends20 for an exclusive 20% discount automatically applied at checkout):
- Grokking the Java Interview Prepare for core Java, concurrency, JVM internals, and design pattern questions. Get Full Book (Paid) | Download Free Sample Copy
- Grokking the Spring Boot Interview Master Spring Core, Auto-configuration, Spring Data JPA, Security, and Microservices. Get Full Book (Paid) | Download Free Sample Copy
- Grokking the SQL Interview Deep-dive into query optimization, indexing, joins, and complex SQL window functions. Get Full Book (Paid) | Download Free Sample Copy
- The Complete Java + Spring + SQL Interview Bundle Get all three interview guides in a single heavily discounted package. Get the Ultimate Interview Bundle
- Spring Professional Certification Practice Questions (250+ Questions) Validating your skills? Practice with real exam-style questions before taking the Spring Professional certification. Get the Spring Professional Questions | Download Free Sample Copy
Top comments (0)