Unlike other architectures such as SOAP, REST APIs are usually lighter and less complex in their implementation. Its design is based on resources represented by unique URLs.
Project Structure
Our application will consist of several files that will manage the different parts of the code:
| File | Function |
|---|---|
| db.php | Managing connections to MySQL. |
| api.php | Main entry point for handling requests HTTP. |
| model.php | Business logic and database access. |
| index.php | Web client homepage (optional). |
Setting up the environment
Make sure you have a web server like Apache or Nginx set up along with PHP and MySQL. You can use solutions like XAMPP, WAMP, or LAMP depending on your operating system. Additionally, verify that you have correctly configured an IDE or text editor such as Visual Studio Code or Sublime Text to write your code.
Connecting to MySQL
Create a file called db.php. This file will be where we will establish the connection to our database:
<?php
$host = localhost;
$db = api_database;
$user = root;
$pass = ;
$charset = utf8mb4;
$dsn = \"mysql:host=$host;dbname=$db;charset=$charset\";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
?>
Creating the RESTful model
Create a file model.php. Here we will handle all interactions with our database. Make sure to include functions for each CRUD operation:
// Get all records
function getAllItems($pdo) {
$stmt = $pdo->query(SELECT * FROM items);
return $stmt->fetchAll();
}
// Additional functions to create, update, and delete records
?>
Handling requests with api.php
Our main file, api.php, will be responsible for handling incoming HTTP requests, directing them to the appropriate model for processing:
// Code to handle GET, POST, PUT, DELETE
// Based on the received HTTP verb, direct to the appropriate functions
?>
As you complete these stages, you will have a functional API using PHP and MySQL that follows RESTful principles. This not only improves code organization but also facilitates future expansion if you decide to integrate additional layers such as authentication or advanced validations.
Comments
0Be the first to comment