Skip to main content

JSON Responses

The Ecommerce\Http\JsonResponse class extends WP_REST_Response to provide a fluent interface for constructing JSON responses. It automatically handles encoding, setting headers, and proper status codes for your API endpoints.

Creating Responses​

Constructing a new JSON response.

Constructor​

Create a new JsonResponse instance.

Description:

The constructor initializes the response with data, status code, and headers. It automatically encodes the data to JSON.

Method Signature:

public function __construct(mixed $data = [], int $status = 200, array $headers = [], int $options = 0)

Parameters:

  • $data - The data to be encoded. Can be array, object, Jsonable, or Arrayable.
  • $status - HTTP status code (default 200).
  • $headers - Array of HTTP headers.
  • $options - JSON encoding options.

Examples:

use Ecommerce\Http\JsonResponse;

// Simple success response
return new JsonResponse(['message' => 'Success']);

// Response with data and status
return new JsonResponse(
['error' => 'Not Found'],
404
);

// Response with headers
return new JsonResponse(
['data' => []],
200,
['X-Custom-Header' => 'Value']
);

Helper Function​

Use the droip_response() helper.

Description:

The droip_response() helper function provides a convenient way to create responses without instantiating the class manually. It returns a factory or the response itself.

Examples:

// JSON helper
return droip_response()->json(['message' => 'Created'], 201);

// Error helper
return droip_response()->error('Something went wrong', 400);

// Success helper
return droip_response()->success(['id' => 1], 'Saved successfully');

Managing Content​

Methods for manipulating the response content.

Set Content​

Set and encode the response content.

Description:

The set_content() method updates the response body. It handles various data types (arrays, objects, collections) and encodes them to JSON.

Method Signature:

public function set_content(mixed $data): JsonResponse

Examples:

$response = new JsonResponse();
$response->set_content(['new' => 'data']);

Get Content​

Retrieve the decoded response content.

Description:

The get_content() method returns the decoded JSON data. You can request it as an associative array or object.

Method Signature:

public function get_content(bool $assoc = false, int $depth = 512): mixed

Parameters:

  • $assoc - True to return as associative array.
  • $depth - Maximum recursion depth.

Examples:

$content = $response->get_content(true);
echo $content['message'];

Encoding Options​

Set custom JSON encoding options.

Description:

The set_encoding_options() method allows you to customize how the JSON is encoded (e.g., JSON_PRETTY_PRINT).

Method Signature:

public function set_encoding_options(int $option): JsonResponse

Examples:

$response->set_encoding_options(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);