Skip to content

Instantly share code, notes, and snippets.

@tareq1988
Created August 10, 2022 08:50
Show Gist options
  • Save tareq1988/be49697425326fc90952de835313ff6b to your computer and use it in GitHub Desktop.
Save tareq1988/be49697425326fc90952de835313ff6b to your computer and use it in GitHub Desktop.
WREST - easy to use REST API wrapper for WordPress

WREST (WordPress REST)

An easy to use fluent REST API wrapper

wrest()->get($uri, $callback);
wrest()->post($uri, $callback);
wrest()->put($uri, $callback);
wrest()->patch($uri, $callback);
wrest()->delete($uri, $callback);
wrest()->options($uri, $callback);

Example

WordPress API needs a namespace, so we can group it.

wrest()->namespace('myplugin/v1', function() {
    wrest->get('greeting', function(WP_REST_Request $req) {
        return 'Hello world';
    });

    wrest->post('greeting', function(WP_REST_Request $req) {
        return 'Hello world';
    });
});

Permission Management

Passing a capability

wrest->get('greeting', function() {
    return 'Hello world';
})->permission('manage_options');

Passing a callback

wrest->get('greeting', function() {
    return 'Hello world';
})->permission(function(WP_REST_Request $req) {
    return is_user_logged_in();
});

Namespace on the fly

wrest()->namespace('myplugin/v1')->get('greeting', function() {
    return 'Hello there';
});

Resources

A single endpoint can have CRUD operation

wrest->resource('/posts')
    ->schema($callback)
    ->routes(function($group) {
        $group->get(function() {
            return 'All posts';
        });

        $group->post(function($request) {
            // create post
        })->permission($callback);
    });

Parameters passing

wrest()->get('/posts/{slug}', function(WP_REST_Request $request, $slug) {

})->param('slug', '[A-Za-z]+');

wrest()->get('/user/{id}/{name}', function ($request, $id, $name) {
    //
})->param(['id' => '[0-9]+', 'name' => '[a-z]+']);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment