Installing REST Bundle

Installing REST Bundle

Requirements: PHP ^8.4, Symfony ^7.2 or ^8.0, cebe/php-openapi ^1.8 and ufo-tech/json-rpc-bundle: ^10.2.3 for 1.2, ^10.4.2 for 1.3 (not released yet).

The application must already run JsonRpcBundle: REST Bundle uses its method map, the ufo_json_rpc settings, security and translations.

Step 0: composer.json setup

For Symfony Flex to register the bundle and create the routes file automatically, add the UFO-Tech recipes repository to your composer.json (the same as for JsonRpcBundle):

{
    "extra" : {
        "symfony": {
            "endpoint": [
                "https://api.github.com/repos/ufo-tech/recipes/contents/index.json?ref=main",
                "flex://defaults"
            ]
        }
    }
}

Step 1: Installation

composer require ufo-tech/rest-bundle

Step 2: Registering the package

Make sure the bundle is registered in config/bundles.php after JsonRpcBundle:

return [
    // ...
    Ufo\JsonRpcBundle\UfoJsonRpcBundle::class => ['all' => true],
    Ufo\RestBundle\RestBundleBundle::class => ['all' => true],
];

Step 3: Registering routes

If you completed "Step 0", the file was created automatically and you can skip this step.

Add the file config/routes/ufo_rest_api.yaml (the template is in the package: install/routes/ufo_rest_api.yaml):

# config/routes/ufo_rest_api.yaml
ufo_rest_api:
    resource: ../../vendor/ufo-tech/rest-bundle/config/router.yaml
    prefix: /rest
    trailing_slash_on_root: false

prefix is the address of the REST entry point. Separate entry points for API groups are described in Routing.

The bundle has no configuration file of its own; see Configuration.

Step 4: The first REST method

Add the Symfony #[Route] attribute to a method of an existing RPC procedure:

use Symfony\Component\Routing\Attribute\Route;
use Ufo\JsonRpcBundle\ApiMethod\Interfaces\IRpcService;
use Ufo\RpcObject\RPC;

#[RPC\Info('catalog')]
#[Route('/catalog', name: 'catalog')]
class CatalogApi implements IRpcService
{
    #[Route('/items', name: 'list', methods: ['GET'])]
    public function list(int $page = 1): array
    {
        return ['page' => $page, 'items' => []];
    }
}

Verification

Request What it returns
GET /rest An OpenAPI 3.1 document
GET /rest/postman A Postman collection
GET /rest/catalog/items?page=2 The result of catalog.list
curl 'https://example.com/rest/catalog/items?page=2' \
  -H 'Ufo-RPC-Token: change-me'
{"page": 2, "items": []}

Casting "2" from the query to int appeared in 1.3; in 1.2 this request returns 400 (see Request parameters).

A token is required if protected_api: true is set in the JsonRpcBundle settings (the default). bin/console debug:router | grep ufo_rest shows the names of the generated routes.

What next?