Custom Rest API POST endpoint with conditionally required parameters

Question

Guys;

I’ve spent the last 6 hours trying to figure this out, I’m likely being dumb.

I’m trying to create a POST endpoint that has parameters that are required based on the value of another parameter.

register_rest_route(
        'thing/v1',
        '/thingy/(?P<foo>d+)',
        array(
            'methods'  => 'POST',
            'callback' => array( $this, 'create_something' ),
            'args'     => array(
                'foo' => array(
                    'required' => true,
                    'type'     => 'integer',
                ),
                'bar' => array(
                    'required' => true, // make this false if foo = 3
                    'type'     => 'integer',
                ),
            ),
        )
    );

I’ve tried a few things including:

  • Setting a callback as the required value. (It didn’t get into the function so I guess it doesn’t like callbacks).
  • Using validate_callback with required as false by default, the problem was that if the parameter wasn’t submitted to the request it didn’t get into the function.
  • Using validate_callback with required as true by default, the problem was that the parameter still existed when it wasn’t needed (which in my case would cause issue further down the line).

I was looking through the core for a filter or hook that would let me change the required value dynamically, (a little hacky sure), but I couldn’t find anything.

Just thought I’d ask here, incase I’m missing something obvious.

Thanks

0
Toby Osborne 4 months 0 Answers 14 views 0

Leave an answer