Introduction
FastRoute makes it easy to build RESTful APIs by supporting all HTTP methods and allowing you to define multiple routes for the same URI with different methods.
CRUD Operations
Here’s an example of implementing CRUD operations for an API resource:
$r -> addRoute ( 'GET' , '/api/test' , 'test_get' );
$r -> addRoute ( 'POST' , '/api/test' , 'test_post' );
$r -> addRoute ( 'GET' , '/api/items' , 'items_get' );
$r -> addRoute ( 'POST' , '/api/items' , 'items_post' );
$r -> addRoute ( 'GET' , '/api/items/1' , 'item_get_1' );
Handler Functions
Each route references a handler function that processes the request:
GET Handler
POST Handler
List Items
Create Item
function test_get () {
echo json_encode ([ "message" => "This is the test route (GET)" ]);
}
Complete REST API Example
Here’s a complete example showing a RESTful API implementation:
<? php
use FastRoute\ RouteCollector ;
return function ( RouteCollector $r ) {
// GET: Retrieve all items
$r -> addRoute ( 'GET' , '/api/items' , 'items_get' );
// POST: Create a new item
$r -> addRoute ( 'POST' , '/api/items' , 'items_post' );
// GET: Retrieve a specific item
$r -> addRoute ( 'GET' , '/api/items/1' , 'item_get_1' );
};
For API routes, set the appropriate content type header:
if ( strpos ( $uri , '/api/' ) === 0 ) {
header ( 'Content-Type: application/json; charset=utf-8' );
} else {
header ( 'Content-Type: text/html; charset=utf-8' );
}
Route Groups
Organize related API routes using groups:
$r -> addGroup ( '/api/projects' , function ( FastRoute\ RouteCollector $r ) use ( $obj ) {
$r -> get ( '/testing/test' , function () use ( $obj ) {
$obj -> hello ();
});
$r -> get ( "/" , function () use ( $obj ) {
$obj -> display ( 1 );
});
});
$r -> addGroup ( '/api/tasks' , function ( FastRoute\ RouteCollector $r ) use ( $obj ) {
$r -> get ( "/" , function () use ( $obj ) {
$obj -> display ( 2 );
});
});
Route groups automatically prefix all routes within the group, making it easy to organize your API endpoints.
Best Practices
Use HTTP Methods Use appropriate HTTP methods (GET, POST, PUT, DELETE) for different operations
JSON Responses Always return JSON responses for API endpoints
Group Related Routes Use route groups to organize related endpoints
Handle Input Parse request body using file_get_contents('php://input')
Next Steps
Dynamic Parameters Add dynamic parameters to your routes
HTTP Methods Learn about all available HTTP methods