PHP code example of marspress / rest-api-endpoint
1. Go to this page and download the library: Download marspress/rest-api-endpoint library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
marspress / rest-api-endpoint example snippets
\WP_REST_Server::READABLE = 'GET'
\WP_REST_Server::EDITABLE = 'POST, PUT, PATCH'
\WP_REST_Server::DELETABLE = 'DELETE'
\WP_REST_Server::ALLMETHODS = 'GET, POST, PUT, PATCH, DELETE'
$myApiNamespace = new \MarsPress\RestAPI\Rest_Namespace(
'my_api_namespace',
'v1'
);
$myApiNamespace_Endpoint = new \MarsPress\RestAPI\Endpoint(
'my_endpoint',
\WP_REST_Server::READABLE,
function ( \WP_REST_Request $_request ){
return new \WP_REST_Response([
'message' => 'PID is ' . $_request->get_param("pid"),
],200);
}
);
$myApiNamespace_Endpoint_PID = new \MarsPress\RestAPI\Parameter(
'pid',
'/',
12,
true,
'.+',
function( string $_parameterValue, \WP_REST_Request $_request, string $_parameterName ){
if( ! \is_numeric($_parameterValue) ){
return new \WP_Error(
503,
"$_parameterName must be a numeric value."
);
}
return true;
},
function( string $_parameterValue, \WP_REST_Request $_request, string $_parameterName ){
return \number_format( \floatval( $_parameterValue ), 2 );
}
);
$myApiNamespace_Endpoint->add_parameters(
$myApiNamespace_Endpoint_PID,
);
$myApiNamespace->add_endpoints(
$myApiNamespace_Endpoint,
);
$myApiNamespace = (new \MarsPress\RestAPI\Rest_Namespace(
'my_api_namespace',
'v1'
))->add_endpoints(
(new \MarsPress\RestAPI\Endpoint(
'my_endpoint',
\WP_REST_Server::READABLE,
function ( \WP_REST_Request $_request ){
return new \WP_REST_Response([
'message' => 'PID is ' . $_request->get_param("pid"),
],200);
}
))->add_parameters(
new \MarsPress\RestAPI\Parameter(
'pid',
'/',
12,
true,
'.+',
function( string $_parameterValue, \WP_REST_Request $_request, string $_parameterName ){
if( ! \is_numeric($_parameterValue) ){
return new \WP_Error(
503,
"$_parameterName must be a numeric value."
);
}
return true;
},
function( string $_parameterValue, \WP_REST_Request $_request, string $_parameterName ){
return \number_format( \floatval( $_parameterValue ), 2 );
}
),
),
);
wp_register_script( 'my_js_script', '<script_uri>', ['<dependencies>'], '<version>', true );
wp_localize_script( 'my_js_script', '<localized_object_name>', [
'my_nonce' => \wp_create_nonce('wp_rest'),
]);
wp_enqueue_script( 'my_js_script' );