Search code examples
wordpresswordpress-rest-api

Wordpress custom API endpoint, making arguments required not working as expected


I appreciate your help; I have wordpress 6.3x and have defined a custom endpoint as follows;

add_action('rest_api_init', function(){
    register_rest_route('fs/v1', '/fs_ski_resort/', array(
            'methods'   => 'GET',
            'callback'  => 'fs_ski_resort_data',
            'args'      =>  array(
                    'osm_geometry' => array(
                            'required' => true
                        )
                ) 
        )
    );
});

If I run the below, it doesn't work as expected. I want the API to say, the meta_value is required for the meta_key but instead it returns all ski resorts. How to I say that the meta_value is also required?

https://www.example.com/api/fs/v1/fs_ski_resort/?osm_geometry

The below works as expected and returns attributes for a single ski resort:

https://www.example.com/api/fs/v1/fs_ski_resort/?osm_geometry=way-1176728877

The below also works as expected and replies, osm_geometry is required

https://www.example.com/api/fs/v1/fs_ski_resort/

Solution

  • You can use validation_callback property to check whether the param is empty.

    add_action('rest_api_init', function(){
        register_rest_route('fs/v1', '/fs_ski_resort/', array(
                'methods'   => 'GET',
                'callback' => 'fs_ski_resort_data',
                'args'      =>  array(
                        'osm_geometry' => array(
                                'required' => true,
                                'validate_callback' => function($param, $request, $key) {
                                        return !empty($param);
                                }
                            )
                    ) 
            )
        );
    });
    

    Update: It may be annoying and not a best practice if you have many APIs for which that validation should be checked.

    You can extract that anonymous function into a named function and pass the function to validation_callback:

    function checkParamIsNotEmpty($param, $request, $key)
    {
        return !empty($param);
    }
    
    add_action('rest_api_init', function () {
        register_rest_route(
            'fs/v1',
            '/fs_ski_resort/',
            array(
                'methods'   => 'GET',
                'callback' => 'fs_ski_resort_data',
                'args'      =>  array(
                    'osm_geometry' => array(
                        'required' => true,
                        'validate_callback' => 'checkParamIsNotEmpty'
                    )
                )
            )
        );
    });