Make WordPress Core


Ignore:
Timestamp:
03/02/2025 10:05:08 PM (3 months ago)
Author:
TimothyBlynJacobs
Message:

REST API: Improve performance for HEAD requests.

By default, the REST API responds to HEAD rqeuests by calling the GET handler and omitting the body from the response. While convenient, this ends up performing needless work that slows down the API response time.

This commit adjusts the Core controllers to specifically handle HEAD requests by not preparing the response body.

Fixes #56481.
Props antonvlasenko, janusdev, ironprogrammer, swissspidy, spacedmonkey, mukesh27, mamaduka, timothyblynjacobs.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api/wpRestTemplatesController.php

    r59201 r59899  
    177177
    178178    /**
     179     * @ticket 56481
     180     *
     181     * @covers WP_REST_Templates_Controller::get_items
     182     */
     183    public function test_get_items_should_return_no_response_body_for_head_requests() {
     184        wp_set_current_user( self::$admin_id );
     185        $request  = new WP_REST_Request( 'HEAD', '/wp/v2/templates' );
     186        $response = rest_get_server()->dispatch( $request );
     187        $this->assertSame( 200, $response->get_status(), 'Response status is 200.' );
     188        $this->assertNull( $response->get_data(), 'The server should not generate a body in response to a HEAD request.' );
     189    }
     190
     191    /**
    179192     * @covers WP_REST_Templates_Controller::get_items
    180193     */
     
    269282
    270283    /**
     284     * @ticket 56481
     285     *
     286     * @covers WP_REST_Templates_Controller::get_item
     287     * @covers WP_REST_Templates_Controller::prepare_item_for_response
     288     */
     289    public function test_get_item_should_return_no_response_body_for_head_requests() {
     290        wp_set_current_user( self::$admin_id );
     291        $request  = new WP_REST_Request( 'HEAD', '/wp/v2/templates/default//my_template' );
     292        $response = rest_get_server()->dispatch( $request );
     293        $this->assertSame( 200, $response->get_status(), 'Response status is 200.' );
     294        $this->assertNull( $response->get_data(), 'The server should not generate a body in response to a HEAD request.' );
     295    }
     296
     297    /**
    271298     * @covers WP_REST_Templates_Controller::get_item
    272299     */
     
    311338        wp_set_current_user( self::$subscriber_id );
    312339        $request  = new WP_REST_Request( 'GET', '/wp/v2/templates/default//my_template' );
    313         $response = rest_get_server()->dispatch( $request );
    314340        $response = rest_get_server()->dispatch( $request );
    315341        $this->assertErrorResponse( 'rest_cannot_manage_templates', $response, 403 );
Note: See TracChangeset for help on using the changeset viewer.