Igor Simic
4 years ago

Wordpress REST API response codes




Using the custom HTTP response codes in WP REST API can be very useful, especially to display different kind of messages in frontend based on them. Wordpress rest API is offering two ways how to set them: for error and success responses.

To set custom response error code with message we can use class: WP_Error
// if there is no posts return 404 with custom message
if( empty($query->posts) ){
                return new WP_Error( 'no_posts', __('No post found'), array( 'status' => 404 ) );// status can be changed to any number
            }

// output

{
"code": "no_posts",
"message": "No post found",
"
data": {
"status": 404}}

Of course we can change the status number to any number (even 200s), as well as the other parameters code and message

Another, simpler, way is to use WP_REST_Response - this one is usually used for successful requests and it does not contain message in response:
// when response is success
$response = new WP_REST_Response($data, 200); // data => array of returned data
return $response;