PHP code example of kuliebiakin / simple-rest-api
1. Go to this page and download the library: Download kuliebiakin/simple-rest-api 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/ */
kuliebiakin / simple-rest-api example snippets
$router = new Simple_REST_API\Router( 'my-plugin/v1.0', [ 'etag' => true ] );
$router->get( '/posts', function() {
return get_posts();
} );
$router->get( '/post/{id}', function( WP_REST_Response $response, $id ) {
$post = get_post( $id );
if( ! $post ) {
$response->set_status( 404 );
}
else {
$response->set_data( $post );
}
return $response;
} );
$router->post( '/feedback', function( WP_REST_Request $request, WP_REST_Response $response ) {
$body_params = $request->get_body_params();
$message = esc_html( $body_params['message'] );
wp_mail( '[email protected] ', '[YourSite] Feedback', $message );
$response->set_status( 201 );
$response->set_data( 'Thank you for your feedback!' );
return $response;
} );
$router->put( '/post/{id}', function( $id ) {
// ...
} );
$router->delete( '/post/{id}', function( $id ) {
// ...
} );
$router->patch( '/post/{id}', function( $id ) {
// ...
} );
$router->get( '/post/{id}', function( $id ) {
// ...
} );
$router->get( '/post/{post_id}/paged/{page_id}', function( $post_id, $page_id ) {
// ...
} );
$router->get( '/post/{post_id}/paged/{page_id}', function( $page_id, $post_id ) {
// ...
} );
$router->get( '/post/{id}', function( WP_REST_Request $request, WP_REST_Response $response, $id ) {
// ...
} );
$router->get( '/post/{id}', function( $id ) {
// ...
} )->convert( 'id', function( $id ) { return (int) $id; } );
$router->get( '/comments/{user}', function( $user ) {
// ...
} )->convert( 'user', function( $user ) { return get_user_by( 'id', $user ); } );
$router->get( '/post/{id}', function( $id ) {
// ...
} )->assert( 'id', '\d+' );
$before_callback = function() {
$GLOBALS['wpdb']->queries = [];
};
$after_callback = function( WP_REST_Response $response ) {
$data = $response->get_data();
if( is_array( $data ) ) {
$data['debug'] = [
'time' => timer_stop(),
'queries' => $GLOBALS['wpdb']->queries,
];
$response->set_data( $data );
}
};
$router->get( '/post/{id}', function( $id ) {
// ...
} )->before( $before_callback )->after( $after_callback );