ActionAPI

php api backend

Traditional REST API uses methods like GET, POST, PATCH, DELETE along with data from the url to indicate what action is being performed.

I am using an alternate method that POSTs JSON to single endpoints. For example:

https://api.example.com/user
{
    "action": "addUser",
    "data": {
        "username": "bob"
    }
}

All data required to perform the action is included in the POSTed data. The response will contain the result of the operation:

HTTP STATUS 200 OK

{
    "user_id": 1   
}

OR

HTTP STATUS 4xx ERROR

{
    "error_message": "'bob' is a user already"
}

On the server side, I'm running Slim Framework

I'm routing requests posted to /user through to the UserController

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

$app = AppFactory::create();
$app->addRoutingMiddleware();
$errorMiddleware = $app->addErrorMiddleware(true, true, true);

$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});

$app->post('/user',\Controllers\UserController::class . ':do');

$app->run();

The controller is then interpretting the action and data from the received JSON and posting it to the appropriate Model Method.

<?php

namespace Controllers;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Models\User;

class UserController extends Controller{

    public function do(Request $request, Response $response ) {

        $user = new User();
        $body = json_decode($request->getBody(), true);

        switch ($body['action']){

            case "addUser":
                $result = $user->addUser($body['data']);
                break;

            case "deleteUser":
                $result = $user->deleteUser($body['data']);

        }

        return $this->withJson($response, $result);

    }

}