Documentation menu

Building an app

REST APIs

This page covers JSON APIs: RestController and its response helpers, routes bound to HTTP methods, request bodies through a FormRequest, output shaped by an ApiResource, error responses, and CrudController for standard resources. It assumes you know routing and validation.

Every PHP example below marked as runnable runs as written, in order, against SQLite.

Contents

#

The table for these examples

#

In an application the table comes from a migration (see Database). Here it is created directly:

PHP
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;

$schema = new SchemaBuilder(DatabaseConnection::load('app_master'));
$schema->dropIfExists('posts');
$schema->create('posts', function ($t) {
    $t->id();
    $t->string('title');
    $t->text('body')->nullable();
    $t->string('status', 20)->default('draft');
    $t->timestamps();
});
PHP
// app/DataStores/PostDataStore.php
namespace App\DataStores;

use Taphra\Traits\Timestamps;

class PostDataStore extends AppDataStore
{
    use Timestamps;

    public $objectName = 'posts';
    protected $fillable = ['title', 'body', 'status'];
}

JSON responses

#

An API controller extends Taphra\RestController. Each helper sets the status code and Content-Type: application/json; charset=utf-8, turns off view rendering, and returns the body; the action returns it.

Helper Response
json(mixed $data, int $status = 200) $data as JSON (unescaped slashes and Unicode)
created(mixed $data = null, string $location = '') 201, with a Location header when given
noContent() 204, empty body
resource(string $resourceClass, array|object $row, int $status = 200) one row through an ApiResource
collection(string $resourceClass, iterable $rows, int $status = 200) a JSON array of rows through an ApiResource
apiError(int $status, string $detail = '', array $extra = [], string $type = '', string $title = '') an RFC 7807 problem body (see Errors)

These helpers, like every method the base controller classes declare, are never URL actions: only the public methods your own controller declares are.

PHP
// app/Controllers/PostController.php
namespace App\Controllers;

use App\DataStores\PostDataStore;
use App\Requests\PostRequest;
use App\Resources\PostResource;
use Taphra\RestController;

class PostController extends RestController
{
    public function index(): string
    {
        $posts = PostDataStore::where('status', 'published')->orderBy('id')->get();
        return $this->collection(PostResource::class, $posts);
    }

    public function show(int $id): string
    {
        $post = PostDataStore::findById($id);
        if ($post === null) {
            return $this->apiError(404, "No post with id $id.");
        }
        return $this->resource(PostResource::class, $post);
    }

    public function store(PostRequest $request): string
    {
        if ($request->fails()) {
            return $this->apiError(422, 'The given data was invalid.', ['errors' => $request->errors()]);
        }
        $post = PostDataStore::create($request->validated());
        return $this->created((new PostResource($post))->toArray(), '/api/posts/' . $post['id']);
    }

    public function destroy(int $id): string
    {
        (new PostDataStore())->delete(['id' => $id]);
        return $this->noContent();
    }
}

Route parameters arrive as action arguments in order; a parameter typed with a FormRequest subclass is filled from the request instead (next sections).

Shaping output with ApiResource

#

An ApiResource maps one row to the array the API returns, so the table's columns are not exposed by accident. Implement transform(array $row): array; the constructor takes an array or a DataStoreRow.

PHP
// app/Resources/PostResource.php
namespace App\Resources;

use Taphra\ApiResource;

class PostResource extends ApiResource
{
    public function transform(array $row): array
    {
        return [
            'id'     => (int) $row['id'],
            'title'  => $row['title'],
            'status' => $row['status'],
            'links'  => ['self' => '/api/posts/' . $row['id']],
        ];
    }
}

Outside a controller: PostResource::make($row)->toArray(), PostResource::make($row)->toJson(), and PostResource::collection($rows) for a list (an array of arrays).

Routes bound to methods

#

Bind each API route to its HTTP method in app/Config/routes.yml. The method sections (GET:, POST:, PUT:, PATCH:, DELETE:) sit at the top level of the file; {id:\d+} captures a parameter that must match the pattern. The target post/show runs PostController::show().

app/Config/routes.yml
GET:
  /api/posts:              post/index
  /api/posts/{id:\d+}:     post/show
  /api/crud/posts:          postCrud/index
  /api/crud/posts/{id:\d+}: postCrud/show
POST:
  /api/posts:              post/store
  /api/crud/posts:          postCrud/store
PUT:
  /api/crud/posts/{id:\d+}: postCrud/update
DELETE:
  /api/posts/{id:\d+}:     post/destroy
  /api/crud/posts/{id:\d+}: postCrud/destroy

A request with another method on a declared path gets 405 Method Not Allowed with an Allow header listing the methods that path accepts. The /post/destroy convention URL is refused the same way for a GET, because the routes bind destroy to DELETE only. Binding every state-changing action to POST, PUT, PATCH or DELETE keeps links and <img> tags from reaching it.

Request bodies and FormRequest

#

A FormRequest declares the rules for one kind of input. Type-hint it on the action and the framework builds it from the request: query string, form fields, and a JSON body when Content-Type is application/json. Validation runs the first time you call fails(), errors() or validated(). validated() never returns input that failed: it throws a ValidationException (HTTP 422).

PHP
// app/Requests/PostRequest.php
namespace App\Requests;

use Taphra\FormRequest;

class PostRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'title'  => 'required|min:3|max:200',
            'body'   => 'nullable|max:10000',
            'status' => 'required|in:draft,published',
        ];
    }

    public function authorize(): bool
    {
        return true; // for example: return \Taphra\Auth::check();
    }
}
Method Returns
fails(): bool whether any rule failed
errors(): array messages per field, for example ['title' => ['...']]
validated(): array the input fields that have a rule, and only those (check fails() first: it does not throw)
all(): array, get(string $key, mixed $default = null), has(string $key): bool the raw merged input

When authorize() returns false the action does not run and the request ends with 403 Forbidden.

Taphra\Request::input() and the other Request accessors read the query string and form fields only. On the web entry a JSON body is decoded by a FormRequest; elsewhere read it with json_decode(file_get_contents('php://input'), true).

A JSON request against the routes above, sent in-process the way the testing helpers send it:

PHP
$created = docs_request('POST', '/api/posts',
    ['title' => 'Hello API', 'body' => 'First post.', 'status' => 'published'],
    ['Content-Type' => 'application/json'], json: true);

echo $created->getStatusCode(), "\n";            // 201
echo $created->getHeaderLine('Location'), "\n";  // /api/posts/1
echo $created->getBody(), "\n";
// {"id":1,"title":"Hello API","status":"published","links":{"self":"/api/posts/1"}}

(docs_request() is the helper these pages use to run examples; in your own tests use HttpTestCase.)

Reading it back, directly and through the API:

PHP
use App\DataStores\PostDataStore;
use App\Resources\PostResource;

$post = PostDataStore::findById(1);
echo PostResource::make($post)->toJson(), "\n";
// {"id":1,"title":"Hello API","status":"published","links":{"self":"/api/posts/1"}}

echo docs_request('GET', '/api/posts')->getBody(), "\n";
// [{"id":1,"title":"Hello API","status":"published","links":{"self":"/api/posts/1"}}]

Errors

#

apiError() answers with an RFC 7807 problem body. type defaults to about:blank and title to the standard phrase for the status; $extra is merged in.

PHP
$invalid = docs_request('POST', '/api/posts', ['title' => 'x'], ['Content-Type' => 'application/json'], json: true);

echo $invalid->getStatusCode(), "\n";   // 422
echo $invalid->getBody(), "\n";
// {"type":"about:blank","title":"Unprocessable Entity","status":422,"detail":"The given data was invalid.",
//  "errors":{"title":["The title must be at least 3."],"status":["The status field is required."]}}

echo docs_request('GET', '/api/posts/99')->getStatusCode(), "\n";      // 404 (from apiError)
echo docs_request('DELETE', '/api/posts')->getStatusCode(), "\n";      // 405
echo docs_request('GET', '/api/posts/99')->getHeaderLine('Content-Type'), "\n"; // application/json; charset=utf-8

Exceptions that reach the framework are answered by the app's error controller (AppErrorController), with the status taken from the exception:

Exception Status
Taphra\Exceptions\UnauthorizedException 401
Taphra\Exceptions\ForbiddenException (a failed CSRF check, authorize() returning false, a denied policy) 403
Taphra\Exceptions\NotFoundException, Taphra\Db\RecordNotFoundException (from findOrFail()), an unknown controller or action 404
Taphra\Exceptions\MethodNotAllowedException (a wrong method on a declared route) 405, with Allow
anything else 500, logged

For a request that sends Accept: application/json (or X-Requested-With: XMLHttpRequest), the body is JSON:

JSON
{"error": true, "message": "Not Found", "code": 404}

In production the message is generic (Not Found, Forbidden, or Internal Server Error for every other status) so file names and queries never reach the client; in development it is the exception's message. Other requests get the error404.tpl.php or error500.tpl.php view. In development, the debug page shows the exception instead (and answers with status 500). Catch the exceptions you expect and answer with apiError() when an API needs a precise message for them.

CRUD controllers

#

Taphra\CrudController implements the five actions of a resource on top of a DataStore, a FormRequest and an ApiResource. You name the three classes; the actions are ordinary public methods you can override.

Action Request Response
index() GET, with ?page=, ?search=, ?sort=, ?dir= 200, {"data": [...], "meta": {...}}
show($id) GET 200, the resource; 404 problem body when missing
store() POST 201, the created resource; 422 with errors on invalid input
update($id) PUT or PATCH 200, the updated resource; 404 or 422
destroy($id) DELETE 204; 404 when missing

CRUD controllers extend the app's own base class, App\Controllers\AppCrudController (a subclass of Taphra\CrudController, as AppController is for pages); the controllers make:crud writes extend it too. If your app does not have it yet, create it:

PHP
// app/Controllers/AppCrudController.php
namespace App\Controllers;

use Taphra\CrudController;

abstract class AppCrudController extends CrudController
{
}
PHP
// app/Controllers/PostCrudController.php
namespace App\Controllers;

use App\DataStores\PostDataStore;
use App\Requests\PostRequest;
use App\Resources\PostResource;

class PostCrudController extends AppCrudController
{
    protected function datastoreClass(): string   { return PostDataStore::class; }
    protected function formRequestClass(): string { return PostRequest::class; }
    protected function resourceClass(): string    { return PostResource::class; }

    protected function perPage(): int          { return 10; }
    protected function searchable(): array     { return ['title', 'body']; }
    protected function sortable(): array       { return ['id', 'title', 'created_at']; }
    protected function defaultSort(): string   { return 'id'; }
    protected function defaultSortDir(): string { return 'desc'; }

    protected function afterStore(array $row): void
    {
        // send a notification, clear a cache ...
    }
}

The other settings are indexConditions(): array (fixed WHERE conditions for index(), such as ['user_id' => Auth::id()]) and the hooks afterUpdate(array $row) and afterDestroy(array $row). ?search= runs a LIKE over the searchable() columns; ?sort= accepts only the sortable() columns. Search and sort are off while those lists are empty.

PHP
docs_request('POST', '/api/crud/posts', ['title' => 'Second', 'status' => 'draft'],
    ['Content-Type' => 'application/json'], json: true);

$list = json_decode((string) docs_request('GET', '/api/crud/posts?search=Second')->getBody(), true);
print_r($list['meta']);
// [total => 1, per_page => 10, current_page => 1, last_page => 1, has_more => false]

$updated = docs_request('PUT', '/api/crud/posts/2', ['title' => 'Second, edited', 'status' => 'published'],
    ['Content-Type' => 'application/json'], json: true);
echo $updated->getBody(), "\n";
// {"id":2,"title":"Second, edited","status":"published","links":{"self":"/api/posts/2"}}

echo docs_request('DELETE', '/api/crud/posts/2')->getStatusCode(), "\n";   // 204
echo docs_request('GET', '/api/crud/posts/2')->getStatusCode(), "\n";      // 404

meta carries the pagination numbers only; the rows in data always go through the ApiResource. update() and destroy() address the row by the key read from the database, never by the raw URL value.

Generating a resource with make:crud

#
Shell
php taphra make:crud Post
php taphra make:crud Post --table=blog_posts

It writes four files, each a starting point to fill in:

Text
app/DataStores/PostDataStore.php       $objectName, commented $fillable and $casts
app/Requests/PostFormRequest.php       empty rules(), authorize() returning true
app/Resources/PostResource.php         transform() returning the id
app/Controllers/PostCrudController.php the three class names

Then:

  1. Make sure the app has AppCrudController (above).
  2. Fill in $fillable, the rules and transform().
  3. Add the routes. The command prints a list of paths without HTTP methods (/posts/store, /posts/:id/update ...); bind them to methods instead, as in Routes bound to methods, so a GET cannot reach store(), update() or destroy().

OpenAPI from annotations

#

php taphra route:openapi writes an OpenAPI 3.0.3 description of the actions that carry @Api* docblock annotations, read from every PHP file under app/Controllers/:

PHP
// app/Controllers/PostController.php (annotated)
/**
 * @ApiTag("Posts")
 * @ApiRoute(method="POST", path="/api/posts", summary="Create a post")
 * @ApiResponse(status=201, description="Created")
 * @ApiResponse(status=422, description="Invalid input")
 * @ApiSecurity("bearerAuth")
 */
public function store(PostRequest $request): string
Shell
php taphra route:openapi                                  # docs/openapi.yaml
php taphra route:openapi --format=json --output=public/openapi.json --title="Blog API"

The annotations are @ApiRoute(method, path, summary), @ApiParam(name, in, type, required, description), @ApiResponse(status, description), @ApiBody(description, required), @ApiTag("...") and @ApiSecurity("bearerAuth"). When an action takes a FormRequest and has no @ApiBody, its rules() become the request body schema: required fields are listed as required, min/max become minLength/maxLength and in: an enum. Actions without @ApiRoute are left out; the routes file is not read.

Authentication and CSRF for APIs

#

RestController does not check CSRF tokens (the skeleton turns the check on for AppController, the base of its HTML pages). That suits APIs that authenticate each request with a token, such as a JWT in the Authorization header: a browser does not add that header on its own. An API that relies on the session cookie instead must check a token, either by setting protected $autoVerifyCsrf = true; on its controllers or with the double-submit cookie. Both are in Security.

Protect routes with AuthMiddleware or a JWT middleware in a route group; see Authentication.