Home > Article > Backend Development > How to create a RESTful API using PHP and SQLite
How to create a RESTful API using PHP and SQLite
Introduction:
In today's development, RESTful API has become an increasingly popular interface design style. It uses simple HTTP verbs (GET, POST, DELETE, etc.) to operate resources, making it easy for data interaction between different applications. In this article, we will learn how to create a basic RESTful API using PHP and SQLite.
Step One: Install PHP and SQLite
Before we begin, we need to make sure that PHP and SQLite have been installed. If it is not installed yet, you can install it by:
Step 2: Create a database
After installing PHP and SQLite, we need to create a SQLite database file. Databases can be created using the command line or SQLite management tools. The following is an example of creating a database using the command line:
$ sqlite3 mydatabase.db
This will create a database file named mydatabase.db in the current directory.
Step 3: Create a data table
Next, we need to create a data table to store the resources operated by the API. The following is a simple example, we create a table named "products" to store product information:
$database = new SQLite3('mydatabase.db'); $table = "CREATE TABLE IF NOT EXISTS products ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, price REAL NOT NULL )"; $database->exec($table);
This will create a data table named "products" in the database, containing id, name and Price has three columns.
Step 4: Create API routing
In order for the API to respond to different HTTP requests, we need to create a router to dispatch the requests. Here is a simple example:
class Router { private $routes = []; public function register($method, $path, $callback) { $this->routes[] = [ 'method' => $method, 'path' => $path, 'callback' => $callback ]; } public function handleRequest() { $method = $_SERVER['REQUEST_METHOD']; $path = $_SERVER['PATH_INFO']; foreach ($this->routes as $route) { if ($route['method'] == $method && $route['path'] == $path) { call_user_func($route['callback']); return; } } http_response_code(404); echo "Not Found"; } }
This router class allows us to register different routes and call the corresponding callback function when the request arrives.
Step 5: Implement the CRUD operations of the API
Next, we will implement the CRUD operations of the API (create, read, update and delete). The following is an example:
$router = new Router(); $router->register('GET', '/products', function() { $database = new SQLite3('mydatabase.db'); $results = $database->query("SELECT * FROM products"); $data = []; while ($row = $results->fetchArray()) { $data[] = [ 'id' => $row['id'], 'name' => $row['name'], 'price' => $row['price'] ]; } echo json_encode($data); }); $router->register('POST', '/products', function() { $data = json_decode(file_get_contents('php://input'), true); $name = $data['name']; $price = $data['price']; $database = new SQLite3('mydatabase.db'); $database->exec("INSERT INTO products (name, price) VALUES ('$name', $price)"); $lastInsertId = $database->lastInsertRowID(); echo json_encode(['id' => $lastInsertId]); }); // 同样的方式,我们可以实现PUT和DELETE方法来更新和删除产品信息。 $router->handleRequest();
The above example code implements basic CRUD operations on product resources. The GET request will return a JSON array of all product information, and the POST request will create a new product and return the new product's ID.
Summary:
Through the above steps, we have successfully created a simple RESTful API based on PHP and SQLite. Through router and database operations, we can perform common CRUD operations. Of course, this is just a starting point and we can further develop and optimize it based on actual needs. I hope this article will be helpful to learn and practice RESTful API.
The above is the detailed content of How to create a RESTful API using PHP and SQLite. For more information, please follow other related articles on the PHP Chinese website!