Creating a RESTful API resource in CakePHP 4

in CakePHP


CakePHP lets you convert a controller into a RESTful API resource. We will use a prefixed (in other words, namespaced) controller to prevent cluttering your main controller for that given resource.

Using $routes->setExtensions(['json']); tells the framework to parse the .json extension in the URL. Otherwise it will think it's a part of the method name.

CakePHP 4

  1. Create a prefix in config/routes.php:

    $routes->prefix('Api', function (RouteBuilder $routes) {
        $routes->setExtensions(['json']);
        $routes->fallbacks(DashedRoute::class);
    });
  2. Create src/Controller/Api/AppController.php:

    viewBuilder()->setOption('serialize', true);
        }
    
    }
  3. Create your resource controller, say src/Controller/Api/PostsController.php:

    set([
                'foo' => 'bar',
            ]);
        }
    
    }
  4. Optional: Configure your API scope in config/routes.php:

    $routes->scope('/api', function (RouteBuilder $builder) {
        $builder->setRouteClass(DashedRoute::class);
        $builder->setExtensions(['json']);
        $builder->resources('Events', [
            'prefix' => 'Api',
        ]);
    });

CakePHP 5

  1. Create a prefix in config/routes.php:

    $routes->prefix('Api', function (RouteBuilder $routes) {
        $routes->setExtensions(['json']);
        $routes->fallbacks(DashedRoute::class);
    });
  2. Create src/Controller/Api/AppController.php:

    addViewClasses([\Cake\View\JsonView::class]);
            $this->viewBuilder()->setOption('serialize', true);
        }
    
    }
  3. Create your resource controller, say src/Controller/Api/PostsController.php:

    set([
                'foo' => 'bar',
            ]);
        }
    
    }

Try accessing your resource at example.com/api/posts/hello.json.

If something doesn't work right away, always run bin/cake cache clear_all before you spend hours investigating.

#cakephp #api #rest