How can I return an image from a custom REST API endpoint?

I’m brand new to WordPress development; Trying to return an image from a custom endpoint, but it seems to want to serialize everything to JSON.

I did manage to get it to work using echo. Is that a hack?

I also tried using WP_HTTP_Response, but that didn’t seem to work.

My code:

require 'vendor/autoload.php';

use Intervention\Image\ImageManagerStatic as Image;

function prefix_generate_cover_photo($data) {
    $image = Image::make(plugin_dir_path(__FILE__) . 'image.png')->response();
    $response = new WP_REST_Response($image, 200, array(
        'Content-Type' => 'image/png'
    ));
    return $response;
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'prefix/v1', '/photo', array(
        'methods' => 'GET',
        'callback' => 'prefix_generate_cover_photo',
    ));
});

This works but I’m not sure if it’s good practice:

function prefix_generate_cover_photo($data) {
    echo Image::make(plugin_dir_path(__FILE__) . 'image.png')->response();
}

Any ideas?

1 Answer
1

echo in the rest-api and not valid! You should using return to make output to Rest API.

For example:

function prefix_generate_cover_photo( WP_REST_Request $request ) {
    // Get method params
    $params = $request->get_params();

    // Data
    $data = array(
        'url'   => 'The image url',
        'title' => 'The image title',
    );

    // Create the response object
    $response = new WP_REST_Response( array( 'image' => $data ) );

    // Add a custom header (Optional)
    //$response->header( 'Cache-Control', 'no-cache' );

    return $response;
}

Leave a Comment