PHP Classes

Learn How to Implement a Real API with the PHP REST API Example Package Luminova REST API Example: Implements an example of a REST API

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-11-25 (5 days ago) RSS 2.0 feedNot enough user ratingsTotal: 10 This week: 10All time: 11,457 This week: 6Up
Version License PHP version Categories
luminova-rest-api-ex 3.0MIT/X Consortium ...8.0Libraries, Web services, Design Patterns, P..., A...
Description 

Author

This package implements an example of a REST API.

It provides an example script that calls the Luminova framework to define the URL route patterns that the API application implements.

The package example also shows how to call the Luminova API to process the HTTP requests routing requests to the controller classes that implement the API call actions.

This example shows how to preview the presentation of blog posts with images from either the command line console or using HTTP requests:

- Command line console: displays the post image as ASCII art using the Luminova CLI Image Art module, rendering the image as pixel-based characters.

- HTTP requests: Provides a browsable image URL, routed through the CDN handler method for efficient content delivery.

Picture of Ujah Chigozie peter
  Performance   Level  
Name: Ujah Chigozie peter <contact>
Classes: 29 packages by
Country: Nigeria Nigeria
Innovation award
Innovation award
Nominee: 11x

Example

<?php
/**
 * Luminova Framework Index front controller.
 *
 * @package Luminova
 * @author Ujah Chigozie Peter
 * @copyright (c) Nanoblock Technology Ltd
 * @license See LICENSE file
*/
declare(strict_types=1);

use \
Luminova\Boot;
// use \Luminova\Routing\Prefix;
// use \App\Controllers\Errors\ViewErrors;

require_once __DIR__ . '/../system/Boot.php';

/**
 * Ensure that we are in front controller while running script in cli mode
 */
if (getcwd() . DIRECTORY_SEPARATOR !== FRONT_CONTROLLER) {
   
chdir(FRONT_CONTROLLER);
}

/**
 * FOR ATTRIBUTE ROUTING
 *
 * Load application route context based on PHP attribute routing.
 */
Boot::http()->router->context()->run();

/**
 * FOR NON ATTRIBUTE ROUTING
 *
 * Load application route context based on method-based routing.
 * Uncomment this below code if using method-based routing (Non-Attribute).
 *
 * @see /routes/web.php - Main web-pages routes
 * @see /routes/api.php - APIs routes
 * @see /routes/cli.php - CLI routes
 */
/*
Boot::http()->router->context(
    [
        'prefix' => Prefix::WEB,
        'error' => [ViewErrors::class, 'onWebError']
    ],
    [
        'prefix' => Prefix::API,
        'error' => [ViewErrors::class, 'onRestError']
    ],
    [
        'prefix' => Prefix::CLI
    ]
)->run();*/


Details

PHP Luminova Framework RESTful API Example

Luminova Logo

Introduction

This repository provides a comprehensive example of building a RESTful API using the Luminova PHP framework, showcasing both HTTP and CLI implementations. The example is designed to help developers understand how to create APIs that support full CRUD operations (Create, Read, Update, Delete) and handle various HTTP methods such as GET, POST, PUT, and DELETE. It also supports secure content delivery through the Luminova\Storages\FileDelivery class. This feature enables serving images stored in private directories directly via URL access, eliminating the need for creating symbolic links (symlinks).

In addition to HTTP-based API endpoints, this example also demonstrates the power of Luminova's command-line tools, making it possible to perform API-related tasks directly via the CLI. Whether you're looking to seed your database, manage user tokens, or perform backend operations, this repository covers it all.

By following the provided steps, you can quickly set up an API infrastructure, learn best practices for working with Luminova, and explore features like database migrations, API client authentication, and middleware for rate-limiting or token validation.

This project is ideal for developers aiming to: - Build scalable and secure APIs for web and mobile applications. - Explore the seamless integration of HTTP and CLI workflows. - Learn Luminova's approach to rapid API development and management.

Source Files Highlight

Below is an overview of the primary files involved in the API implementation, organized by functionality and purpose. Each file plays a critical role in building a RESTful API using the Luminova PHP framework.

Controllers

Controllers handle HTTP and CLI requests, providing routes and business logic for the API.

HTTP Controllers

  • App\Controllers\Http\RestController Implements the core API endpoints for CRUD operations. This class handles user authentication, input validation, and database interaction for the `/api/v1/posts` route.
  • App\Controllers\Http\Welcome Serves as the main page controller, providing access to the API's landing page. It also manages private file delivery via the `Luminova\Storages\FileDelivery` class.

CLI Controller

Database

Migrations

Define the database schema for the API's core entities. - App\Database\Migrations\PostsMigration Defines the schema for the posts table, including fields for title, body, and relationships with users.

Seeders

Populate the database with initial data. - App\Database\Seeders\PostsSeeder Inserts sample post data for testing and development purposes.

Models

Models provide a programmatic interface for interacting with the database tables. - App\Models\Posts Represents the posts table, including relationships to users and validation logic for creating or updating posts.

  • App\Models\Users Represents the `users` table, managing user-specific operations such as authentication and role assignments.

Configuration

  • App\Config\Apis Central configuration file for defining HTTP API-related behaviors, such as `allowCredentials`, `allowOrigins`, and `allowHeaders`.

Installation

Clone the Repository

Clone the repository using Git or download the files directly from GitHub:

cd your-project-path
git clone https://github.com/luminovang/luminova-rest-api-example.git

Install Dependencies

Navigate to the project directory and update the Composer dependencies:

composer update

Database Configuration

Configure your MySQL socket path in the .env file:

database.mysql.socket.path = /var/mysql/mysql.sock

Start the Development Server

Use the Luminova built-in development server or a third-party server such as XAMPP or WAMPP.

Manage the Database

Run Migrations

Apply database migrations to create the required tables:

php novakit db:migrate

Seed the Database

Populate the database with sample data:

php novakit db:seed

Create an API Client Account

Generate an API token for your client:

Example:

cd public
php index.php posts key --user-id=1 --quota=1000 --expiry=3600

Copy the generated API token for use with API tools like Postman or curl.

CURL API HTTP Request Example

Method GET

Retrieve all post contents.

curl --location 'https://localhost/your-project-path/public/api/v1/posts' \
--header 'X-Api-Client-Id: <your-client-id>' \
--header 'Authorization: <your-api-token>'

For more examples and details, refer to the documentation in this repository.

Method GET

Retrieve a single post content by id.

curl --location 'https://localhost/your-project-path/public/api/v1/posts/<post-id>' \
--header 'X-Api-Client-Id: <your-client-id>' \
--header 'Authorization: <your-api-token>'

Method POST

Create a new post with an optional image.

curl --location 'https://localhost/your-project-path/public/api/v1/posts/create' \
--header 'X-Api-Client-Id: <your-client-id>' \
--header 'Authorization: <your-api-token>' \
--form 'body="{
    \"userId\": 10, 
    \"title\": \"This a test new title\", 
    \"body\": \"New Body content\"
}"' \
--form 'image=@"/Path/To/Images/image.png"'

Method PUT

Update a existing post with an optional image.

curl --location --request PUT 'https://localhost/your-project-path/public/api/v1/posts/update/<post-id>' \
--header 'X-Api-Client-Id: <your-client-id>' \
--header 'Authorization: <your-api-token>' \
--form 'body="{
    \"title\": \"New Update a test new title\", 
    \"body\": \"New Update Body content\"
}"'

Method PUT

Delete a existing post.

curl --location --request DELETE 'https://localhost/your-project-path/public/api/v1/posts/delete/<post-id>' \
--header 'X-Api-Client-Id: <your-client-id>' \
--header 'Authorization: <your-api-token>'

API CLI Request Example

Sample

First navigate to public directory of your project.

Users

Lists users with optional pagination.

php index.php posts users --limit=10 --offset=0

Posts

Lists posts with optional pagination.

php index.php posts list --limit=2

For more, run help command to show all available post commands:

php index.php posts --help

  Files folder image Files (119)  
File Role Description
Files folder imageapp (1 file, 6 directories)
Files folder imagebootstrap (3 files)
Files folder imagepublic (3 files, 1 directory)
Files folder imageresources (1 directory)
Files folder imageroutes (3 files)
Files folder imagesamples (1 directory)
Files folder imagesystem (1 file, 3 directories)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file index.php Aux. Configuration script
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file novakit Example Example script
Accessible without login Plain text file phpstan.includes.php Aux. Configuration script
Accessible without login Plain text file phpstan.neon Data Auxiliary data
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Plain text file rector.php Class Class source

  Files folder image Files (119)  /  app  
File Role Description
Files folder imageConfig (20 files, 1 directory)
Files folder imageControllers (3 directories)
Files folder imageDatabase (2 directories)
Files folder imageLanguages (2 files)
Files folder imageModels (2 files)
Files folder imageUtils (2 files)
  Plain text file Application.php Class Class source

  Files folder image Files (119)  /  app  /  Config  
File Role Description
Files folder imageTemplates (2 directories)
  Plain text file AI.php Class Class source
  Plain text file Apis.php Class Class source
  Plain text file Browser.php Class Class source
  Plain text file ContentSecurityPolicy.php Class Class source
  Plain text file Cookie.php Class Class source
  Plain text file Cron.php Class Class source
  Plain text file Database.php Class Class source
  Plain text file Encryption.php Class Class source
  Plain text file Files.php Class Class source
  Plain text file IPConfig.php Class Class source
  Plain text file Logger.php Class Class source
  Plain text file Mailer.php Class Class source
  Accessible without login Plain text file Modules.php Aux. Configuration script
  Accessible without login Plain text file Schema.php Aux. Configuration script
  Plain text file Security.php Class Class source
  Plain text file Services.php Class Class source
  Plain text file Session.php Class Class source
  Plain text file Sitemap.php Class Class source
  Accessible without login Plain text file Storage.php Aux. Configuration script
  Plain text file Template.php Class Class source

  Files folder image Files (119)  /  app  /  Config  /  Templates  
File Role Description
Files folder imageSmarty (2 files)
Files folder imageTwig (9 files)

  Files folder image Files (119)  /  app  /  Config  /  Templates  /  Smarty  
File Role Description
  Plain text file Classes.php Class Class source
  Plain text file Modifiers.php Class Class source

  Files folder image Files (119)  /  app  /  Config  /  Templates  /  Twig  
File Role Description
  Plain text file Extensions.php Class Class source
  Plain text file Filters.php Class Class source
  Plain text file Functions.php Class Class source
  Plain text file Globals.php Class Class source
  Plain text file NodeVisitors.php Class Class source
  Plain text file Operators.php Class Class source
  Plain text file Rot13Provider.php Class Class source
  Plain text file Tests.php Class Class source
  Plain text file TokenParsers.php Class Class source

  Files folder image Files (119)  /  app  /  Controllers  
File Role Description
Files folder imageCli (1 file)
Files folder imageErrors (1 file)
Files folder imageHttp (2 files)

  Files folder image Files (119)  /  app  /  Controllers  /  Cli  
File Role Description
  Plain text file PostsCommand.php Class Class source

  Files folder image Files (119)  /  app  /  Controllers  /  Errors  
File Role Description
  Plain text file ViewErrors.php Class Class source

  Files folder image Files (119)  /  app  /  Controllers  /  Http  
File Role Description
  Plain text file RestController.php Class Class source
  Plain text file Welcome.php Class Class source

  Files folder image Files (119)  /  app  /  Database  
File Role Description
Files folder imageMigrations (2 files)
Files folder imageSeeders (2 files)

  Files folder image Files (119)  /  app  /  Database  /  Migrations  
File Role Description
  Plain text file PostsMigration.php Class Class source
  Plain text file UserMigration.php Class Class source

  Files folder image Files (119)  /  app  /  Database  /  Seeders  
File Role Description
  Plain text file PostsSeeder.php Class Class source
  Plain text file UserSeeder.php Class Class source

  Files folder image Files (119)  /  app  /  Languages  
File Role Description
  Accessible without login Plain text file App.en.php Aux. Configuration script
  Accessible without login Plain text file App.fr.php Aux. Configuration script

  Files folder image Files (119)  /  app  /  Models  
File Role Description
  Plain text file Posts.php Class Class source
  Plain text file Users.php Class Class source

  Files folder image Files (119)  /  app  /  Utils  
File Role Description
  Plain text file Functions.php Class Class source
  Accessible without login Plain text file Global.php Aux. Configuration script

  Files folder image Files (119)  /  bootstrap  
File Role Description
  Accessible without login Plain text file constants.php Example Example script
  Accessible without login Plain text file features.php Aux. Configuration script
  Plain text file functions.php Class Class source

  Files folder image Files (119)  /  public  
File Role Description
Files folder imageassets (1 directory)
  Accessible without login Image file favicon.png Icon Icon image
  Accessible without login Plain text file index.php Example Example script
  Accessible without login Plain text file robots.txt Data Robots blocking configuration

  Files folder image Files (119)  /  public  /  assets  
File Role Description
Files folder imagecss (1 file)

  Files folder image Files (119)  /  public  /  assets  /  css  
File Role Description
  Accessible without login Plain text file app.css Data Auxiliary data

  Files folder image Files (119)  /  resources  
File Role Description
Files folder imageViews (4 files, 1 directory)

  Files folder image Files (119)  /  resources  /  Views  
File Role Description
Files folder imagesystem_errors (13 files)
  Accessible without login Plain text file 404.php Example Example script
  Accessible without login Plain text file index.php Aux. Configuration script
  Accessible without login Plain text file index.tpl Data Auxiliary data
  Accessible without login Plain text file index.twig Data Auxiliary data

  Files folder image Files (119)  /  resources  /  Views  /  system_errors  
File Role Description
  Accessible without login Plain text file 404.php Aux. Configuration script
  Accessible without login Plain text file api.php Example Example script
  Plain text file cli.php Class Class source
  Accessible without login Plain text file debug.css Data Auxiliary data
  Accessible without login Plain text file errors.php Example Example script
  Accessible without login Plain text file info.php Aux. Configuration script
  Accessible without login Plain text file mailer.php Example Example script
  Accessible without login Plain text file maintenance.css Data Auxiliary data
  Accessible without login Plain text file maintenance.php Aux. Configuration script
  Accessible without login Plain text file remote.php Example Example script
  Accessible without login Plain text file tracer.php Example Example script
  Accessible without login Plain text file tracing.php Example Example script
  Plain text file view.error.php Class Class source

  Files folder image Files (119)  /  routes  
File Role Description
  Accessible without login Plain text file api.php Example Example script
  Accessible without login Plain text file cli.php Example Example script
  Accessible without login Plain text file web.php Example Example script

  Files folder image Files (119)  /  samples  
File Role Description
Files folder imageapp (1 directory)

  Files folder image Files (119)  /  samples  /  app  
File Role Description
Files folder imageConfig (4 files)

  Files folder image Files (119)  /  samples  /  app  /  Config  
File Role Description
  Plain text file Cron.php Class Class source
  Plain text file Files.php Class Class source
  Plain text file Logger.php Class Class source
  Plain text file Mailer.php Class Class source

  Files folder image Files (119)  /  system  
File Role Description
Files folder imageComposer (3 files)
Files folder imageDebugger (3 files)
Files folder imageplugins (1 file, 2 directories)
  Plain text file Boot.php Class Class source

  Files folder image Files (119)  /  system  /  Composer  
File Role Description
  Plain text file BaseComposer.php Class Class source
  Plain text file Builder.php Class Class source
  Plain text file Updater.php Class Class source

  Files folder image Files (119)  /  system  /  Debugger  
File Role Description
  Plain text file Performance.php Class Class source
  Plain text file PHPStanRules.php Class Class source
  Plain text file Tracer.php Class Class source

  Files folder image Files (119)  /  system  /  plugins  
File Role Description
Files folder imagecomposer (11 files)
Files folder imagepsr (1 directory)
  Accessible without login Plain text file autoload.php Aux. Configuration script

  Files folder image Files (119)  /  system  /  plugins  /  composer  
File Role Description
  Accessible without login Plain text file autoload_classmap.php Aux. Configuration script
  Accessible without login Plain text file autoload_namespaces.php Aux. Configuration script
  Accessible without login Plain text file autoload_psr4.php Aux. Configuration script
  Plain text file autoload_real.php Class Class source
  Plain text file autoload_static.php Class Class source
  Plain text file ClassLoader.php Class Class source
  Accessible without login Plain text file installed.json Data Auxiliary data
  Accessible without login Plain text file installed.php Aux. Configuration script
  Plain text file InstalledVersions.php Class Class source
  Accessible without login Plain text file LICENSE Lic. License text
  Accessible without login Plain text file platform_check.php Aux. Configuration script

  Files folder image Files (119)  /  system  /  plugins  /  psr  
File Role Description
Files folder imagelog (3 files, 1 directory)

  Files folder image Files (119)  /  system  /  plugins  /  psr  /  log  
File Role Description
Files folder imagePsr (1 directory)
  Accessible without login Plain text file composer.json Data Auxiliary data
  Accessible without login Plain text file LICENSE Lic. License text
  Plain text file README.md Class Class source

  Files folder image Files (119)  /  system  /  plugins  /  psr  /  log  /  Psr  
File Role Description
Files folder imageLog (8 files, 1 directory)

  Files folder image Files (119)  /  system  /  plugins  /  psr  /  log  /  Psr  /  Log  
File Role Description
Files folder imageTest (3 files)
  Plain text file AbstractLogger.php Class Class source
  Plain text file InvalidArgumentException.php Class Class source
  Plain text file LoggerAwareInterface.php Class Class source
  Plain text file LoggerAwareTrait.php Class Class source
  Plain text file LoggerInterface.php Class Class source
  Plain text file LoggerTrait.php Class Class source
  Plain text file LogLevel.php Class Class source
  Plain text file NullLogger.php Class Class source

  Files folder image Files (119)  /  system  /  plugins  /  psr  /  log  /  Psr  /  Log  /  Test  
File Role Description
  Plain text file DummyTest.php Class Class source
  Plain text file LoggerInterfaceTest.php Class Class source
  Plain text file TestLogger.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:10
This week:10
All time:11,457
This week:6Up