Home > Software design >  Wordpress rest API work on browser but not with curl
Wordpress rest API work on browser but not with curl

Time:11-02

I wrote this code to register REST route, It works fine in the browser but not work with CURL

function my_func()
{
    return new WP_REST_Response('ok');
}

function init_my_func(){
    $namespace = 'test/v1';
    $route     = 'fire';

    register_rest_route($namespace, $route, array(
        'methods'   => WP_REST_Server::READABLE,
        'callback'  => 'my_func',
        'args' => array(),
        'permission_callback' => function () {
        return true;
        }
    ));
}

add_action('rest_api_init', 'init_my_func');

The curl code:

$params = array();
$params['arg1'] = 'value1';
$json = json_encode($params);

$url = "http://example.com/wp-json/test/v1/fire";
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $json,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_HTTPHEADER => array(
        "cache-control: no-cache",
        "Content-Type: application/json;"
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

The response:

{\"code\":\"rest_no_route\",\"message\":\"No route was found matching the URL and request method.\",\"data\":{\"status\":404}}

CodePudding user response:

You registed a GET route by 'methods' => WP_REST_Server::READABLE, but sent a POST request in curl. you need to unify the request method, both GET or both POST.

  • Related