How can create api Please let me know how?

https://book.cakephp.org/4/en/development/routing.html#resource-routes

also, how can i use the following things :

     $routes->scope('/api', function (RouteBuilder $builder) {
          // No $builder->applyMiddleware() here.
               // Parse specified extensions from URLs
          // $builder->setExtensions(['json', 'xml']);
              // Connect API actions here.
      });

and when use the following code ?

$routes->scope('/', function (RouteBuilder $routes) {
    $routes->setExtensions(['json']);
    $routes->resources('Recipes');
});

There are 2 main ways how you can “force” CakePHP to return e.g. a JSON instead of HTML:

  • Resource Routes (what you are referring to)
  • JSON View via Accept HTTP Header

What you are referring to is Resource Routes, so something like http://localhost/recipes.json
As you can see it has a .json at the end (what the documentation refers to as .format)
So by default http://localhost/recipes.json would call the index method of the RecipesController and return a json (because of the .json ending in the URL)
This does NOT require your client to send a Accept HTTP header.

For the second you may refer to https://book.cakephp.org/4/en/views/json-and-xml-views.html and how JSON views work.
JSON Views requires your client (maybe postman, maybe a browser) to add the

Accept: application/json

HTTP header so Cakephp knows it should return with a JSON body, not a HTML body.

It all depends on what kind of URL (and what kind of clients) you have and you want to serve data to.

1 Like