TQ
dev.com

Blog about software development

Subscribe

Automatic REST API for Symfony 4

21 Apr 2019 - by 'Maurits van der Schee'

I'm writing a series of blog posts on how to integrate PHP-CRUD-API (a single PHP file that adds a REST API to your database) into popular PHP web frameworks. In this post we integrate the PHP-CRUD-API (2k stars) with the Symfony framework (20k stars). This is possible as they both adhere to the PHP-FIG's (PHP Framework Interop Group) HTTP standard PSR-7.

Install Symfony

You need to run the following commands on your Linux system:

wget https://getcomposer.org/composer.phar
php composer.phar create-project symfony/website-skeleton symfony-crud-api
cd symfony-crud-api
mv ../composer.phar .
php bin/console server:start

Now verify that the installation works by visiting:

http://127.0.0.1:8000

If you see the Symfony welcome page, then your configuration is okay.

Install PHP-CRUD-API

In order to add the automatic API library you need to run:

php composer.phar require symfony/psr-http-message-bridge
php composer.phar require mevdschee/php-crud-api

You now add a controller file "src/Controller/ApiController.php" with the following contents:

<?php

namespace App\Controller;

use Nyholm\Psr7\Factory\Psr17Factory;
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Tqdev\PhpCrudApi\Api;
use Tqdev\PhpCrudApi\Config;

class ApiController extends AbstractController
{
    /**
     * @Route("/api{params}", name="api_route", requirements={"params"=".+"})
     */
    public function index(Request $symfonyRequest): Response
    {
        // Convert the symfonyRequest to a psrRequest
        $psr17Factory = new Psr17Factory();
        $psrHttpFactory = new PsrHttpFactory($psr17Factory, $psr17Factory,
                                             $psr17Factory, $psr17Factory);
        $psrRequest = $psrHttpFactory->createRequest($symfonyRequest);

        // PHP-CRUD-API takes a psrRequest and generates a psrResponse
        $config = new Config([
            'username' => 'php-crud-api',
            'password' => 'php-crud-api',
            'database' => 'php-crud-api',
            'basePath' => '/api',
        ]);
        $api = new Api($config);
        $psrResponse = $api->handle($psrRequest);

        // Convert the psrResponse to a symfonyResponse
        $httpFoundationFactory = new HttpFoundationFactory();
        $symfonyResponse = $httpFoundationFactory->createResponse($psrResponse);

        return $symfonyResponse;
    }
}

Replace the string "php-crud-api" in the above code to match the username, password and database of your setup (preferably reading them from environment variables). You should see your application running at:

http://127.0.0.1:8000/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.

Further reading

Symfony 4 is often used to build APIs, because it is easy to use, standard compliant and light-weight. PHP-CRUD-API on the other hand saves you a lot of time, as it offers you a full featured REST API for all tables in your database without any coding (it uses reflection). Now that you can combine the two you can have the best of both worlds. For more information about PHP-CRUD-API and what you can do with it read the Github README at:

https://github.com/mevdschee/php-crud-api

For more information on Symfony go to:

https://symfony.com/

Other frameworks

Laravel and SlimPHP (alternatives for Symfony) can be integrated in a similar way. Read more:

Enjoy!


PS: Liked this article? Please share it on Facebook, Twitter or LinkedIn.