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/src/wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php

    r59892 r59899  
    356356            $prepared_args['search'] = '*' . $prepared_args['search'] . '*';
    357357        }
     358
     359        $is_head_request = $request->is_method( 'HEAD' );
     360        if ( $is_head_request ) {
     361            // Force the 'fields' argument. For HEAD requests, only user IDs are required.
     362            $prepared_args['fields'] = 'id';
     363        }
    358364        /**
    359365         * Filters WP_User_Query arguments when querying users via the REST API.
     
    370376        $query = new WP_User_Query( $prepared_args );
    371377
    372         $users = array();
    373 
    374         foreach ( $query->get_results() as $user ) {
    375             $data    = $this->prepare_item_for_response( $user, $request );
    376             $users[] = $this->prepare_response_for_collection( $data );
    377         }
    378 
    379         $response = rest_ensure_response( $users );
     378        if ( ! $is_head_request ) {
     379            $users = array();
     380
     381            foreach ( $query->get_results() as $user ) {
     382                $data    = $this->prepare_item_for_response( $user, $request );
     383                $users[] = $this->prepare_response_for_collection( $data );
     384            }
     385        }
     386
     387        $response = $is_head_request ? new WP_REST_Response() : rest_ensure_response( $users );
    380388
    381389        // Store pagination values for headers then unset for count query.
     
    10211029        // Restores the more descriptive, specific name for use within this method.
    10221030        $user = $item;
     1031
     1032        // Don't prepare the response body for HEAD requests.
     1033        if ( $request->is_method( 'HEAD' ) ) {
     1034            /** This filter is documented in wp-includes/rest-api/endpoints/class-wp-rest-users-controller.php */
     1035            return apply_filters( 'rest_prepare_user', new WP_REST_Response(), $user, $request );
     1036        }
    10231037
    10241038        $fields = $this->get_fields_for_response( $request );
Note: See TracChangeset for help on using the changeset viewer.