9.b. JSON
Introduction
Since the default content-type for requests in Adventure is text/html; charset=utf-8, we have a special endpoint for returning JSON content. This is done through the /json/ endpoint, which returns the content with the Content-Type: application/json representation header. This endpoint is particularly useful for developers as it simplifies JSON-based communication and enables seamless API integrations, making it easier to build and interact with RESTful services.
The response can be built using standard Smarty or Adventure Smarty components and composites. The JSON endpoint lives under the /json/ path and has an associated view files in the /src/views/json.tpl directory. Together with the platform utilities, this can be used to handle most of the RESTful API requirements. Specifically the Request and JSON utilities have functions that work great for JSON use cases. The example below is taken from /src/views/json.tpl and shows how you can accept the request parameters and return a JSON response, with all the data provided in the initial request.
Example
{$request = $Platform->import("request")}
{$json = $Platform->import("json")}
{$payload = $request->getBodyPayload()}
{$payloadData = $json->parse($payload['data'])}
{$json->encode([
"Received method:" => $request->getType(),
"Received body (JSON):" => $payloadData
])}