Tutorials
Tutorial 2: REST API
A JSON API for blog posts, on SQLite: list, read, create, update and delete, with validation, proper status codes, and a token for the writes.
| Method and path | Token | Answer |
|---|---|---|
GET /api/posts |
the posts, newest first | |
GET /api/posts/{id} |
one post, or 404 | |
POST /api/posts |
yes | 201 and the new post, or 422 |
PUT /api/posts/{id} |
yes | the changed post |
DELETE /api/posts/{id} |
yes | 204 |
Prerequisites
#- PHP 8.2 or later, with the
pdo_sqliteextension (php -mlists your extensions) - Composer
Step 1: Create the app
#composer create-project taphra/skeleton my-api
cd my-apiThe skeleton's database is a SQLite file, app/Database/app.sqlite, created
on first use (see app/Config/databases.yml).
Step 2: The table
#Migrations live in app/Migrations/. A file is named
migration_<id>_<Description>.php and declares the class
Migrate_migration_<id>_<Description>; php taphra make:migration create posts table
writes an empty one with the current time as its id. Create
app/Migrations/migration_20261201000000_CreatePostsTable.php:
<?php
use Taphra\DatabaseConnection;
use Taphra\SchemaBuilder;
class Migrate_migration_20261201000000_CreatePostsTable
{
public function up(array $args): void
{
(new SchemaBuilder(DatabaseConnection::load('app_master')))->create('posts', function ($t) {
$t->id();
$t->string('title');
$t->text('body');
$t->timestamps();
});
}
public function down(array $args): void
{
(new SchemaBuilder(DatabaseConnection::load('app_master')))->dropIfExists('posts');
}
}The SchemaBuilder writes the right SQL for SQLite, MySQL, PostgreSQL and SQL Server. Run the migration:
php taphra migrate1 up migration(s) performed.Step 3: The DataStore
#A DataStore is the class for one table. Create
app/DataStores/PostDataStore.php:
<?php
namespace App\DataStores;
use Taphra\Traits\Timestamps;
class PostDataStore extends AppDataStore
{
use Timestamps; // sets created_at and updated_at
public $objectName = 'posts'; // the table
protected $fillable = ['title', 'body']; // the columns create() accepts
protected $casts = ['id' => 'int'];
}Step 4: Validation
#A FormRequest holds the rules for a request body. The framework fills it
from the JSON body (or form fields) of the request and hands it to the
action that asks for it. Create app/Requests/PostRequest.php:
<?php
namespace App\Requests;
use Taphra\FormRequest;
class PostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => 'required|min:3|max:255',
'body' => 'required',
];
}
}Step 5: The controller
#RestController gives JSON helpers: json(), created(), noContent() and
apiError(), which answers an RFC 7807 problem document. Create
app/Controllers/PostsController.php:
<?php
namespace App\Controllers;
use App\DataStores\PostDataStore;
use App\Requests\PostRequest;
use Taphra\RestController;
class PostsController extends RestController
{
// GET /api/posts
public function index(): string
{
return $this->json((new PostDataStore())->find([], 50, 0, 'id', 'DESC')->toArray());
}
// GET /api/posts/{id}
public function show(string $id): string
{
$post = PostDataStore::findById((int) $id);
return $post ? $this->json($post) : $this->apiError(404, 'Post not found');
}
// POST /api/posts
public function create(PostRequest $request): string
{
if ($denied = $this->denied()) {
return $denied;
}
if ($request->fails()) {
return $this->apiError(422, 'Validation failed', ['errors' => $request->errors()]);
}
$post = PostDataStore::create($request->validated());
return $this->created($post, '/api/posts/' . $post['id']);
}
// PUT /api/posts/{id}
public function update(PostRequest $request, string $id): string
{
if ($denied = $this->denied()) {
return $denied;
}
$post = PostDataStore::findById((int) $id);
if (!$post) {
return $this->apiError(404, 'Post not found');
}
if ($request->fails()) {
return $this->apiError(422, 'Validation failed', ['errors' => $request->errors()]);
}
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->save();
return $this->json($post);
}
// DELETE /api/posts/{id}
public function destroy(string $id): string
{
if ($denied = $this->denied()) {
return $denied;
}
$post = PostDataStore::findById((int) $id);
if (!$post) {
return $this->apiError(404, 'Post not found');
}
$post->delete();
return $this->noContent();
}
// A 401 answer unless the request carries "Authorization: Bearer <API_TOKEN>".
private function denied(): ?string
{
$token = (string) getenv('API_TOKEN');
$sent = preg_match('/^Bearer\s+(\S+)$/', $_SERVER['HTTP_AUTHORIZATION'] ?? '', $m) ? $m[1] : '';
if (strlen($token) < 32 || !hash_equals($token, $sent)) {
return $this->apiError(401, 'Send the API token as a bearer token.');
}
return null;
}
}The writes check a token instead of a session, so there are no cookies and no
CSRF token to send. A private method like denied() is never reachable from
a URL: only public methods are actions.
Step 6: Routes
#Replace app/Config/routes.yml with:
GET:
/health: health/index
/api/posts: posts/index
/api/posts/{id:\d+}: posts/show
POST:
/api/posts: posts/create
PUT:
/api/posts/{id:\d+}: posts/update
DELETE:
/api/posts/{id:\d+}: posts/destroy{id:\d+} matches digits and is passed to the action as $id. Because every
action that changes data has a POST, PUT or DELETE route, the other
methods get a 405, also on the /posts/destroy/1 form of the URL.
Step 7: The token
#app/bootstrap.php reads .env on every request. Put a random token there:
echo "API_TOKEN=$(php -r 'echo bin2hex(random_bytes(32));')" >> .envStep 8: Try it
#php taphra serveIn a second terminal, in the project folder, read the token into a shell variable, then create a post:
export API_TOKEN=$(grep '^API_TOKEN=' .env | cut -d= -f2)
curl -s -X POST http://127.0.0.1:8000/api/posts \
-H "Authorization: Bearer $API_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"title": "First post", "body": "Hello, Taphra!"}'{"id":1,"title":"First post","body":"Hello, Taphra!","created_at":"...","updated_at":"..."}List and read:
curl -s http://127.0.0.1:8000/api/posts[{"id":1,"title":"First post","body":"Hello, Taphra!","created_at":"...","updated_at":"..."}]curl -s http://127.0.0.1:8000/api/posts/1{"id":1,"title":"First post","body":"Hello, Taphra!","created_at":"...","updated_at":"..."}Update:
curl -s -X PUT http://127.0.0.1:8000/api/posts/1 \
-H "Authorization: Bearer $API_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"title": "First post, edited", "body": "Changed."}'{"id":1,"title":"First post, edited","body":"Changed.","created_at":"...","updated_at":"..."}Invalid input gets a 422 with the errors per field:
curl -s -X POST http://127.0.0.1:8000/api/posts \
-H "Authorization: Bearer $API_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"title": "Hi"}'{"type":"about:blank","title":"Unprocessable Entity","status":422,"detail":"Validation failed","errors":{"title":["The title must be at least 3."],"body":["The body field is required."]}}Without the token, a write gets a 401:
curl -s -X DELETE http://127.0.0.1:8000/api/posts/1{"type":"about:blank","title":"Unauthorized","status":401,"detail":"Send the API token as a bearer token."}A wrong method gets a 405 that names the allowed ones:
curl -s -o /dev/null -w '%{http_code} %header{allow}\n' -X PATCH http://127.0.0.1:8000/api/posts/1
curl -s -o /dev/null -w '%{http_code} %header{allow}\n' http://127.0.0.1:8000/posts/destroy/1405 GET, PUT, DELETE
405 DELETEDelete, then read again:
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE http://127.0.0.1:8000/api/posts/1 -H "Authorization: Bearer $API_TOKEN"
curl -s http://127.0.0.1:8000/api/posts/1204
{"type":"about:blank","title":"Not Found","status":404,"detail":"Post not found"}Validation rules
#| Rule | Example | Meaning |
|---|---|---|
required |
required |
present and not empty |
email |
email |
an email address |
min / max |
min:3, max:255 |
length of a string (or size of a number) |
integer |
integer |
a whole number |
in |
in:draft,published |
one of the listed values |
regex |
regex:/^[a-z-]+$/ |
matches the pattern |
Next steps
#composer create-project taphra/api-starter my-apigives you this API with user accounts, signed tokens (JWT), owner checks, rate limits and CORS.- A chat page on an AI model: Tutorial 3: AI chatbot