PHPackages                             gebruederheitz/wp-simple-rest - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. gebruederheitz/wp-simple-rest

ActiveLibrary[API Development](/categories/api)

gebruederheitz/wp-simple-rest
=============================

A trait to help you set up REST endpoints in Wordpress.

v3.0.1(1y ago)01.3k↓50%[1 issues](https://github.com/gebruederheitz/wp-simple-rest/issues)4GPL-3.0-onlyPHPPHP &gt;=7.4

Since Jul 8Pushed 1y ago2 watchersCompare

[ Source](https://github.com/gebruederheitz/wp-simple-rest)[ Packagist](https://packagist.org/packages/gebruederheitz/wp-simple-rest)[ RSS](/packages/gebruederheitz-wp-simple-rest/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)Dependencies (4)Versions (11)Used By (4)

Wordpress Simple REST Trait
===========================

[](#wordpress-simple-rest-trait)

*A trait to help you set up REST endpoints in Wordpress.*

---

Helps you with registering and processing REST endpoints in Wordpress projects.

- [Installation](#installation)
- [Usage](#usage)
    - [Getting the defined routes' full URLs](#getting-the-defined-routes-full-urls)
    - [Changing the route base path](#changing-the-route-base-path)
- [Upgrading](#upgrading)

Installation
------------

[](#installation)

via composer:

```
> composer require gebruederheitz/wp-simple-rest
```

Make sure you have Composer autoload or an alternative class loader present.

Usage
-----

[](#usage)

```
use Gebruederheitz\Traits\withREST;
/* optional */
use Gebruederheitz\Wordpress\Rest\RestRoute;

class MyClass {
    // use the trait
    use withREST;

    public function __construct() {
        // initialize the REST functionality
        $this->initInstanceRestApi();
    }

    // Callbacks for your routes must be public
    public function myRestCallback() {}

    // Define your Routes by implementing the abstract method
    public function getInstanceRestRoutes()
    {
        return [
            // Using the RestRoute helper object
            RestRoute::create(
                'A description of what your route does.',
                '/rest-example'
            )
                ->setCallback([$this, 'myRestCallback'])
                ->setMethods('POST')
                ->allowAnyone()
                ->addArgument(
                    'parameter_one',
                    'A description of what the argument is for.',
                    'a default value',
                    'string',
                    [$this, 'sanitizeParameterOne'],
                    [$this, 'validateParameterOne']
                )
                ->addArgument(
                    'other_param',
                    'A parameter that is essential to this route.',
                )
            ,
            // Using the legacy array format
            [
                'name' => 'A description of what your route does',
                'route' => '/rest-example',
                'config' => [
                    'methods' => 'POST',
                    'callback' => [$this, 'myRestCallback'],
                    'permission_callback' => function () {
                        return current_user_can('edit_posts');
                    },
                    'args' => [
                        'parameter_one' => [
                            'description' => 'A description of what the argument is for',
                            'default' => '',
                            'type' => 'string',
                            'sanitize_callback' => 'esc_url_raw',
                        ]
                    ]
                ]
            ],
            // Restricting access
            RestRoute::create(
                'Do dangerous things with the database',
                '/danger-zone/database',
            )
                ->setCallback([$this, 'restDangerousDbOperation'])
                // only users with 'install_plugins' capabilities
                ->allowOnlyAdmins()
                // or only users with 'edit_posts' capabilities
                ->allowOnlyEditors()
                // or a custom callback allowing you to check for capabilities
                // ...with a closure
                ->setPermissionCallback(function() {
                    return current_user_can('read_private_pages');
                })
                // ...with a class method
                ->setPermissionCallback([$this, 'canUserAccessDbDangerZone'])
                // ...with a static class method
                ->setPermissionCallback([self::class, 'canUserAccessStatic'])
            ,
        ];
    }

    // Must have an implementation, in this case it's just a dummy
    protected static function getRestRoutes(): array
    {
        return [];
    }
}
```

You could now execute your callback with the following request:

```
POST https://example.com/wp-json/ghwp/v1/rest-example

```

Alternatively you can use the static variant allowing you to call only static methods on your class:

```
use Gebruederheitz\Traits\withREST;

class MyClass {
    // use the trait
    use withREST;

    public static function init() {
        // initialize the REST functionality
        self::initRestApi();
    }

    public static function myRestCallback() {}

    // This is the dummy this time around
    public function getInstanceRestRoutes()
    {
        return [];
    }

    // Define your Routes by implementing the abstract method
    protected static function getRestRoutes(): array
    {
        return [
            [
                'name' => 'A description of what your route does',
                'route' => '/rest-example',
                'config' => [
                    'methods' => 'POST',
                    'callback' => [self::class, 'myRestCallback'],
                    'permission_callback' => function () {
                        return current_user_can('edit_posts');
                    },
                    'args' => [
                        'parameter_one' => [
                            'description' => 'A description of what the argument is for',
                            'default' => '',
                            'type' => 'string',
                            'sanitize_callback' => 'esc_url_raw',
                        ]
                    ]
                ]
            ],
        ];
    }
}
```

### Setting the route's access

[](#setting-the-routes-access)

You should always explicitly define your route's access privileges, otherwise Wordpress will wiggle its finger in your face. You can choose one of the convenience methods provided by `RestRoute` or supply your own callback:

```
RestRoute::create('Name', '/path')
    // public route
    ->allowAnyone()
    // or only users with 'install_plugins' capabilities
    ->allowOnlyAdmins()
    // or only users with 'edit_posts' capabilities
    ->allowOnlyEditors()
    // or a custom callback allowing you to check for capabilities
    // ...with a closure
    ->setPermissionCallback(function() {
        return current_user_can('read_private_pages');
    })
    // ...with a class method
    ->setPermissionCallback([$this, 'canUserAccessDbDangerZone'])
    // ...with a static class method
    ->setPermissionCallback([self::class, 'canUserAccessStatic'])
```

### Getting the defined routes' full URLs

[](#getting-the-defined-routes-full-urls)

```
// list only the static routes
MyClass::getRestEndpoints();
// Both static and instance routes
$myClassInstance->getAllRestEndpoints();
```

### Changing the route base path

[](#changing-the-route-base-path)

```
class MyClass {
    use \Gebruederheitz\Traits\withREST;

    public static $restNamespaceBase = 'my-rest-routes';
}
```

Your routes will now be available at `/wp-json/my-rest-routes/v1/rest-example`.

Upgrading
---------

[](#upgrading)

### To version 2.x

[](#to-version-2x)

From v1.x to v2.0 the namespaces used in the library changed. You will need to update your `use` statements to reflect those changes:

```
/* BEFORE */
use Gebruederheitz\Traits\Rest\withREST
/* AFTER */
use Gebruederheitz\Wordpress\Rest\Traits\withREST
```

Development
-----------

[](#development)

### Dependencies

[](#dependencies)

- PHP &gt;= 7.4
- [Composer 2.x](https://getcomposer.org)
- [NVM](https://github.com/nvm-sh/nvm) and nodeJS LTS (v16.x)
- Nice to have: GNU Make (or drop-in alternative)

###  Health Score

37

—

LowBetter than 82% of packages

Maintenance50

Moderate activity, may be stable

Popularity18

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~153 days

Recently: every ~311 days

Total

10

Last Release

389d ago

Major Versions

v1.x-dev → v2.0.02021-11-12

v2.2.0 → v3.0.02025-04-15

PHP version history (3 changes)v1.0.0PHP ^7.3

v2.1.1PHP &gt;=7.3

v3.0.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/d2a201d58341e3ed71321bcb66cb375a8c6efffce7d8fe33244e821afc087c78?d=identicon)[mediocrity](/maintainers/mediocrity)

---

Top Contributors

[![AndreasMaros](https://avatars.githubusercontent.com/u/25008845?v=4)](https://github.com/AndreasMaros "AndreasMaros (19 commits)")

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/gebruederheitz-wp-simple-rest/health.svg)

```
[![Health](https://phpackages.com/badges/gebruederheitz-wp-simple-rest/health.svg)](https://phpackages.com/packages/gebruederheitz-wp-simple-rest)
```

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M475](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M270](/packages/twilio-sdk)[knplabs/github-api

GitHub API v3 client

2.2k15.8M187](/packages/knplabs-github-api)[facebook/php-business-sdk

PHP SDK for Facebook Business

90121.9M34](/packages/facebook-php-business-sdk)[microsoft/microsoft-graph

The Microsoft Graph SDK for PHP

65723.5M95](/packages/microsoft-microsoft-graph)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

73813.7M114](/packages/meilisearch-meilisearch-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
