In this tutorial, I'll teach you how to build a simple REST API with PHP and MySQL.
REST has become the de facto standard when it comes to exposing data via APIs and building web services. In fact, most web applications these days access and expose data via REST APIs. With the popularity of front-end frameworks that can consume REST APIs effortlessly, it’s always going to be a plus for you if your web application exposes REST APIs.
In this article, we’ll build a simple demo application, which allows you to fetch a list of users from the MySQL database via a REST endpoint.
Setting Up the Skeleton
In this section, we’ll briefly go through the project structure.
Let’s have a look at the following structure.
├── Controller │ └── Api │ ├── BaseController.php │ └── UserController.php ├── inc │ ├── bootstrap.php │ └── config.php ├── index.php └── Model ├── Database.php └── UserModel.php
Let’s try to understand the project structure.
- index.php: the entry-point of our application. It will act as a front-controller of our application.
- inc/config.php: holds the configuration information of our application. Mainly, it will hold the database credentials.
- inc/bootstrap.php: used to bootstrap our application by including the necessary files.
- Model/Database.php: the database access layer which will be used to interact with the underlying MySQL database.
-
Model/UserModel.php: the
User
model file which implements the necessary methods to interact with the users table in the MySQL database. - Controller/Api/BaseController.php: a base controller file which holds common utility methods.
- Controller/Api/UserController.php: the
User
controller file which holds the necessary application code to entertain REST API calls.
So that’s the basic setup that we are going to implement in the rest of the post.
Create a Database and Model Classes
In this section, we’ll create a database and the users table. We’ll also create the necessary model classes that will be used to fetch users from a database.
Create a Database and the Users Table
Create the rest_api_demo
database by executing the following command in your MySQL terminal. [Access this with the command mysql
from the command line.]
$CREATE DATABASE rest_api_demo;
You could also use a tool like phpMyAdmin if you prefer working with your databases that way.
Once the rest_api_demo
database is created, go ahead and create the users
table by running the following statements.
$use rest_api_demo; $CREATE TABLE `users` [ `user_id` bigint[20] unsigned NOT NULL AUTO_INCREMENT, `username` varchar[60] COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `user_email` varchar[100] COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '', `user_status` int[11] NOT NULL DEFAULT '0', PRIMARY KEY [`user_id`] ] ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
That should create the users
table in the rest_api_demo
database. You will also want to populate this table with a few dummy records for testing purposes. Insert a few records, and you’re good to go!
Create Model Classes
In this section, we’ll create the necessary model classes.
Create the Model/Database.php file with the following contents.
Firstly, we’ve initialized the PROJECT_ROOT_PATH
constant with the directory root of our application. In this way, we could use the PROJECT_ROOT_PATH
constant to prepare absolute paths in our application. Next, we’ve included the config.php file, which holds the database connection information. Finally, we've included controller and model files.
So that’s it for setting up the common files in our application.
The Controller Directory
In this section, we’ll implement controllers that hold the majority of our application logic.
The BaseController.php File
Create the
Controller/Api/BaseController.php file with the following contents. The BaseController
class contains the utility methods that are used by other controllers.
Firstly, we’ve used parse_url
and explode
functions to initialize URI segments into the $uri
array variable. Next, we’re validating the URI segments. Finally, we’ve initialized the UserController
controller and called the corresponding action method.
With that, we’ve created all the necessary files in our demo REST application. In the next section, we’ll see how to call it from the end-user perspective.
How to Call Our REST API
In this section, we’ll see how to call our demo application. In our application, we’ve built a REST endpoint to get a list of users.
Let’s see how the URL of our endpoint looks:
// //localhost/index.php/{MODULE_NAME}/{METHOD_NAME}?limit={LIMIT_VALUE} //localhost/index.php/user/list?limit=20
If you recall the index.php file, we checked if the $uri[2]
variable is set to user
. Also, the $uri[3]
variable value would act as a method name. In the above case, the
$uri[3]
variable is set to list
. Thus, it would end up calling the listAction
method of the UserController
class.
The output should look like this:
[ { "user_id":1, "username":"Bob", "user_email":"", "user_status":0 }, { "user_id":2, "username":"John", "user_email":"", "user_status":1 }, { "user_id":3, "username":"Mark", "user_email":"", "user_status":1 }, { "user_id":4, "username":"Ville", "user_email":"", "user_status":0 } ]
As you can see, it returns a list of users as a JSON object. Apart from that, if there’s any application error, it would be returned as a JSON object as well for debugging purposes.
Conclusion
Today, we discussed how you can build a REST application with PHP and MySQL. For demonstration purposes, we created a demo application which allows you to fetch a list of users from a MySQL database via a REST API.
Did you find this post useful?
Software Engineer, FSPL, India
I'm a software engineer by profession, and I've done my engineering in computer science. It's been around 14 years I've been working in the field of website development and open-source technologies. Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I've worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I've also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce. I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore [India] and 2018 DrupalCon which was held in Mumbai [India]. Apart from this, I like to travel, explore new places, and listen to music!