REST API Endpoint

Let's create a REST API endpoint that retrieves details on a project. First, install the apex/rest-api by running the following install command:

apex install rest-api

Once installed, create an API endpoint with the following opus api-endpoint command:

apex opus api-endpoint Disaster/Api/Projects/Retrieve

Open the newly generated file at /src/Disaster/Api/Projects/Retrieve.php and replace it with the following contents:

<?php
declare(strict_types = 1);

namespace App\Disaster\Api\Projects;

use App\RestApi\Helpers\ApiRequest;
use App\RestApi\Models\{ApiResponse, ApiDoc, ApiParam, ApiReturnVar};
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Disaster\Models\Project;

/**
 * Retrieve API endpoint
 */
Class Retrieve extends ApiRequest
{

    /**
     * The auth level required to access this endpoint.  
     * Supported values are:  public, user, admin
     */
    public string $acl_required = 'public';

    /**
     * Retrive project details
     */
    public function get(ServerRequestInterface $request, RequestHandlerInterface $app):ApiResponse
    {

        // Check for project id
        if (!$project_id = $app->get('project_id')) {
            return new ApiResponse(400, [], "No project_id variable defined.");
        }

        // Get project
        if (!$proj = Project::whereId($project_id)) {
            return new ApiResponse(404, [], "No project exists with the id# $project_id");
        }

        // Gather response
        $res = $proj->toArray();
        $res['asignees'] = $proj->getAssignees();

        // Return
        return new ApiResponse(200, $res);
    }

}

You will notice this class closely resembles ar PSR-15 Middleware class with two notable exceptions:

  • It returns an ApiResponse object instead of a PSR-7 compliant ResponseInterface object.
  • Same as Views it allows methods based on HTTP method (ie. get, post, put, delete, etc) instead of only a process() method.

When creating API endpoints, they can be accessed at https://domain.com/api/<PACKAGE>/>ENDPOINT_ALIAS>. For example, once the above class is in place visit the URL within your web browser at: http://127.0.0.1/api/disaster/projects/retrieve?project_id=1

Replace the value of project_id with any valid id# that's in your database. This will return a JSON response providing details on the project.

For further information on the REST API please consult the REST APIs Made Easy page of the documentation.