Table of Contents
What you will read?
Silex is a lightweight PHP micro-framework built on Symfony components, ideal for building fast and simple REST APIs. Creating a REST API in Silex helps developers structure clean endpoints and deliver JSON responses efficiently.
Step 1: Install Silex
To start building your REST API, first install the lightweight Silex framework using Composer, which provides a simple and flexible foundation for your application.
mkdir silex-api && cd silex-api
composer require silex/silex
Step 2: Create the Main Application File
To initialize your Silex REST API, create a main index.php file that will handle application setup, routes, and responses for all API requests.
<?php
require_once __DIR__.'/vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
Step 3: Define REST API Routes
To make your API functional, define routes that handle different HTTP methods such as GET, POST, PUT, and DELETE to manage resources efficiently.
$app->get('/users', function() {
return json_encode(['users' => ['John', 'Mary', 'Alex']]);
});
$app->post('/users', function() {
return json_encode(['message' => 'User added successfully']);
});
Step 4: Handle PUT and DELETE Requests
To make your REST API complete and fully functional, add routes that handle PUT and DELETE requests for updating and removing specific resources.
$app->put('/users/{id}', function($id) {
return json_encode(['message' => "User {$id} updated"]);
});
$app->delete('/users/{id}', function($id) {
return json_encode(['message' => "User {$id} deleted"]);
});
Step 5: Run the Application
To test your REST API and ensure all routes work correctly, start the built-in PHP development server and access your endpoints in a browser or API tool.
php -S localhost:8000 -t .