OpenApi
Juneau supports converting arbitrary POJOs to and from strings using OpenAPI-based schema rules.
When to use it
Use the OpenAPI serializer and parser when a single value, such as a query parameter, header or path segment, must follow a schema: a delimited list, a fixed date format, a range or a length limit. For whole documents in a data format, use JSON or one of the other format families; those carry structure by themselves and need no schema. In a REST server or client you seldom call these classes directly: the part annotations below attach a schema to a method parameter and Juneau applies it.
Example
import static org.apache.juneau.marshall.httppart.HttpPartSchema.*;
import org.apache.juneau.commons.httppart.*;
import org.apache.juneau.marshall.httppart.*;
import org.apache.juneau.marshall.oapi.*;
public class OpenApiExample {
public static void main(String[] args) throws Exception {
// A pipe-delimited list of comma-delimited numbers, each between 0 and 100.
HttpPartSchema schema = tArrayPipes(
tArrayCsv(
tInt64().min(0).max(100)
)
).build();
// String to POJO.
Long[][] pojo = OpenApiParser.DEFAULT.read(HttpPartType.QUERY, schema, "1,2,3|4,5,6|7,8,9", Long[][].class);
// POJO back to string.
System.out.println(pojo[1][2] + " " + OpenApiSerializer.DEFAULT.write(HttpPartType.QUERY, schema, pojo));
// A value outside the schema is rejected.
try {
OpenApiParser.DEFAULT.read(HttpPartType.QUERY, schema, "1,2,300", Long[][].class);
} catch (SchemaValidationException e) {
System.out.println("rejected");
}
}
}
The program prints 6 1,2,3|4,5,6|7,8,9 and then rejected.
Options
The relevant classes for using OpenAPI-based serialization are:
The HttpPartSchema class is used to define the formatting and validations for a POJO. It's used in conjunction with the serializer and parser to produce and consume HTTP parts based on OpenAPI rules.
Later in the rest-server and rest-client sections, we also describe how the following annotations can be applied to method parameters and class types to define the schema for various HTTP parts:
The schema builder methods the example uses:
| Method | Effect |
|---|---|
tArrayPipes(...) / tArrayCsv(...) | An array whose items are separated by pipes or commas; the argument is the item schema. |
tInt64() / tInt32() | A 64-bit or 32-bit integer. |
min(...) / max(...) | Lower and upper bound on a number. |
minl(...) / maxl(...) | Minimum and maximum length of a string or array. |
See also
In This Section
📄️ 2.2.31.1. OpenAPI Methodology
Unlike the other Juneau serializers and parsers that convert input and output directly to-and-from POJOs, the OpenAPI
📄️ 2.2.31.2. OpenAPI Serializers
The OpenApiSerializer class is used to convert POJOs to
📄️ 2.2.31.3. OpenAPI Parsers
The OpenApiParser class is used to convert HTTP parts back