Creating a post with the REST API, curl and oauth returning 401 error

“The REST API uses JSON exclusively as the request and response format, including error responses.”

WordPress REST API Reference

I would try explicitly setting the content type/length and json encode your data with something like this (assuming you need to specify all the options you did in your code provided):

$data = array(
    'title' => 'testTitle',
    'content' => '',
);

$data = json_encode( $data );

$header = array(
    buildAuthorizationHeader( $oauth ),
    'Content-Type: application/json',
    'Content-Length: ' . strlen( $data ),
    'Expect:',
);

$options = array(
    CURLOPT_HTTPHEADER => $header,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_POST => true,
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_POSTFIELDS => $data,
);

Leave a Comment