World is getting interconnected. No single application can do all the computation. However, solutions need to interact and bank upon each other’s strength. For example, while designing a software solution you may need tax calculation from another application. Such integrations not only increase the overall efficiency of the solution but also eliminate manual effort and chances for errors.
While we have many integration protocols such as SOAP, XML-RPC, JSON and many more, REST is increasingly being used due to their architectural superiority. Since PHP contributes to about 78% of the world web developments, in this article we will see how to create a custom REST API in PHP which can then be used by third party application to consume.
REST API
Rest API is a Representational State Transfer API. It is an architectural design which is most widely used to communicate with the exposed functions of the Applications. Since Rest is a stateless component, each request should have considerable information to process the requested data in the Application. Rest API exchanges data in the form of JavaScript Object Notation (JSON) format.
Due to stateless data transmission, lightweight and easily modifiable structure, most of the small applications to the enterprise applications are using REST API as their primary source of communication across different applications.
Rest API in PHP
For a better understanding of the Rest API in PHP, let’s take an example of user management. In this application, an external client/application will have the access to create, update, read and delete the user.
Below is the folder and file structure –
UserController.php – This is an exposed file which will be used by the other application to communicate with the User Management Application.
UserModel.php – This file helps us to process the business logic and interact with the storage applications like MySQL, MSSQL, Oracle SQL, etc.
How to create a controller
Create a UserController.php file under api folder and place below code in the file
- Adding a header line will let the external application know that the response will be JSON.
- Type of HTTP request and Request data are assigned in the constructor
- Execute method checks the type of request and calls the respective action to complete the request
- If an unknown HTTP method is used, then the ‘Method Not Available’ error code is sent back
- If the requested data is not processed then ‘Bad Request Data’ error code is thrown
<?php header('Content-type:application/json'); include_once '../model/UserModel.php'; class UserController { private $_request_type; private $_request_body; public function __construct() { $this->_request_type = $_SERVER['REQUEST_METHOD']; $this->_request_body = file_get_contents('php://input'); if (!empty($this->_request_body)) { // Decode the json string from the request to Array $this->_request_body = json_decode($this->_request_body, true); } $this->model = new UserModel(); } public function execute() { $status = false; $response = []; switch ($this->_request_type) { case 'PUT': // HTTP PUT method request will be used to create a new user list($status, $response) = $this->createUser(); break; case 'POST': // HTTP POST method will be used the update the data for the requested user id list($status, $response) = $this->updateUser(); break; case 'DELETE': // HTTP DELETE method will delete the user list($status, $response) = $this->deleteUser(); break; case 'GET': // HTTP GET method will fetch the user details list($status, $response) = $this->getUser(); break; default: // Throw 'method not available' response for methods Other than PUT, POST, DELETE, GET http_response_code(405); return; } if ($status) { echo json_encode($response); // Success response http_response_code(200); } else { // Based on the response, response codes can be changed. // For now always a Bad request error is thrown http_response_code(400); } } private function createUser(): array { $data = $this->model->create($this->_request_body); if (!empty($data)) { return [true, $data]; } return [false, []]; } private function updateUser(): array { $data = $this->model->update($this->_request_body); if (!empty($data)) { return [true, $data]; } return [false, []]; } private function deleteUser(): array { $data = $this->model->delete($this->_request_body['id']); if ($data) { return [true, []]; } return [false, []]; } private function getUser(): array { $data = $this->model->get($this->_request_body); if (!empty($data)) { return [true, $data]; } return [false, []]; } } (new UserController())->execute();
How to create a model
Create the model file as in the file structure.
- Model interacts with storage applications like MySQL, MSSQL, etc
- Model can also hold the business logic
- Each method holds a purpose of making the changes in the database.
- Create method – Creates the new user based on the requested data
- Update Method – Updates the data for the particular user
- Get Method – Fetches the user data for given user id
- Delete Method – Deletes the user for the given user id
<?php class UserModel { /** * Create a new user * * @param [array] $data * @return void */ public function create($data): array { $createdUserData = []; $id = uniqid(); $createdUserData['id'] = $id; $createdUserData['user_name'] = $data['user_name']; $createdUserData['email'] = $data['email']; // logic to create the user return $createdUserData; } /** * update the data of the user for the given id * * @param [string] $id * @param [array] $data * @return void */ public function update($id, $data): array { $updatedUserData = []; $updatedUserData['id'] = $id; $updatedUserData['user_name'] = $data['user_name']; $updatedUserData['email'] = $data['email']; // logic to update the user return $updatedUserData; } /** * Fetch the user data * * @param [string] $id * @return void */ public function get($id): array { $data = []; // Check if id is not empty if (!isset($id) || empty($id)) { return $data; } // logic to fetch the data based on the id return $data; } /** * Delete the user * * @param [string] $id * @return boolean */ public function delete($id): bool { // Check if id is not empty if (!isset($id) || empty($id)) { return false; } // logic to delete the user based on id return true; } }
How to call the API from an external application
You can use any RESTful client or can write a script in any of your preferred language to use the API. However for the scope of this article we will use the POSTMAN as a REST client to our REST API script.
Using our API we will create a user in the User management Application. Please find the screenshot with request and response for creating the user.
In the same way, the user can be updated, deleted and fetched. Further validation and depth to implementation can be added to the code, based upon the requirement.
Rest API is easily implemented in any application. REST can be integrated with Oauth-Tokens which makes the API more secure in communicating with applications. Due to the JSON data structure, any change in the structure can be easily handled in the application.
Evaluating SugarCRM for your business – We can help
Reach out to us so that we can assess and plan a road-map for your CRM implementation. Let’s build a system, which you will use for years to come.