Zum Inhalt

Implement a JSON API

We will implement a simple JSON API that splits the input string.

static class SplitRequest implements JSONReflective {
    String text;
    String delimiter;
}

@Override
public void start() {
    SiteLocation location = getConfig().getLocation("location").orError();
    addSite(location.appendPath("/split"), request -> {

        if (!request.hasContent())
            throw new HTTPException(HTTPStatus.S400_BAD_REQUEST, "No input provided");

        SplitRequest r = request.getContentJSON(new SplitRequest());
        String[] parts = r.text.split(r.delimiter);
        return new HTTPResponse().setContentJSON(new JSONReflectiveWrapper(parts));

    });
}

A request with body

{
    "text": "Tomato, Apple, Orange",
    "delimiter": ", "
}

will be responded to with (compact)

[
    "Tomato",
    "Apple",
    "Orange"
]