REST APIs are the backbone of modern web applications. In PHP, Slim Framework offers a lightweight and flexible way to build APIs quickly.
Setting up Slim
Install Slim using Composer and create a basic index.php file:
composer require slim/slim:"^4.0"
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
$app = AppFactory::create();
$app->get('/hello/{name}', function (Request $request, Response $response, $args) {
$response->getBody()->write("Hello " . htmlspecialchars($args['name']));
return $response;
});
$app->run();
Creating Resources
For a Posts API, you can define endpoints like:
- GET /posts – list all posts
- GET /posts/{id} – retrieve a single post
- POST /posts – create a new post
- PUT /posts/{id} – update a post
- DELETE /posts/{id} – delete a post
Data handling
Use PDO or an ORM to interact with the database. Always validate input and return proper HTTP status codes.
Conclusion
Slim makes RESTful APIs simple and clean. Coupled with proper routing and middleware, you can scale APIs efficiently.
Comentarios (3)
Slim is so easy to get started with, this guide is perfect for beginners!
Would love to see an example with JWT authentication next.
Great post!