@Wordpress\RestRoute( namespace="plugin/v1", methods="GET,POST", route="/endpoint",
args={
"entity_id" : { "required": true, "sanitize_callback": "absint" }
}
)
This annotation is used to create a new WP REST API endpoint. This annotation uses the register_rest_route()
function in WordPress to add the endpoint.
@Params
methods="GET,POST"
(optional) / {default: “GET”} – Comma separated list of HTTP acesss methods.
route="/endpoint"
(required) – The endpoint url route
namespace="plugin/v1"
(optional) / The namespace for the endpoint. If not provided, the ‘rest_namespace’ property on the object class will be used, otherwise your plugin slug will be used (if your object instance implements a getPlugin() method). If none of the above can be found, then the namespace will default to ‘mwp’. >args={"entity_id": { "required": true, "sanitize_callback": "absint" } }
(optional) An array of arguments to pass to the register_rest_route() wp function. Where callbacks are specified, if you enter the name of a method that is callable on your object instance, it will be used as the callback.
@Example Code
/**
* Create a new association given a parent/child/relationship
*
* @MWP\WordPress\RestRoute( methods="POST", route="/associations",
* args={
* "parent_id" : { "required": true, "validate_callback": "validatePostExists" },
* "child_id" : { "required": true, "validate_callback": "validatePostExists" },
* "user_id" : { "sanitize_callback": "absint" }
* }
* )
*
* @param WP_REST_Request $request The request
* @return WP_REST_Response
*/
public function postAssociation( \WP_REST_Request $request )
{
try
{
$manager = $this->getPlugin()->getRelationshipManager( $request['relationship_id'] );
$association = $manager->createAssociation(
$request['parent_id'],
$request['child_id'],
$request['user_id' ]
);
return new \WP_REST_Response( $association->backboneModel(), 201 );
}
catch( \InvalidArgumentException $e )
{
return new \WP_Error( 'invalid_argument', $e->getMessage() );
}
}
/**
* Validate a post
*
* @param int $post_id The post id
* @return bool
*/
public function validatePostExists( $post_id )
{
return ! empty( get_post( $post_id ) );
}