Installation
1. Create your api folder
2. Make sure you download the composer.phar file into the folder.
3. Open a shell script, cd to your new api folder and type
composer require slim/slim "^3.0"
//or
php composer.phar require slim/slim "^3.0"
Basic Setup and Routing
Now you should only see your composer.lock, composer.json and a vendor directory. Create index.php and place the following code inside.
get('/', function ($request, $response) {
return 'hello world';
});
$app->run();
Preview
Go back to the terminal and type
php -S localhost:8000
in the browser visit, http://localhost:8000/ you should see “hello world”
API calls with Slim
GET is used for reading and retrieving data.
POST is used for inserting data.
PUT is used for updating data.
DELETE is used for deleting data.
POST
get('/', function ($request, $response) {
return 'hello world';
});
$app->post('/postit', function ($request, $response) {
$input = $request->getParsedBody();
return $this->response->withJson($input);
});
$app->run();
You can then create a form but we will simulate a form post by using curl.
on the command line run
curl -d "param1=value1¶m2=value2" -X POST http://localhost:8000/postit
You should see
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 64 100 37 100 27 45 33 --:--:-- --:--:-- --:--:-- 78{"param1":"value1","param2":"value2"}