Create Simple REST API using PHP

Create a Simple HTTP REST API using PHP Slim framework and MySQL database with JSON response!

GitHub Project:

The Purpose of the project

Create a Simple HTTP REST API using PHP Slim framework and MySQL database

Get Started

Add you MySQL database credentials Go to index.php on line 17

$dsn = 'mysql:host=localhost;dbname=dbName;charset=utf8'; // replace Localhost with your mysql host ip and replace dbName with your database name
$usr = 'dbUSERNAME'; //replace dbUSERNAME with your database username
$pwd = 'dbPASSWORD'; //replace dbUSERNAME with your database password

API Routes definitions

Go to the folder Routes:

Example: category.php

To handle a GET request

$app->get('/api/contents', function ($request, $response, $args) {  //GET example
    $pdo =$this->pdo;
$selectStatement = $pdo->select()
$stmt = $selectStatement->execute();
$categories = $stmt->fetchAll();
	$res['success'] = true;
$res['data'] = $categories;
$pdo = null;
return $response;

To handle a POST resquest

$app->post('/api/category', function ($request, $response, $args) { //POST example
 	$pdo =$this->pdo;
$params = $request->getParsedBody();
$categoryName = $params['categoryName'];
$color = $params['color'];
$active = $params['active'];
    $icon = '';
$files = $request->getUploadedFiles();
if (!empty($files['icon'])) {
$newfile = $files['icon'];
if ($newfile->getError() === UPLOAD_ERR_OK) {
$newName = str_replace(' ','', $newfile->getClientFilename());
$uploadFileName = md5($newName. time()).'.'.pathinfo($newName, PATHINFO_EXTENSION);
$icon = $uploadFileName;
    $insertStatement = $pdo->insert(array( 'name', 'color', 'icon', 'active' ))
->values(array($categoryName, $color, $icon, $active));
$insert = $insertStatement->execute();
	$pdo = null;

What is REST?

An architectural style called REST (Representational State Transfer) advocates that web applications should use HTTP as it was originally envisioned. Lookups should use GETrequests. PUT, POST, and DELETE requests should be used for creation, mutation, and deletion.

What is meant by the term “RESTful API”?

An API can be considered “RESTful” if it has the following features (not a complete list just the main ones):

  1. Client–server — The client handles the front end the server handles the backend and can both be replaced independently of each other.
  2. Stateless — No client data is stored on the server between requests and session state is stored on the client.
  3. Cacheable — Clients can cache response (just like browsers caching static elements of a web page) to improve performance.

Complying with these constraints, and thus conforming to the REST architectural style enables any kind of distributed hypermedia system to have desirable emergent properties, such as performance, scalability, simplicity, modifiability, visibility, portability, and reliability. A common trend I have seen is to use absolute urls for RESTful APIs which are meaningful.