Skip to main content

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:

OpenApiSerializer - Converts POJOs to strings.OpenApiParser - Converts strings to POJOs.HttpPartSchema - Defines the schema for your POJO.

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:

Content Header Query FormData Path Response

The schema builder methods the example uses:

MethodEffect
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​