Skip to content

Defining the endpoint's available routes (URLs)

Dane Rossenrode edited this page Apr 9, 2016 · 6 revisions

RESTful defines a bunch of routes by default for each resource. For example, it provides GET and POST at your resource URL i.e.

GET http://drupalsite.com/api/v1.0/myresource
POST http://drupalsite.com/api/v1.0/myresource

as well as routes for when there's one or more ID's on the end i.e.

GET http://drupalsite.com/api/v1.0/myresource/5,34

These default routes are defined in controllersInfo() in the RestfulBase class in 1.x, and the Resource class in 2.x, and can be overridden in your own resource class if needed.

The method definition in 1.x:

  /**
   * Returns the default controllers for the entity.
   *
   * @return array
   *   Nested array that provides information about what method to call for each
   *   route pattern.
   */
  public static function controllersInfo() {
    // Provide sensible defaults for the HTTP methods. These methods (index,
    // create, view, update and delete) are not implemented in this layer but
    // they are guaranteed to exist because we are enforcing that all restful
    // resources are an instance of \RestfulDataProviderInterface.
    return array(
      '' => array(
        // GET returns a list of entities.
        \RestfulInterface::GET => 'index',
        \RestfulInterface::HEAD => 'index',
        // POST
        \RestfulInterface::POST => 'create',
      ),
      // We don't know what the ID looks like, assume that everything is the ID.
      '^.*$' => array(
        \RestfulInterface::GET => 'view',
        \RestfulInterface::HEAD => 'view',
        \RestfulInterface::PUT => 'replace',
        \RestfulInterface::PATCH => 'update',
        \RestfulInterface::DELETE => 'remove',
      ),
    );
  }

The method definition in 2.x:

  public function controllersInfo() {
    return array(
      '' => array(
        // GET returns a list of entities.
        RequestInterface::METHOD_GET => 'index',
        RequestInterface::METHOD_HEAD => 'index',
        // POST.
        RequestInterface::METHOD_POST => 'create',
        RequestInterface::METHOD_OPTIONS => 'discover',
      ),
      // We don't know what the ID looks like, assume that everything is the ID.
      '^.*$' => array(
        RequestInterface::METHOD_GET => 'view',
        RequestInterface::METHOD_HEAD => 'view',
        RequestInterface::METHOD_PUT => 'replace',
        RequestInterface::METHOD_PATCH => 'update',
        RequestInterface::METHOD_DELETE => 'remove',
        RequestInterface::METHOD_OPTIONS => 'discover',
      ),
    );
  }
Clone this wiki locally