0

I've made a custom endpoint for my REST API:

add_action( 'rest_api_init', function () {
 register_rest_route( 'foo/v1', '/bar/', array(
   'methods' => 'GET',
   'callback' => 'foo_callback',
 ) );
} );

I normally have a WP query as my callback, but to simplify things let's pretend I'm just asking for certain parameters to be returned to me:

function foo_callback(){
    $string = "";  
    if($_REQUEST['paged']){
       $string .= $_REQUEST['paged'];
    }
    if($_REQUEST['posts_per_page']){
       $string .= $_REQUEST['posts_per_page']; 
    }

    return $string; 
}

I'm also locking down my API so only logged-in users can access it, requiring an Application Password.

add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) {
        return $result;
    }
    if ( ! is_user_logged_in() ) {
        return new WP_Error( 'rest_not_logged_in', 'You're not logged in bozo.', array( 'status' => 401 ) );
    }
    return $result;
});

This API request with a single parameter works:

curl -X GET https://example.com/wp-json/foo/v1/bar?posts_per_page=1 -H "Authorization: Basic xxxxx"

This API request with a different parameter works:

curl -X GET https://example.com/wp-json/foo/v1/bar?paged=2 -H "Authorization: Basic xxxxx"

But this API request combining both parameters does not work:

curl -X GET https://example.com/wp-json/foo/v1/bar?posts_per_page=1&paged=2 -H "Authorization: Basic xxxxx"

In fact, it tells me "You're not logged in, bozo". Multiple parameters are somehow triggering my !is_user_logged_in() rule (although it throws up a generic error even if I remove that clause).

What am I doing wrong, and what's the correct way to allow multiple parameters in my endpoint?

2
  • Argh - ignore me. It was a simple matter of needing quotation marks in my cURL around the URL. :/ Commented Dec 8, 2023 at 12:49
  • can you post that as an answer rather than a comment? Commented Dec 8, 2023 at 13:30

1 Answer 1

2

Short answer to a long question:

I needed quotation marks round the URL.

curl -X GET "https://example.com/wp-json/foo/v1/bar?posts_per_page=1&paged=2" -H "Authorization: Basic xxxxx"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.