PHPackages                             marspress/rest-api-endpoint - 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. marspress/rest-api-endpoint

ActiveLibrary[API Development](/categories/api)

marspress/rest-api-endpoint
===========================

Utility package to create custom REST API routes in WordPress.

1.01(4y ago)0552GPL-2.0PHPPHP &gt;=7.4

Since Dec 14Pushed 4y ago2 watchersCompare

[ Source](https://github.com/MARSWorksInc/wordpress-rest-api-routes)[ Packagist](https://packagist.org/packages/marspress/rest-api-endpoint)[ RSS](/packages/marspress-rest-api-endpoint/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (4)Used By (0)

MarsPress REST API Endpoints
============================

[](#marspress-rest-api-endpoints)

### Installation

[](#installation)

Require the composer package in your composer.json with `marspress/rest-api-endpoint` with minimum `dev-main` OR run `composer require marspress/rest-api-endpoint`

### Resources

[](#resources)

-

There are WordPress constants for the allowed request methods. It is recommended that you use the constants below, concatenating where necessary.

```
\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'
```

### Usage

[](#usage)

You will first need to create a Rest Namespace. Then you will add Endpoint objects to it, and add Parameter objects to your Endpoints.

#### Rest Namespace

[](#rest-namespace)

`new \MarsPress\RestAPI\Rest_Namespace()` takes 4 parameters, 2 required and 2 optional.

- Namespace (required)(string)
    - The slug for your namespace, this should be unique in the whole WordPress theme and plugin scope.
    - E.g. `seminars` would result in your namespace being at `/wp-json/seminars`.
- Version (required)(string)
    - The version string for your namespace, generally these are just `v1` etc.
    - It is recommended that you keep all versions of your namespaces available.
    - E.g. `v1` would result in your namespace being at `/wp-json/seminars/v1`.
- Permissions Callback (optional)(callable)
    - The method to call to check if the namespace endpoints are able to get accessed.
    - This method should return a bool.
    - Defaults to a method that returns `true`, making the endpoints public to all.
    - Your permission callback should take 1 parameter of the type `\WP_REST_Request`.
    - This can be a Closure function, or `[ $this, '' ]` for non-static classes or `[ __CLASS__, '' ]` for static classes.
- Override (required)(bool)
    - Whether the namespace should be able to override other namespaces and endpoints.
    - Defaults to `false`.

##### Available Methods

[](#available-methods)

- `$namespace->add_endpoints()`
    - Adds Endpoint objects to the Rest Namespace instance.
    - Takes any umber of `\MarsPress\RestAPI\Endpoint` objects.

#### Endpoint

[](#endpoint)

`new \MarsPress\RestAPI\Endpoint()` takes 5 parameters, 3 required and 2 optional.

- Endpoint (required)(string)
    - The slug of the endpoint.
    - E.g. `upcoming` would result in the endpoint being at `/wp-json/seminars/v1/upcoming`.
- Allowed Methods (required)(string)
    - The allowed HTTP Request methods for the endpoint.
    - This should be a comma seperated string of the methods. You may use the WordPress constants.
    - E.g. `GET`.
- Callback (required)(callable)
    - The method to be called for the endpoint.
    - The callback should take 1 parameter of the type `\WP_REST_Request`.
    - Your method should return a new instance of `\WP_REST_Response`.
    - This can be a Closure function, or `[ $this, '' ]` for non-static classes or `[ __CLASS__, '' ]` for static classes.
- Override (optional)(bool)
    - If the endpoint should override existing endpoints of the same name and namespace.
    - Defaults to `false`.
- Permissions Callback (optional)(callable)
    - The method to call to check if the endpoint is able to get accessed.
    - This method should return a bool.
    - Defaults to `null`, falling back to the Rest Namespace permission callback.
    - Your permission callback should take 1 parameter of the type `\WP_REST_Request`.
    - This can be a Closure function, or `[ $this, '' ]` for non-static classes or `[ __CLASS__, '' ]` for static classes.

##### Available Methods

[](#available-methods-1)

- `$endpoint->add_parameters()`
    - Adds Parameter objects to the Endpoint instance.
    - Takes any umber of `\MarsPress\RestAPI\Parameter` objects.

#### Parameter

[](#parameter)

`new \MarsPress\RestAPI\Parameter()` takes 7 parameters, 1 required and 6 optional.

- Name (required)(string)
    - The name of the parameter.
    - This should be unique to the Endpoint.
- Type (optional)(string)
    - Whether the parameter should be passed in the URL or as a URL parameter.
    - Defaults to `?`, having the parameter have to be passed as `?=x`.
    - Valid values are `?` and `/`.
    - `/` will pass the parameter into the URL as such: `/wp-json/seminars/v1/upcoming/`
    - You may have multiple `/` parameters, they will just be registered in the order they are in the array of Parameter objects in the Endpoint class.
- Default (optional)(mixed)
    - The default value for the parameter.
    - Default is no default: `null`.
- Required (optional)(bool)
    - If the parameter is required or not.
    - Defaults to `false`.
- Match (optional)(string)
    - The regex type matching for the parameter.
    - This is only used in Parameters of the type `/`.
    - Defaults to `.{1,128}`, meaning it will match any character 1 to 128 times.
    - Other useful matches are:
        - `.+`, match any character any amount of times.
        - `\d{1,8}`, match any digit 1 to 8 times.
- Validation Callback (optional)(callable)
    - Defaults to no callback: `null`.
    - If any of your parameters fail their validation, your Endpoint's callback will not be called.
    - Your validation callback should take 3 parameters:
        - Parameter Value (string)
        - Request Object (\\WP\_REST\_Request)
        - Parameter Name (string)
    - IMPORTANT: The limitation of the validation callback in WordPress is that the framework does not test if your return is `empty` or `nullable`. Another limitation is that it only outputs a vague message if you return `false`.
        - Return `true` specifically if the Parameter Value matches your validation.
        - If it does not meet your validation, it is recommended that you return a new instance of `\WP_Error`, allowing you to return specific status codes and messages.
    - This can be a Closure function, or `[ $this, '' ]` for non-static classes or `[ __CLASS__, '' ]` for static classes.
- Sanitization Callback (optional)(callable)
    - Defaults to no callback: `null`.
    - Sanitize any of the parameter values before they are passed to your Endpoint's callback.
    - Your sanitization callback should take 3 parameters:
        - Parameter Value (string)
        - Request Object (\\WP\_REST\_Request)
        - Parameter Name (string)
    - This can be a Closure function, or `[ $this, '' ]` for non-static classes or `[ __CLASS__, '' ]` for static classes.

#### Example

[](#example)

First we make a new Namespace:

```
$myApiNamespace = new \MarsPress\RestAPI\Rest_Namespace(
    'my_api_namespace',
    'v1'
);
```

Then we can create an Endpoint:

```
$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);
    }
);
```

Then we can create a Parameter:

```
$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 );
    }
);
```

Then we can add Parameters to the newly created Endpoint:

```
$myApiNamespace_Endpoint->add_parameters(
    $myApiNamespace_Endpoint_PID,
);
```

Finally, we can add the Endpoint to the Rest Namespace:

```
$myApiNamespace->add_endpoints(
    $myApiNamespace_Endpoint,
);
```

In the above example, the REST API endpoint we created will be at `/wp-json/my_api_namespace/v1/my_endpoint/`. The PID parameter will be passed inside the URL, and it must be a numeric value, finally it will be sanitized into a two decimal formatted float. It then returns a new `\WP_REST_Response` with a message and a status code of `200`.

### Method / Class Chaining

[](#method--class-chaining)

It is highly recommended that you use method and class chaining when creating your Rest Namespace, Endpoints, and Parameters.

Here is the above example, but using method and class chaining:

```
$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 );
            }
        ),
    ),
);
```

### Advanced Topics

[](#advanced-topics)

#### X-WP-Nonce Header

[](#x-wp-nonce-header)

If you need to use current user sessions in your Endpoint and Parameter callbacks (e.g. `current_user_can()` or `get_current_user_id()`), you must send a generated nonce in the header of your request.

This is particularly useful if you only want users to be able to access their own data through your REST endpoint. E.g. I could call `/wp-json/my_api_namespace/v1/my_endpoint/18` to get user data for a user with the ID of 18, but if I am not logged in as the user with the ID 18, I would not be able to access the endpoint.

To generate a nonce and make is usable in your JS scripts, you will need to localize your script as such:

```
wp_register_script( 'my_js_script', '', [''], '', true );
wp_localize_script( 'my_js_script', '', [
    'my_nonce'  => \wp_create_nonce('wp_rest'),
]);
wp_enqueue_script( 'my_js_script' );
```

It is important to use `wp_rest` as the key as that is the key WordPress will use to validate the nonce in the REST API.

In a jQuery AJAX example, you would set it as such:

```
jQuery.ajax({
  type: 'GET',
  url: '/wp-json/my_api_namespace/v1/my_endpoint/18',
  async: true,
  dataType: 'json',
  data: ({}),
  beforeSend: function( _request ) {
    _request.setRequestHeader( 'X-WP-Nonce', '.my_nonce' );
  },
  complete: function ( _response ) {},
});
```

Nothing further is needed, if you generated and localized your nonce and set the `X-WP-Nonce` header correctly, your REST endpoint callbacks should automatically know the current user session that is trying to access the endpoint.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

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 ~0 days

Total

2

Last Release

1613d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/adcbfb731b685a8b219008c6c3673b843a0c9aa66c4b6d2a2c1ab03eef959f08?d=identicon)[martian-jesse](/maintainers/martian-jesse)

---

Top Contributors

[![martian-jesse](https://avatars.githubusercontent.com/u/86261906?v=4)](https://github.com/martian-jesse "martian-jesse (4 commits)")

### Embed Badge

![Health badge](/badges/marspress-rest-api-endpoint/health.svg)

```
[![Health](https://phpackages.com/badges/marspress-rest-api-endpoint/health.svg)](https://phpackages.com/packages/marspress-rest-api-endpoint)
```

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

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

A PHP wrapper for Twilio's API

1.6k92.9M272](/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)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

73813.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

263103.1M454](/packages/google-gax)

PHPackages © 2026

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