26 Sep 2019 - by 'Maurits van der Schee'
Last month we showed how to use PHP-CRUD-API (2k stars) as a library executed on an endpoint in the SlimPHP 4 framework (10k stars). In the previous post we used the recommended way to set up a SlimPHP 4 project and in this post we take a minimal approach (using as little code as possible).
We download composer and use it to install the two projects:
wget https://getcomposer.org/composer.phar
php composer.phar require slim/slim:^4
php composer.phar require mevdschee/php-crud-api
This is all that is needed.
Now add the following code to a file named index.php
:
<?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; use \Tqdev\PhpCrudApi\Config; use \Tqdev\PhpCrudApi\Api; require __DIR__ . '/vendor/autoload.php'; // Instantiate App $app = AppFactory::create(); // Add this handler for PHP-CRUD-API: $app->any('/api[/{params:.*}]', function (Request $request, Response $response) { $config = new Config([ 'username' => 'php-crud-api', 'password' => 'php-crud-api', 'database' => 'php-crud-api', 'basePath' => '/api', ]); $api = new Api($config); $response = $api->handle($request); return $response; }); $app->run();
And run it using the following command:
php -S localhost:8080
You should be able to see the API running at:
http://localhost:8080/api/records/posts
Replace "posts" with the name of any table in your database. If everything works as expected, then you should see the contents of the table in JSON format.
You can find the code on Github:
https://github.com/mevdschee/slim-crud-api
PS: Liked this article? Please share it on Facebook, Twitter or LinkedIn.