PHP Luminova: Build a REST API for Blog Posts
Define API routes, prepare post models and database tables, and implement JSON CRUD handlers.
Start with a development database and choose one routing style. Add the model and migration before testing the handlers. Connect the authentication middleware to your application before exposing write routes. See the HTTP Request Routing.
For a working implementation and source code, check out the Luminova HTTP and CLI REST API Examples on GitHub.
Requirements
Before starting, ensure you have:
- Luminova PHP Framework installed.
- A working database (e.g., MySQL).
Step 1: Define API Routes
Routes map client requests to specific controller actions. In Luminova, routes can be defined using method-based or attribute-based routing.
Attribute-Based Routing
With attribute-based routing, routes are defined directly on controller methods using PHP attributes.
// /app/Controllers/Http/RestController.php
namespace App\Controllers\Http;
use Luminova\Security\JWT;
use Luminova\Attributes\Route;
use Luminova\Attributes\Prefix;
use App\Errors\Controllers\AppError;
use Luminova\Base\Http\AbstractController;
#[Prefix(
pattern: '/api/v1/(:root)',
onError: [AppError::class, 'onRestError']
)]
class RestController extends AbstractController
{
#[Route(
'/api/v1/posts/(:root)',
methods: ['ANY'],
middleware: Route::BEFORE_MIDDLEWARE
)]
public function middleware(): int
{
if (
$this->request->isAuth('Bearer')
&& JWT::getInstance()->validate(
$this->request->getAuth(),
$this->request->header->get('X-Client-Id')
)
) {
return STATUS_SUCCESS;
}
http_response_code(401);
return STATUS_ERROR;
}
#[Route('/api/v1/', methods: ['ANY'])]
public function index(): int {}
#[Route('/api/v1/posts/create', methods: ['POST'])]
public function create(): int {}
#[Route('/api/v1/posts/(:?int)', methods: ['GET'])]
public function read(?int $postId = null): int {}
#[Route('/api/v1/posts/update/(:int)', methods: ['PUT'])]
public function update(int $postId): int {}
#[Route('/api/v1/posts/delete/(:int)', methods: ['DELETE'])]
public function delete(int $postId): int {}
}- Attributes: Define routes directly in the controller, specifying HTTP methods and additional configurations like middleware.
- Prefix Handling: Routes are scoped under
/api/v1/, with a global error handler for non-existent endpoints.
Method-Based Routing
Routes are defined in the /routes/api.php file using method chaining, and linked to corresponding controller methods.
// /routes/api.php
use Luminova\Routing\Router;
use App\Errors\Controllers\AppError;
Router::onError(
[AppError::class, 'onRestError'], '/api/v1/(:root)'
);
// Api endpoints index
Router::any('/api/v1/(:root)', 'RestController::index');
Router::bind('/v1/posts', static function() {
Router::middleware(
Router::ANY_METHOD,
'/(:root)',
'RestController::middleware'
);
// CRUD routes for posts
// Retrieve all posts
// Retrieve a specific post by ID
Router::get('/(:?int)', 'RestController::read');
// Create a new post
Router::post('/create', 'RestController::create');
// Update an existing post
Router::put('/update/(:int)', 'RestController::update');
// Delete a post by ID
Router::delete('/delete/(:int)', 'RestController::delete');
});- Middleware: Protects the routes with authentication.
- Index handling: Maps the API root to the
indexmethod. Configure the error handler separately for unmatched paths.
Method-Based Routing Index Controller
In your index.php context method, add routes prefixes to handle API endpoint request as below:
// /public/index.php
Boot::http()->router->context([
Prefix::with(Prefix::API, [AppError::class, 'onTrigger']),
Prefix::with(Prefix::WEB, [AppError::class, 'onTrigger']),
Prefix::with(Prefix::CLI),
])->run();Step 2: Define the Models
Posts Model:
The model represents the Posts entity and interacts with the database.
// /app/Models/Posts.php
namespace App\Models;
use Luminova\Base\Database\AbstractModel;
class Posts extends AbstractModel
{
protected string $table = 'posts';
protected string $primaryKey = 'pid';
protected bool $cacheable = true;
}Users Model:
The model represents the Users entity and interacts with the database.
// /app/Models/Users.php
namespace App\Models;
use Luminova\Base\Database\AbstractModel;
class Users extends AbstractModel
{
protected string $table = 'users';
protected string $primaryKey = 'user_id';
protected bool $cacheable = false;
}Step 3: Database Management
1. Create the Database Migration Class:
Define your database migration table blueprint.
// /app/Database/Migrations/PostsMigration.php
namespace App\Database\Migrations;
use Luminova\Database\Table;
use Luminova\Database\Schema;
use Luminova\Database\Migration;
class PostsMigration extends Migration
{
/**
* Defines the 'posts' table structure.
*/
public function up(): bool
{
return Schema::create('posts', function (Table $table) {
$table->prettify = true;
$table->database = Table::SQLITE;
$table->id('pid');
$table->uuid('post_uuid')->nullable(false)->unique();
$table->integer('user_id', 5)->nullable(false);
$table->string('post_title')->nullable(false);
$table->string('post_image')->nullable();
$table->text('post_body')->nullable(false);
$table->timestamps();
return $table;
});
}
public function down(): bool
{
return Schema::dropIfExists('posts');
}
public function alter(): bool
{
return true;
}
}2. Create the Table Seeder Class:
Add seed data to populate your posts table.
// /app/Database/Seeder/PostsSeeder.php
namespace App\Database\Seeders;
use function Luminova\Funcs\uuid;
use Luminova\Database\Seeder;
use Luminova\Database\Query\Builder;
class PostsSeeder extends Seeder
{
/**
* Inserts sample data into 'posts' table.
*/
public function run(Builder $builder): int
{
return $builder->from('posts')->insert([
[
'post_uuid' => uuid(),
'user_id' => 101,
'post_title' => 'Getting Started with PHP Luminova',
'post_body' => 'Learn the basics of setting up and running your first project with PHP Luminova framework.',
],
// Additional seed data
]);
}
}3. Configure Database Connection:
Set up your database configuration in the .env file. Here, SQLITE is used as an example.
# /.env
database.connection = PDO
database.pdo.engine = sqlite
database.development.sqlite.path = writeable/database/development.sqlite
database.mysql.socket = true
database.mysql.socket.path = /var/mysql/mysql.sockNote:The
socketconfiguration is needed for database access on the command line.Adjust the socket path based on your environment.
4. Run Migrations and Seeders:
Once configured, run migrations first:
php novakit db:migrate --class=PostsMigrationAfter a successful migration, seed the database:
php novakit db:seed --class=PostsSeederStep 4: Implement Controller Methods
Each method in the RestController class corresponds to a specific CRUD operation, processing incoming API requests and interacting with the Post model.
middleware
Middleware Authentication
The middleware() method in the route setup checks the bearer token before allowing a posts handler to run. Set POSTS_API_TOKEN in the server environment before testing, and send the same value in the Authorization: Bearer … header. Missing or invalid credentials cause a 401 response. Use HTTPS when sending the token outside local development.
index
Handle Invalid API Endpoints
Processes requests to the API root or invalid endpoints.
public function index(): int {}- HTTP Method:
ANY /api/v1/{invalid} - Functionality:
- Renders a
401 Unauthorizedresponse for invalid or missing endpoints.
- Renders a
read
Retrieve a Single Post
Fetches a specific post by ID from the URL, e.g., GET /api/v1/posts/2.
public function read(?int $postId = null): int {}- HTTP Method:
GET /api/v1/posts/{id} - Functionality:
- Retrieves a post by its ID.
- Returns:
200 OKwith the post data if found.204 No Contentif the post does not exist.
Real All Post
Retrieve All Posts
Retrieves a paginated list of posts. Use query parameters for pagination, e.g., GET /api/v1/posts?limit=10&offset=2.
public function read(?int $postId = null): int {}- HTTP Method:
GET /api/v1/posts - Functionality:
- Fetches all posts from by omitting the Post ID URI segment.
- Returns:
200 OKwith a list of posts if they exist.204 No Contentif no posts are available.
- Includes a
GETlink in each response item for easier navigation.
create
Create a New Post
Creates a new post using the data provided in the request body.
public function create(): int {}- HTTP Method:
POST /api/v1/posts/create - Functionality:
- Accepts
imageandbodycontaining JSON keystitle,bodyanduserId. - Inserts a new post into the database.
- Returns:
200 OKif the post is created successfully.- Relevant error codes for validation or server errors.
- Accepts
- Validation:
- Ensures
title,body, anduserIdare provided and meet the required criteria.
- Ensures
update
Update an Existing Post
Updates an existing post by ID, using data from the request body.
public function update(int $postId): int {}- HTTP Method:
PUT /api/v1/posts/{post_id} - Functionality:
- Requires request body
bodya JSON with optionaltitleandcontentfields. - Updates the specified post in the database.
- Returns:
200 OKif the update is successful.- An error message if the update fails.
- Requires request body
delete
Delete a Post
Deletes a specific post by its ID.
public function delete(int $postId): int {}- HTTP Method:
DELETE /api/v1/posts/delete/{post_id} - Functionality:
- Removes the post with the given ID from the database.
- Returns:
204 No Contentif the deletion is successful.- An error message if the operation fails.