How to Create REST API in Silex

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 .

Share:

More Posts

How to Install Maven on macOS 2025

What you will read?1 Check for Java Installation2 Install Homebrew (If Not Installed)3 Install Maven via Homebrew4 Verify Environment Variables (Optional)5 Create a Sample Maven

How to Use Google SMTP Server

What you will read?1 Step 1: Enable SMTP Access in Gmail2 Step 2: Secure Connection with TLS3 Step 3: Send an Email via SMTP4 Step

how to install wine on RHEL

What you will read?1 Check RHEL version and CPU architecture2 Update system and install base tools3 Verify subscription and enable CodeReady Builder4 Enable EPEL repository5

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments